diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..55c2978 --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +src/main/resources/banner.txt diff --git a/README.md b/README.md index bbd16ed..aa63ea5 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,7 @@ -# Mieriki_test +# ACG测试系统前端 +## 成员 +- 杨旭蕊 +- 李泽辰 +- 陈冶 +- 吴亚楠 diff --git a/index.html b/index.html new file mode 100644 index 0000000..030a6ff --- /dev/null +++ b/index.html @@ -0,0 +1,13 @@ + + + + + + + Vite App + + +
+ + + diff --git a/node_modules/.bin/cssesc b/node_modules/.bin/cssesc new file mode 100644 index 0000000..c9b5214 --- /dev/null +++ b/node_modules/.bin/cssesc @@ -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/../cssesc/bin/cssesc" "$@" +else + exec node "$basedir/../cssesc/bin/cssesc" "$@" +fi diff --git a/node_modules/.bin/cssesc.cmd b/node_modules/.bin/cssesc.cmd new file mode 100644 index 0000000..b560b42 --- /dev/null +++ b/node_modules/.bin/cssesc.cmd @@ -0,0 +1,17 @@ +@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%\..\cssesc\bin\cssesc" %* diff --git a/node_modules/.bin/cssesc.ps1 b/node_modules/.bin/cssesc.ps1 new file mode 100644 index 0000000..480aa17 --- /dev/null +++ b/node_modules/.bin/cssesc.ps1 @@ -0,0 +1,28 @@ +#!/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/../cssesc/bin/cssesc" $args + } else { + & "$basedir/node$exe" "$basedir/../cssesc/bin/cssesc" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../cssesc/bin/cssesc" $args + } else { + & "node$exe" "$basedir/../cssesc/bin/cssesc" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/esbuild b/node_modules/.bin/esbuild new file mode 100644 index 0000000..26bef54 --- /dev/null +++ b/node_modules/.bin/esbuild @@ -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/../esbuild/bin/esbuild" "$@" +else + exec node "$basedir/../esbuild/bin/esbuild" "$@" +fi diff --git a/node_modules/.bin/esbuild.cmd b/node_modules/.bin/esbuild.cmd new file mode 100644 index 0000000..cc920c5 --- /dev/null +++ b/node_modules/.bin/esbuild.cmd @@ -0,0 +1,17 @@ +@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%\..\esbuild\bin\esbuild" %* diff --git a/node_modules/.bin/esbuild.ps1 b/node_modules/.bin/esbuild.ps1 new file mode 100644 index 0000000..81ffbf9 --- /dev/null +++ b/node_modules/.bin/esbuild.ps1 @@ -0,0 +1,28 @@ +#!/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/../esbuild/bin/esbuild" $args + } else { + & "$basedir/node$exe" "$basedir/../esbuild/bin/esbuild" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../esbuild/bin/esbuild" $args + } else { + & "node$exe" "$basedir/../esbuild/bin/esbuild" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/json5 b/node_modules/.bin/json5 new file mode 100644 index 0000000..977b750 --- /dev/null +++ b/node_modules/.bin/json5 @@ -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/../json5/lib/cli.js" "$@" +else + exec node "$basedir/../json5/lib/cli.js" "$@" +fi diff --git a/node_modules/.bin/json5.cmd b/node_modules/.bin/json5.cmd new file mode 100644 index 0000000..95c137f --- /dev/null +++ b/node_modules/.bin/json5.cmd @@ -0,0 +1,17 @@ +@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%\..\json5\lib\cli.js" %* diff --git a/node_modules/.bin/json5.ps1 b/node_modules/.bin/json5.ps1 new file mode 100644 index 0000000..8700ddb --- /dev/null +++ b/node_modules/.bin/json5.ps1 @@ -0,0 +1,28 @@ +#!/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/../json5/lib/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../json5/lib/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../json5/lib/cli.js" $args + } else { + & "node$exe" "$basedir/../json5/lib/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/nanoid b/node_modules/.bin/nanoid new file mode 100644 index 0000000..23254eb --- /dev/null +++ b/node_modules/.bin/nanoid @@ -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/../nanoid/bin/nanoid.cjs" "$@" +else + exec node "$basedir/../nanoid/bin/nanoid.cjs" "$@" +fi diff --git a/node_modules/.bin/nanoid.cmd b/node_modules/.bin/nanoid.cmd new file mode 100644 index 0000000..9c40107 --- /dev/null +++ b/node_modules/.bin/nanoid.cmd @@ -0,0 +1,17 @@ +@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 new file mode 100644 index 0000000..d8a4d7a --- /dev/null +++ b/node_modules/.bin/nanoid.ps1 @@ -0,0 +1,28 @@ +#!/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/parser b/node_modules/.bin/parser new file mode 100644 index 0000000..cb5b10d --- /dev/null +++ b/node_modules/.bin/parser @@ -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/../@babel/parser/bin/babel-parser.js" "$@" +else + exec node "$basedir/../@babel/parser/bin/babel-parser.js" "$@" +fi diff --git a/node_modules/.bin/parser.cmd b/node_modules/.bin/parser.cmd new file mode 100644 index 0000000..1ad5c81 --- /dev/null +++ b/node_modules/.bin/parser.cmd @@ -0,0 +1,17 @@ +@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%\..\@babel\parser\bin\babel-parser.js" %* diff --git a/node_modules/.bin/parser.ps1 b/node_modules/.bin/parser.ps1 new file mode 100644 index 0000000..8926517 --- /dev/null +++ b/node_modules/.bin/parser.ps1 @@ -0,0 +1,28 @@ +#!/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/../@babel/parser/bin/babel-parser.js" $args + } else { + & "$basedir/node$exe" "$basedir/../@babel/parser/bin/babel-parser.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../@babel/parser/bin/babel-parser.js" $args + } else { + & "node$exe" "$basedir/../@babel/parser/bin/babel-parser.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/rollup b/node_modules/.bin/rollup new file mode 100644 index 0000000..11bd86d --- /dev/null +++ b/node_modules/.bin/rollup @@ -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/../rollup/dist/bin/rollup" "$@" +else + exec node "$basedir/../rollup/dist/bin/rollup" "$@" +fi diff --git a/node_modules/.bin/rollup.cmd b/node_modules/.bin/rollup.cmd new file mode 100644 index 0000000..b3f110b --- /dev/null +++ b/node_modules/.bin/rollup.cmd @@ -0,0 +1,17 @@ +@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%\..\rollup\dist\bin\rollup" %* diff --git a/node_modules/.bin/rollup.ps1 b/node_modules/.bin/rollup.ps1 new file mode 100644 index 0000000..10f657d --- /dev/null +++ b/node_modules/.bin/rollup.ps1 @@ -0,0 +1,28 @@ +#!/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/../rollup/dist/bin/rollup" $args + } else { + & "$basedir/node$exe" "$basedir/../rollup/dist/bin/rollup" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../rollup/dist/bin/rollup" $args + } else { + & "node$exe" "$basedir/../rollup/dist/bin/rollup" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/vite b/node_modules/.bin/vite new file mode 100644 index 0000000..a85d325 --- /dev/null +++ b/node_modules/.bin/vite @@ -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/../vite/bin/vite.js" "$@" +else + exec node "$basedir/../vite/bin/vite.js" "$@" +fi diff --git a/node_modules/.bin/vite.cmd b/node_modules/.bin/vite.cmd new file mode 100644 index 0000000..f62e966 --- /dev/null +++ b/node_modules/.bin/vite.cmd @@ -0,0 +1,17 @@ +@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%\..\vite\bin\vite.js" %* diff --git a/node_modules/.bin/vite.ps1 b/node_modules/.bin/vite.ps1 new file mode 100644 index 0000000..a7759bc --- /dev/null +++ b/node_modules/.bin/vite.ps1 @@ -0,0 +1,28 @@ +#!/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/../vite/bin/vite.js" $args + } else { + & "$basedir/node$exe" "$basedir/../vite/bin/vite.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../vite/bin/vite.js" $args + } else { + & "node$exe" "$basedir/../vite/bin/vite.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..1cf8e09 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,602 @@ +{ + "name": "vue3_cli_default", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@babel/helper-validator-identifier": { + "version": "7.14.9", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.9.tgz", + "integrity": "sha512-pQYxPY0UP6IHISRitNe8bsijHex4TWZXi2HwKVsjPiltzlhse2znVcm9Ace510VT1kxIHjGJCZZQBX2gJDbo0g==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.15.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.15.4.tgz", + "integrity": "sha512-xmzz+7fRpjrvDUj+GV7zfz/R3gSK2cOxGlazaXooxspCr539cbTXJKvBJzSVI2pPhcRGquoOtaIkKCsHQUiO3w==", + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.15.4", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.15.4.tgz", + "integrity": "sha512-0f1HJFuGmmbrKTCZtbm3cU+b/AqdEYk5toj5iQur58xkVMlS0JWaKxTBSmCXd47uiN7vbcozAupm6Mvs80GNhw==", + "dependencies": { + "@babel/helper-validator-identifier": "^7.14.9", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@types/estree": { + "version": "0.0.48", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.48.tgz", + "integrity": "sha512-LfZwXoGUDo0C3me81HXgkBg5CTQYb6xzEl+fNmbO4JdRiSKQ8A0GD1OBBvKAIsbCUgoyAty7m99GqqMQe784ew==", + "dev": true + }, + "node_modules/@vitejs/plugin-vue": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-1.6.0.tgz", + "integrity": "sha512-n3i8htn8pTg9M+kM3cnEfsPZx/6ngInlTroth6fA1LQTJq5aTVQ8ggaE5pPoAy9vCgHPtcaXMzwpldhqRAkebQ==", + "dev": true, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "@vue/compiler-sfc": "^3.2.6" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.2.8.tgz", + "integrity": "sha512-Sx8qJ030+QM/NakUrkQuUGCeDEb+0d0AgFOl5W4qRvR6e+YgLnW2ew0jREf4T1hak9Fdk8Edl67StECHrhEuew==", + "dependencies": { + "@babel/parser": "^7.15.0", + "@babel/types": "^7.15.0", + "@vue/shared": "3.2.8", + "estree-walker": "^2.0.2", + "source-map": "^0.6.1" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.2.8.tgz", + "integrity": "sha512-nxBW6k8FMWQ74294CRbqR+iEJRO5vIjx85I3YCOyZFD6FsDHyFL60g76TcJzucp+F2XXIDaYz+A+F4gQlDatjw==", + "dependencies": { + "@vue/compiler-core": "3.2.8", + "@vue/shared": "3.2.8" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.2.8.tgz", + "integrity": "sha512-XClueQAXoWtN2EToKgfYH9FCL70Ac4bxx6OZFZzxYSg1bei8IB9srJP1UOfnJb2IpnM1heikAz1dp1HI1wHcyQ==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.15.0", + "@babel/types": "^7.15.0", + "@types/estree": "^0.0.48", + "@vue/compiler-core": "3.2.8", + "@vue/compiler-dom": "3.2.8", + "@vue/compiler-ssr": "3.2.8", + "@vue/ref-transform": "3.2.8", + "@vue/shared": "3.2.8", + "consolidate": "^0.16.0", + "estree-walker": "^2.0.2", + "hash-sum": "^2.0.0", + "lru-cache": "^5.1.1", + "magic-string": "^0.25.7", + "merge-source-map": "^1.1.0", + "postcss": "^8.1.10", + "postcss-modules": "^4.0.0", + "postcss-selector-parser": "^6.0.4", + "source-map": "^0.6.1" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.2.8.tgz", + "integrity": "sha512-QqyiFRiIl55W0abDNQ6cNG/7iIfBHmbXVtssUAjX3IlI87ELeT0xackmrCyTSnfIX12ixljg9AN0COIZwlvt5A==", + "dev": true, + "dependencies": { + "@vue/compiler-dom": "3.2.8", + "@vue/shared": "3.2.8" + } + }, + "node_modules/@vue/reactivity": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.2.8.tgz", + "integrity": "sha512-/Hj3Uz28SG+xB5SDWPOXUs0emvHkq82EmTgk44/plTVFeswCZ3i3Hd7WmsrPT4rGajlDKd5uqMmW0ith1ED0FA==", + "dependencies": { + "@vue/shared": "3.2.8" + } + }, + "node_modules/@vue/ref-transform": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@vue/ref-transform/-/ref-transform-3.2.8.tgz", + "integrity": "sha512-9LdADd4JM3klt+b2qNT8a7b7JvBETNBy2Btv5rDzyPrAVS4Vrw+1WWay6gZBgnxfJ9TPSvG8f/9zu6gNGHmJLA==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.15.0", + "@vue/compiler-core": "3.2.8", + "@vue/shared": "3.2.8", + "estree-walker": "^2.0.2", + "magic-string": "^0.25.7" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.2.8.tgz", + "integrity": "sha512-hwzXLGw1njBEY5JSyRXIIdCtzMFFF6F38WcKMmoIE3p7da30jEbWt8EwwrBomjT8ZbqzElOGlewBcnXNOiiIUg==", + "dependencies": { + "@vue/reactivity": "3.2.8", + "@vue/shared": "3.2.8" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.2.8.tgz", + "integrity": "sha512-A/aRrlGLJ5y4Z7eNbnO/xHwx2RiPijQo7D3OIwESroG3HNP+dpuoqamajo5TXS9ZGjbMOih82COoe7xb9P4BZw==", + "dependencies": { + "@vue/runtime-core": "3.2.8", + "@vue/shared": "3.2.8", + "csstype": "^2.6.8" + } + }, + "node_modules/@vue/shared": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.2.8.tgz", + "integrity": "sha512-E2DQQnG7Qr4GwTs3GlfPPlHliGVADoufTnhpwfoViw7JlyLMmYtjfnTwM6nXAwvSJWiF7D+7AxpnWBBT3VWo6Q==" + }, + "node_modules/big.js": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", + "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", + "dev": true + }, + "node_modules/colorette": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.3.0.tgz", + "integrity": "sha512-ecORCqbSFP7Wm8Y6lyqMJjexBQqXSF7SSeaTyGGphogUjBlFP9m9o08wy86HL2uB7fMTxtOUzLMk7ogKcxMg1w==", + "dev": true + }, + "node_modules/consolidate": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/consolidate/-/consolidate-0.16.0.tgz", + "integrity": "sha512-Nhl1wzCslqXYTJVDyJCu3ODohy9OfBMB5uD2BiBTzd7w+QY0lBzafkR8y8755yMYHAaMD4NuzbAw03/xzfw+eQ==", + "dev": true, + "dependencies": { + "bluebird": "^3.7.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/csstype": { + "version": "2.6.17", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-2.6.17.tgz", + "integrity": "sha512-u1wmTI1jJGzCJzWndZo8mk4wnPTZd1eOIYTYvuEyOQGfmDl3TrabCCfKnOC86FZwW/9djqTl933UF/cS425i9A==" + }, + "node_modules/emojis-list": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-3.0.0.tgz", + "integrity": "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/esbuild": { + "version": "0.12.25", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.12.25.tgz", + "integrity": "sha512-woie0PosbRSoN8gQytrdCzUbS2ByKgO8nD1xCZkEup3D9q92miCze4PqEI9TZDYAuwn6CruEnQpJxgTRWdooAg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "node_modules/generic-names": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generic-names/-/generic-names-2.0.1.tgz", + "integrity": "sha512-kPCHWa1m9wGG/OwQpeweTwM/PYiQLrUIxXbt/P4Nic3LbGjCP0YwrALHW1uNLKZ0LIMg+RF+XRlj2ekT9ZlZAQ==", + "dev": true, + "dependencies": { + "loader-utils": "^1.1.0" + } + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/hash-sum": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/hash-sum/-/hash-sum-2.0.0.tgz", + "integrity": "sha512-WdZTbAByD+pHfl/g9QSsBIIwy8IT+EsPiKDs0KNX+zSHhdDLFKdZu0BQHljvO+0QI/BasbMSUa8wYNCZTvhslg==", + "dev": true + }, + "node_modules/icss-replace-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/icss-replace-symbols/-/icss-replace-symbols-1.1.0.tgz", + "integrity": "sha1-Bupvg2ead0njhs/h/oEq5dsiPe0=", + "dev": true + }, + "node_modules/icss-utils": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-5.1.0.tgz", + "integrity": "sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==", + "dev": true, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/is-core-module": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.6.0.tgz", + "integrity": "sha512-wShG8vs60jKfPWpF2KZRaAtvt3a20OAn7+IJ6hLPECpSABLcKtFKTTI4ZtH5QcBruBHlq+WsdHWyz0BCZW7svQ==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "dev": true, + "dependencies": { + "minimist": "^1.2.0" + }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/loader-utils": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.0.tgz", + "integrity": "sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==", + "dev": true, + "dependencies": { + "big.js": "^5.2.2", + "emojis-list": "^3.0.0", + "json5": "^1.0.1" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", + "dev": true + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/magic-string": { + "version": "0.25.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz", + "integrity": "sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.4" + } + }, + "node_modules/merge-source-map": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/merge-source-map/-/merge-source-map-1.1.0.tgz", + "integrity": "sha512-Qkcp7P2ygktpMPh2mCQZaf3jhN6D3Z/qVZHSdWvQ+2Ef5HgRAPBO57A77+ENm0CPx2+1Ce/MYKi3ymqdfuqibw==", + "dev": true, + "dependencies": { + "source-map": "^0.6.1" + } + }, + "node_modules/minimist": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "dev": true + }, + "node_modules/nanoid": { + "version": "3.1.25", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.25.tgz", + "integrity": "sha512-rdwtIXaXCLFAQbnfqDRnI6jaRHp9fTcYBjtFKE8eezcZ7LuLjhUaQGNeMXf1HmRoCH32CLz6XwX0TtxEOS/A3Q==", + "dev": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/postcss": { + "version": "8.3.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.3.6.tgz", + "integrity": "sha512-wG1cc/JhRgdqB6WHEuyLTedf3KIRuD0hG6ldkFEZNCjRxiC+3i6kkWUUbiJQayP28iwG35cEmAbe98585BYV0A==", + "dev": true, + "dependencies": { + "colorette": "^1.2.2", + "nanoid": "^3.1.23", + "source-map-js": "^0.6.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + } + }, + "node_modules/postcss-modules": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/postcss-modules/-/postcss-modules-4.2.2.tgz", + "integrity": "sha512-/H08MGEmaalv/OU8j6bUKi/kZr2kqGF6huAW8m9UAgOLWtpFdhA14+gPBoymtqyv+D4MLsmqaF2zvIegdCxJXg==", + "dev": true, + "dependencies": { + "generic-names": "^2.0.1", + "icss-replace-symbols": "^1.1.0", + "lodash.camelcase": "^4.3.0", + "postcss-modules-extract-imports": "^3.0.0", + "postcss-modules-local-by-default": "^4.0.0", + "postcss-modules-scope": "^3.0.0", + "postcss-modules-values": "^4.0.0", + "string-hash": "^1.1.1" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-modules-extract-imports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.0.0.tgz", + "integrity": "sha512-bdHleFnP3kZ4NYDhuGlVK+CMrQ/pqUm8bx/oGL93K6gVwiclvX5x0n76fYMKuIGKzlABOy13zsvqjb0f92TEXw==", + "dev": true, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-local-by-default": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-4.0.0.tgz", + "integrity": "sha512-sT7ihtmGSF9yhm6ggikHdV0hlziDTX7oFoXtuVWeDd3hHObNkcHRo9V3yg7vCAY7cONyxJC/XXCmmiHHcvX7bQ==", + "dev": true, + "dependencies": { + "icss-utils": "^5.0.0", + "postcss-selector-parser": "^6.0.2", + "postcss-value-parser": "^4.1.0" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-scope": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-3.0.0.tgz", + "integrity": "sha512-hncihwFA2yPath8oZ15PZqvWGkWf+XUfQgUGamS4LqoP1anQLOsOJw0vr7J7IwLpoY9fatA2qiGUGmuZL0Iqlg==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.4" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-values": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-4.0.0.tgz", + "integrity": "sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ==", + "dev": true, + "dependencies": { + "icss-utils": "^5.0.0" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.0.6", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.6.tgz", + "integrity": "sha512-9LXrvaaX3+mcv5xkg5kFwqSzSH1JIObIx51PrndZwlmznwXRfxMddDvo9gve3gVR8ZTKgoFDdWkbRFmEhT4PMg==", + "dev": true, + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.1.0.tgz", + "integrity": "sha512-97DXOFbQJhk71ne5/Mt6cOu6yxsSfM0QGQyl0L25Gca4yGWEGJaig7l7gbCX623VqTBNGLRLaVUCnNkcedlRSQ==", + "dev": true + }, + "node_modules/resolve": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", + "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "dev": true, + "dependencies": { + "is-core-module": "^2.2.0", + "path-parse": "^1.0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rollup": { + "version": "2.56.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.56.3.tgz", + "integrity": "sha512-Au92NuznFklgQCUcV96iXlxUbHuB1vQMaH76DHl5M11TotjOHwqk9CwcrT78+Tnv4FN9uTBxq6p4EJoYkpyekg==", + "dev": true, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=10.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-0.6.2.tgz", + "integrity": "sha512-/3GptzWzu0+0MBQFrDKzw/DvvMTUORvgY6k6jd/VS6iCR4RDTKWH6v6WPwQoUO8667uQEf9Oe38DxAYWY5F/Ug==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "dev": true + }, + "node_modules/string-hash": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/string-hash/-/string-hash-1.1.3.tgz", + "integrity": "sha1-6Kr8CsGFW0Zmkp7X3RJ1311sgRs=", + "dev": true + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "engines": { + "node": ">=4" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "node_modules/vite": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-2.5.3.tgz", + "integrity": "sha512-1wMDnjflvtTTkMov8O/Xb5+w1/VW/Gw8oCf8f6dqgHn8lMOEqq0SaPtFEQeikFcOKCfSbiU0nEi0LDIx6DNsaQ==", + "dev": true, + "dependencies": { + "esbuild": "^0.12.17", + "postcss": "^8.3.6", + "resolve": "^1.20.0", + "rollup": "^2.38.5" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": ">=12.2.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/vue": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.2.8.tgz", + "integrity": "sha512-x7lwdnOSkceHQUXRVVHBaZzcp6v7M2CYtSZH75zZaT1mTjB4plC4KZHKP/5jAvdqOLBHZGwDSMkWXm3YbAufrA==", + "dependencies": { + "@vue/compiler-dom": "3.2.8", + "@vue/runtime-dom": "3.2.8", + "@vue/shared": "3.2.8" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true + } + } +} diff --git a/node_modules/@babel/helper-validator-identifier/LICENSE b/node_modules/@babel/helper-validator-identifier/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-validator-identifier/README.md b/node_modules/@babel/helper-validator-identifier/README.md new file mode 100644 index 0000000..6733576 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/README.md @@ -0,0 +1,19 @@ +# @babel/helper-validator-identifier + +> Validate identifier/keywords name + +See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/en/babel-helper-validator-identifier) for more information. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/helper-validator-identifier +``` + +or using yarn: + +```sh +yarn add @babel/helper-validator-identifier --dev +``` diff --git a/node_modules/@babel/helper-validator-identifier/lib/identifier.js b/node_modules/@babel/helper-validator-identifier/lib/identifier.js new file mode 100644 index 0000000..71310db --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/identifier.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIdentifierStart = isIdentifierStart; +exports.isIdentifierChar = isIdentifierChar; +exports.isIdentifierName = isIdentifierName; +let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; +const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; +const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + +function isInAstralSet(code, set) { + let pos = 0x10000; + + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + + return false; +} + +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes); +} + +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} + +function isIdentifierName(name) { + let isFirst = true; + + for (let i = 0; i < name.length; i++) { + let cp = name.charCodeAt(i); + + if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) { + const trail = name.charCodeAt(++i); + + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + + if (isFirst) { + isFirst = false; + + if (!isIdentifierStart(cp)) { + return false; + } + } else if (!isIdentifierChar(cp)) { + return false; + } + } + + return !isFirst; +} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/lib/index.js b/node_modules/@babel/helper-validator-identifier/lib/index.js new file mode 100644 index 0000000..7b623c9 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/index.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return _identifier.isIdentifierName; + } +}); +Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return _identifier.isIdentifierChar; + } +}); +Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return _identifier.isIdentifierStart; + } +}); +Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return _keyword.isReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindOnlyReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindReservedWord; + } +}); +Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictReservedWord; + } +}); +Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return _keyword.isKeyword; + } +}); + +var _identifier = require("./identifier"); + +var _keyword = require("./keyword"); \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/lib/keyword.js b/node_modules/@babel/helper-validator-identifier/lib/keyword.js new file mode 100644 index 0000000..110cee4 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/keyword.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isReservedWord = isReservedWord; +exports.isStrictReservedWord = isStrictReservedWord; +exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; +exports.isStrictBindReservedWord = isStrictBindReservedWord; +exports.isKeyword = isKeyword; +const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +const keywords = new Set(reservedWords.keyword); +const reservedWordsStrictSet = new Set(reservedWords.strict); +const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); + +function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; +} + +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} + +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} + +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); +} + +function isKeyword(word) { + return keywords.has(word); +} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/package.json b/node_modules/@babel/helper-validator-identifier/package.json new file mode 100644 index 0000000..c98f0e4 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/package.json @@ -0,0 +1,24 @@ +{ + "name": "@babel/helper-validator-identifier", + "version": "7.14.9", + "description": "Validate identifier/keywords name", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-helper-validator-identifier" + }, + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "main": "./lib/index.js", + "exports": "./lib/index.js", + "devDependencies": { + "@unicode/unicode-13.0.0": "^1.0.6", + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "author": "The Babel Team (https://babel.dev/team)" +} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js b/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js new file mode 100644 index 0000000..45276d5 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js @@ -0,0 +1,75 @@ +"use strict"; + +// Always use the latest available version of Unicode! +// https://tc39.github.io/ecma262/#sec-conformance +const version = "13.0.0"; + +const start = require("@unicode/unicode-" + + version + + "/Binary_Property/ID_Start/code-points.js").filter(function (ch) { + return ch > 0x7f; +}); +let last = -1; +const cont = [0x200c, 0x200d].concat( + require("@unicode/unicode-" + + version + + "/Binary_Property/ID_Continue/code-points.js").filter(function (ch) { + return ch > 0x7f && search(start, ch, last + 1) == -1; + }) +); + +function search(arr, ch, starting) { + for (let i = starting; arr[i] <= ch && i < arr.length; last = i++) { + if (arr[i] === ch) return i; + } + return -1; +} + +function pad(str, width) { + while (str.length < width) str = "0" + str; + return str; +} + +function esc(code) { + const hex = code.toString(16); + if (hex.length <= 2) return "\\x" + pad(hex, 2); + else return "\\u" + pad(hex, 4); +} + +function generate(chars) { + const astral = []; + let re = ""; + for (let i = 0, at = 0x10000; i < chars.length; i++) { + const from = chars[i]; + let to = from; + while (i < chars.length - 1 && chars[i + 1] == to + 1) { + i++; + to++; + } + if (to <= 0xffff) { + if (from == to) re += esc(from); + else if (from + 1 == to) re += esc(from) + esc(to); + else re += esc(from) + "-" + esc(to); + } else { + astral.push(from - at, to - from); + at = to; + } + } + return { nonASCII: re, astral: astral }; +} + +const startData = generate(start); +const contData = generate(cont); + +console.log("/* prettier-ignore */"); +console.log('let nonASCIIidentifierStartChars = "' + startData.nonASCII + '";'); +console.log("/* prettier-ignore */"); +console.log('let nonASCIIidentifierChars = "' + contData.nonASCII + '";'); +console.log("/* prettier-ignore */"); +console.log( + "const astralIdentifierStartCodes = " + JSON.stringify(startData.astral) + ";" +); +console.log("/* prettier-ignore */"); +console.log( + "const astralIdentifierCodes = " + JSON.stringify(contData.astral) + ";" +); diff --git a/node_modules/@babel/parser/CHANGELOG.md b/node_modules/@babel/parser/CHANGELOG.md new file mode 100644 index 0000000..b3840ac --- /dev/null +++ b/node_modules/@babel/parser/CHANGELOG.md @@ -0,0 +1,1073 @@ +# Changelog + +> **Tags:** +> - :boom: [Breaking Change] +> - :eyeglasses: [Spec Compliance] +> - :rocket: [New Feature] +> - :bug: [Bug Fix] +> - :memo: [Documentation] +> - :house: [Internal] +> - :nail_care: [Polish] + +> Semver Policy: https://github.com/babel/babel/tree/main/packages/babel-parser#semver + +_Note: Gaps between patch versions are faulty, broken or test releases._ + +See the [Babel Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md) for the pre-6.8.0 version Changelog. + +## 6.17.1 (2017-05-10) + +### :bug: Bug Fix + * Fix typo in flow spread operator error (Brian Ng) + * Fixed invalid number literal parsing ([#473](https://github.com/babel/babylon/pull/473)) (Alex Kuzmenko) + * Fix number parser ([#433](https://github.com/babel/babylon/pull/433)) (Alex Kuzmenko) + * Ensure non pattern shorthand props are checked for reserved words ([#479](https://github.com/babel/babylon/pull/479)) (Brian Ng) + * Remove jsx context when parsing arrow functions ([#475](https://github.com/babel/babylon/pull/475)) (Brian Ng) + * Allow super in class properties ([#499](https://github.com/babel/babylon/pull/499)) (Brian Ng) + * Allow flow class field to be named constructor ([#510](https://github.com/babel/babylon/pull/510)) (Brian Ng) + +## 6.17.0 (2017-04-20) + +### :bug: Bug Fix + * Cherry-pick #418 to 6.x ([#476](https://github.com/babel/babylon/pull/476)) (Sebastian McKenzie) + * Add support for invalid escapes in tagged templates ([#274](https://github.com/babel/babylon/pull/274)) (Kevin Gibbons) + * Throw error if new.target is used outside of a function ([#402](https://github.com/babel/babylon/pull/402)) (Brian Ng) + * Fix parsing of class properties ([#351](https://github.com/babel/babylon/pull/351)) (Kevin Gibbons) + * Fix parsing yield with dynamicImport ([#383](https://github.com/babel/babylon/pull/383)) (Brian Ng) + * Ensure consistent start args for parseParenItem ([#386](https://github.com/babel/babylon/pull/386)) (Brian Ng) + +## 7.0.0-beta.8 (2017-04-04) + +### New Feature +* Add support for flow type spread (#418) (Conrad Buck) +* Allow statics in flow interfaces (#427) (Brian Ng) + +### Bug Fix +* Fix predicate attachment to match flow parser (#428) (Brian Ng) +* Add extra.raw back to JSXText and JSXAttribute (#344) (Alex Rattray) +* Fix rest parameters with array and objects (#424) (Brian Ng) +* Fix number parser (#433) (Alex Kuzmenko) + +### Docs +* Fix CONTRIBUTING.md [skip ci] (#432) (Alex Kuzmenko) + +### Internal +* Use babel-register script when running babel smoke tests (#442) (Brian Ng) + +## 7.0.0-beta.7 (2017-03-22) + +### Spec Compliance +* Remove babylon plugin for template revision since it's stage-4 (#426) (Henry Zhu) + +### Bug Fix + +* Fix push-pop logic in flow (#405) (Daniel Tschinder) + +## 7.0.0-beta.6 (2017-03-21) + +### New Feature +* Add support for invalid escapes in tagged templates (#274) (Kevin Gibbons) + +### Polish +* Improves error message when super is called outside of constructor (#408) (Arshabh Kumar Agarwal) + +### Docs + +* [7.0] Moved value field in spec from ObjectMember to ObjectProperty as ObjectMethod's don't have it (#415) [skip ci] (James Browning) + +## 7.0.0-beta.5 (2017-03-21) + +### Bug Fix +* Throw error if new.target is used outside of a function (#402) (Brian Ng) +* Fix parsing of class properties (#351) (Kevin Gibbons) + +### Other + * Test runner: Detect extra property in 'actual' but not in 'expected'. (#407) (Andy) + * Optimize travis builds (#419) (Daniel Tschinder) + * Update codecov to 2.0 (#412) (Daniel Tschinder) + * Fix spec for ClassMethod: It doesn't have a function, it *is* a function. (#406) [skip ci] (Andy) + * Changed Non-existent RestPattern to RestElement which is what is actually parsed (#409) [skip ci] (James Browning) + * Upgrade flow to 0.41 (Daniel Tschinder) + * Fix watch command (#403) (Brian Ng) + * Update yarn lock (Daniel Tschinder) + * Fix watch command (#403) (Brian Ng) + * chore(package): update flow-bin to version 0.41.0 (#395) (greenkeeper[bot]) + * Add estree test for correct order of directives (Daniel Tschinder) + * Add DoExpression to spec (#364) (Alex Kuzmenko) + * Mention cloning of repository in CONTRIBUTING.md (#391) [skip ci] (Sumedh Nimkarde) + * Explain how to run only one test (#389) [skip ci] (Aaron Ang) + + ## 7.0.0-beta.4 (2017-03-01) + +* Don't consume async when checking for async func decl (#377) (Brian Ng) +* add `ranges` option [skip ci] (Henry Zhu) +* Don't parse class properties without initializers when classProperties is disabled and Flow is enabled (#300) (Andrew Levine) + +## 7.0.0-beta.3 (2017-02-28) + +- [7.0] Change RestProperty/SpreadProperty to RestElement/SpreadElement (#384) +- Merge changes from 6.x + +## 7.0.0-beta.2 (2017-02-20) + +- estree: correctly change literals in all cases (#368) (Daniel Tschinder) + +## 7.0.0-beta.1 (2017-02-20) + +- Fix negative number literal typeannotations (#366) (Daniel Tschinder) +- Update contributing with more test info [skip ci] (#355) (Brian Ng) + +## 7.0.0-beta.0 (2017-02-15) + +- Reintroduce Variance node (#333) (Daniel Tschinder) +- Rename NumericLiteralTypeAnnotation to NumberLiteralTypeAnnotation (#332) (Charles Pick) +- [7.0] Remove ForAwaitStatement, add await flag to ForOfStatement (#349) (Brandon Dail) +- chore(package): update ava to version 0.18.0 (#345) (greenkeeper[bot]) +- chore(package): update babel-plugin-istanbul to version 4.0.0 (#350) (greenkeeper[bot]) +- Change location of ObjectTypeIndexer to match flow (#228) (Daniel Tschinder) +- Rename flow AST Type ExistentialTypeParam to ExistsTypeAnnotation (#322) (Toru Kobayashi) +- Revert "Temporary rollback for erroring on trailing comma with spread (#154)" (#290) (Daniel Tschinder) +- Remove classConstructorCall plugin (#291) (Brian Ng) +- Update yarn.lock (Daniel Tschinder) +- Update cross-env to 3.x (Daniel Tschinder) +- [7.0] Remove node 0.10, 0.12 and 5 from Travis (#284) (Sergey Rubanov) +- Remove `String.fromCodePoint` shim (#279) (Mathias Bynens) + +## 6.16.1 (2017-02-23) + +### :bug: Regression + +- Revert "Fix export default async function to be FunctionDeclaration" ([#375](https://github.com/babel/babylon/pull/375)) + +Need to modify Babel for this AST node change, so moving to 7.0. + +- Revert "Don't parse class properties without initializers when classProperties plugin is disabled, and Flow is enabled" ([#376](https://github.com/babel/babylon/pull/376)) + +[react-native](https://github.com/facebook/react-native/issues/12542) broke with this so we reverted. + +## 6.16.0 (2017-02-23) + +### :rocket: New Feature + +***ESTree*** compatibility as plugin ([#277](https://github.com/babel/babylon/pull/277)) (Daniel Tschinder) + +We finally introduce a new compatibility layer for ESTree. To put babylon into ESTree-compatible mode the new plugin `estree` can be enabled. In this mode the parser will output an AST that is compliant to the specs of [ESTree](https://github.com/estree/estree/) + +We highly recommend everyone who uses babylon outside of babel to use this plugin. This will make it much easier for users to switch between different ESTree-compatible parsers. We so far tested several projects with different parsers and exchanged their parser to babylon and in nearly all cases it worked out of the box. Some other estree-compatible parsers include `acorn`, `esprima`, `espree`, `flow-parser`, etc. + +To enable `estree` mode simply add the plugin in the config: +```json +{ + "plugins": [ "estree" ] +} +``` + +If you want to migrate your project from non-ESTree mode to ESTree, have a look at our [Readme](https://github.com/babel/babylon/#output), where all deviations are mentioned. + +Add a parseExpression public method ([#213](https://github.com/babel/babylon/pull/213)) (jeromew) + +Babylon exports a new function to parse a single expression + +```js +import { parseExpression } from 'babylon'; + +const ast = parseExpression('x || y && z', options); +``` + +The returned AST will only consist of the expression. The options are the same as for `parse()` + +Add startLine option ([#346](https://github.com/babel/babylon/pull/346)) (Raphael Mu) + +A new option was added to babylon allowing to change the initial linenumber for the first line which is usually `1`. +Changing this for example to `100` will make line `1` of the input source to be marked as line `100`, line `2` as `101`, line `3` as `102`, ... + +Function predicate declaration ([#103](https://github.com/babel/babylon/pull/103)) (Panagiotis Vekris) + +Added support for function predicates which flow introduced in version 0.33.0 + +```js +declare function is_number(x: mixed): boolean %checks(typeof x === "number"); +``` + +Allow imports in declare module ([#315](https://github.com/babel/babylon/pull/315)) (Daniel Tschinder) + +Added support for imports within module declarations which flow introduced in version 0.37.0 + +```js +declare module "C" { + import type { DT } from "D"; + declare export type CT = { D: DT }; +} +``` + +### :eyeglasses: Spec Compliance + +Forbid semicolons after decorators in classes ([#352](https://github.com/babel/babylon/pull/352)) (Kevin Gibbons) + +This example now correctly throws an error when there is a semicolon after the decorator: + +```js +class A { +@a; +foo(){} +} +``` + +Keywords are not allowed as local specifier ([#307](https://github.com/babel/babylon/pull/307)) (Daniel Tschinder) + +Using keywords in imports is not allowed anymore: + +```js +import { default } from "foo"; +import { a as debugger } from "foo"; +``` + +Do not allow overwritting of primitive types ([#314](https://github.com/babel/babylon/pull/314)) (Daniel Tschinder) + +In flow it is now forbidden to overwrite the primitive types `"any"`, `"mixed"`, `"empty"`, `"bool"`, `"boolean"`, `"number"`, `"string"`, `"void"` and `"null"` with your own type declaration. + +Disallow import type { type a } from … ([#305](https://github.com/babel/babylon/pull/305)) (Daniel Tschinder) + +The following code now correctly throws an error + +```js +import type { type a } from "foo"; +``` + +Don't parse class properties without initializers when classProperties is disabled and Flow is enabled ([#300](https://github.com/babel/babylon/pull/300)) (Andrew Levine) + +Ensure that you enable the `classProperties` plugin in order to enable correct parsing of class properties. Prior to this version it was possible to parse them by enabling the `flow` plugin but this was not intended the behaviour. + +If you enable the flow plugin you can only define the type of the class properties, but not initialize them. + +Fix export default async function to be FunctionDeclaration ([#324](https://github.com/babel/babylon/pull/324)) (Daniel Tschinder) + +Parsing the following code now returns a `FunctionDeclaration` AST node instead of `FunctionExpression`. + +```js +export default async function bar() {}; +``` + +### :nail_care: Polish + +Improve error message on attempt to destructure named import ([#288](https://github.com/babel/babylon/pull/288)) (Brian Ng) + +### :bug: Bug Fix + +Fix negative number literal typeannotations ([#366](https://github.com/babel/babylon/pull/366)) (Daniel Tschinder) + +Ensure takeDecorators is called on exported class ([#358](https://github.com/babel/babylon/pull/358)) (Brian Ng) + +ESTree: correctly change literals in all cases ([#368](https://github.com/babel/babylon/pull/368)) (Daniel Tschinder) + +Correctly convert RestProperty to Assignable ([#339](https://github.com/babel/babylon/pull/339)) (Daniel Tschinder) + +Fix #321 by allowing question marks in type params ([#338](https://github.com/babel/babylon/pull/338)) (Daniel Tschinder) + +Fix #336 by correctly setting arrow-param ([#337](https://github.com/babel/babylon/pull/337)) (Daniel Tschinder) + +Fix parse error when destructuring `set` with default value ([#317](https://github.com/babel/babylon/pull/317)) (Brian Ng) + +Fix ObjectTypeCallProperty static ([#298](https://github.com/babel/babylon/pull/298)) (Dan Harper) + + +### :house: Internal + +Fix generator-method-with-computed-name spec ([#360](https://github.com/babel/babylon/pull/360)) (Alex Rattray) + +Fix flow type-parameter-declaration test with unintended semantic ([#361](https://github.com/babel/babylon/pull/361)) (Alex Rattray) + +Cleanup and splitup parser functions ([#295](https://github.com/babel/babylon/pull/295)) (Daniel Tschinder) + +chore(package): update flow-bin to version 0.38.0 ([#313](https://github.com/babel/babylon/pull/313)) (greenkeeper[bot]) + +Call inner function instead of 1:1 copy to plugin ([#294](https://github.com/babel/babylon/pull/294)) (Daniel Tschinder) + +Update eslint-config-babel to the latest version 🚀 ([#299](https://github.com/babel/babylon/pull/299)) (greenkeeper[bot]) + +Update eslint-config-babel to the latest version 🚀 ([#293](https://github.com/babel/babylon/pull/293)) (greenkeeper[bot]) + +devDeps: remove eslint-plugin-babel ([#292](https://github.com/babel/babylon/pull/292)) (Kai Cataldo) + +Correct indent eslint rule config ([#276](https://github.com/babel/babylon/pull/276)) (Daniel Tschinder) + +Fail tests that have expected.json and throws-option ([#285](https://github.com/babel/babylon/pull/285)) (Daniel Tschinder) + +### :memo: Documentation + +Update contributing with more test info [skip ci] ([#355](https://github.com/babel/babylon/pull/355)) (Brian Ng) + +Update API documentation ([#330](https://github.com/babel/babylon/pull/330)) (Timothy Gu) + +Added keywords to package.json ([#323](https://github.com/babel/babylon/pull/323)) (Dmytro) + +AST spec: fix casing of `RegExpLiteral` ([#318](https://github.com/babel/babylon/pull/318)) (Mathias Bynens) + +## 6.15.0 (2017-01-10) + +### :eyeglasses: Spec Compliance + +Add support for Flow shorthand import type ([#267](https://github.com/babel/babylon/pull/267)) (Jeff Morrison) + +This change implements flows new shorthand import syntax +and where previously you had to write this code: + +```js +import {someValue} from "blah"; +import type {someType} from "blah"; +import typeof {someOtherValue} from "blah"; +``` + +you can now write it like this: + +```js +import { + someValue, + type someType, + typeof someOtherValue, +} from "blah"; +``` + +For more information look at [this](https://github.com/facebook/flow/pull/2890) pull request. + +flow: allow leading pipes in all positions ([#256](https://github.com/babel/babylon/pull/256)) (Vladimir Kurchatkin) + +This change now allows a leading pipe everywhere types can be used: +```js +var f = (x): | 1 | 2 => 1; +``` + +Throw error when exporting non-declaration ([#241](https://github.com/babel/babylon/pull/241)) (Kai Cataldo) + +Previously babylon parsed the following exports, although they are not valid: +```js +export typeof foo; +export new Foo(); +export function() {}; +export for (;;); +export while(foo); +``` + +### :bug: Bug Fix + +Don't set inType flag when parsing property names ([#266](https://github.com/babel/babylon/pull/266)) (Vladimir Kurchatkin) + +This fixes parsing of this case: + +```js +const map = { + [age <= 17] : 'Too young' +}; +``` + +Fix source location for JSXEmptyExpression nodes (fixes #248) ([#249](https://github.com/babel/babylon/pull/249)) (James Long) + +The following case produced an invalid AST +```js +
{/* foo */}
+``` + +Use fromCodePoint to convert high value unicode entities ([#243](https://github.com/babel/babylon/pull/243)) (Ryan Duffy) + +When high value unicode entities (e.g. 💩) were used in the input source code they are now correctly encoded in the resulting AST. + +Rename folder to avoid Windows-illegal characters ([#281](https://github.com/babel/babylon/pull/281)) (Ryan Plant) + +Allow this.state.clone() when parsing decorators ([#262](https://github.com/babel/babylon/pull/262)) (Alex Rattray) + +### :house: Internal + +User external-helpers ([#254](https://github.com/babel/babylon/pull/254)) (Daniel Tschinder) + +Add watch script for dev ([#234](https://github.com/babel/babylon/pull/234)) (Kai Cataldo) + +Freeze current plugins list for "*" option, and remove from README.md ([#245](https://github.com/babel/babylon/pull/245)) (Andrew Levine) + +Prepare tests for multiple fixture runners. ([#240](https://github.com/babel/babylon/pull/240)) (Daniel Tschinder) + +Add some test coverage for decorators stage-0 plugin ([#250](https://github.com/babel/babylon/pull/250)) (Andrew Levine) + +Refactor tokenizer types file ([#263](https://github.com/babel/babylon/pull/263)) (Sven SAULEAU) + +Update eslint-config-babel to the latest version 🚀 ([#273](https://github.com/babel/babylon/pull/273)) (greenkeeper[bot]) + +chore(package): update rollup to version 0.41.0 ([#272](https://github.com/babel/babylon/pull/272)) (greenkeeper[bot]) + +chore(package): update flow-bin to version 0.37.0 ([#255](https://github.com/babel/babylon/pull/255)) (greenkeeper[bot]) + +## 6.14.1 (2016-11-17) + +### :bug: Bug Fix + +Allow `"plugins": ["*"]` ([#229](https://github.com/babel/babylon/pull/229)) (Daniel Tschinder) + +```js +{ + "plugins": ["*"] +} +``` + +Will include all parser plugins instead of specifying each one individually. Useful for tools like babel-eslint, jscodeshift, and ast-explorer. + +## 6.14.0 (2016-11-16) + +### :eyeglasses: Spec Compliance + +Throw error for reserved words `enum` and `await` ([#195](https://github.com/babel/babylon/pull/195)) (Kai Cataldo) + +[11.6.2.2 Future Reserved Words](http://www.ecma-international.org/ecma-262/6.0/#sec-future-reserved-words) + +Babylon will throw for more reserved words such as `enum` or `await` (in strict mode). + +``` +class enum {} // throws +class await {} // throws in strict mode (module) +``` + +Optional names for function types and object type indexers ([#197](https://github.com/babel/babylon/pull/197)) (Gabe Levi) + +So where you used to have to write + +```js +type A = (x: string, y: boolean) => number; +type B = (z: string) => number; +type C = { [key: string]: number }; +``` + +you can now write (with flow 0.34.0) + +```js +type A = (string, boolean) => number; +type B = string => number; +type C = { [string]: number }; +``` + +Parse flow nested array type annotations like `number[][]` ([#219](https://github.com/babel/babylon/pull/219)) (Bernhard Häussner) + +Supports these form now of specifying array types: + +```js +var a: number[][][][]; +var b: string[][]; +``` + +### :bug: Bug Fix + +Correctly eat semicolon at the end of `DelcareModuleExports` ([#223](https://github.com/babel/babylon/pull/223)) (Daniel Tschinder) + +``` +declare module "foo" { declare module.exports: number } +declare module "foo" { declare module.exports: number; } // also allowed now +``` + +### :house: Internal + + * Count Babel tests towards Babylon code coverage ([#182](https://github.com/babel/babylon/pull/182)) (Moti Zilberman) + * Fix strange line endings ([#214](https://github.com/babel/babylon/pull/214)) (Thomas Grainger) + * Add node 7 (Daniel Tschinder) + * chore(package): update flow-bin to version 0.34.0 ([#204](https://github.com/babel/babylon/pull/204)) (Greenkeeper) + +## v6.13.1 (2016-10-26) + +### :nail_care: Polish + +- Use rollup for bundling to speed up startup time ([#190](https://github.com/babel/babylon/pull/190)) ([@drewml](https://github.com/DrewML)) + +```js +const babylon = require('babylon'); +const ast = babylon.parse('var foo = "lol";'); +``` + +With that test case, there was a ~95ms savings by removing the need for node to build/traverse the dependency graph. + +**Without bundling** +![image](https://cloud.githubusercontent.com/assets/5233399/19420264/3133497e-93ad-11e6-9a6a-2da59c4f5c13.png) + +**With bundling** +![image](https://cloud.githubusercontent.com/assets/5233399/19420267/388f556e-93ad-11e6-813e-7c5c396be322.png) + +- add clean command [skip ci] ([#201](https://github.com/babel/babylon/pull/201)) (Henry Zhu) +- add ForAwaitStatement (async generator already added) [skip ci] ([#196](https://github.com/babel/babylon/pull/196)) (Henry Zhu) + +## v6.13.0 (2016-10-21) + +### :eyeglasses: Spec Compliance + +Property variance type annotations for Flow plugin ([#161](https://github.com/babel/babylon/pull/161)) (Sam Goldman) + +> See https://flowtype.org/docs/variance.html for more information + +```js +type T = { +p: T }; +interface T { -p: T }; +declare class T { +[k:K]: V }; +class T { -[k:K]: V }; +class C2 { +p: T = e }; +``` + +Raise error on duplicate definition of __proto__ ([#183](https://github.com/babel/babylon/pull/183)) (Moti Zilberman) + +```js +({ __proto__: 1, __proto__: 2 }) // Throws an error now +``` + +### :bug: Bug Fix + +Flow: Allow class properties to be named `static` ([#184](https://github.com/babel/babylon/pull/184)) (Moti Zilberman) + +```js +declare class A { + static: T; +} +``` + +Allow "async" as identifier for object literal property shorthand ([#187](https://github.com/babel/babylon/pull/187)) (Andrew Levine) + +```js +var foo = { async, bar }; +``` + +### :nail_care: Polish + +Fix flowtype and add inType to state ([#189](https://github.com/babel/babylon/pull/189)) (Daniel Tschinder) + +> This improves the performance slightly (because of hidden classes) + +### :house: Internal + +Fix .gitattributes line ending setting ([#191](https://github.com/babel/babylon/pull/191)) (Moti Zilberman) + +Increase test coverage ([#175](https://github.com/babel/babylon/pull/175) (Moti Zilberman) + +Readd missin .eslinignore for IDEs (Daniel Tschinder) + +Error on missing expected.json fixture in CI ([#188](https://github.com/babel/babylon/pull/188)) (Moti Zilberman) + +Add .gitattributes and .editorconfig for LF line endings ([#179](https://github.com/babel/babylon/pull/179)) (Moti Zilberman) + +Fixes two tests that are failing after the merge of #172 ([#177](https://github.com/babel/babylon/pull/177)) (Moti Zilberman) + +## v6.12.0 (2016-10-14) + +### :eyeglasses: Spec Compliance + +Implement import() syntax ([#163](https://github.com/babel/babylon/pull/163)) (Jordan Gensler) + +#### Dynamic Import + +- Proposal Repo: https://github.com/domenic/proposal-dynamic-import +- Championed by [@domenic](https://github.com/domenic) +- stage-2 +- [sept-28 tc39 notes](https://github.com/rwaldron/tc39-notes/blob/master/es7/2016-09/sept-28.md#113a-import) + +> This repository contains a proposal for adding a "function-like" import() module loading syntactic form to JavaScript + +```js +import(`./section-modules/${link.dataset.entryModule}.js`) +.then(module => { + module.loadPageInto(main); +}) +``` + +Add EmptyTypeAnnotation ([#171](https://github.com/babel/babylon/pull/171)) (Sam Goldman) + +#### EmptyTypeAnnotation + +Just wasn't covered before. + +```js +type T = empty; +``` + +### :bug: Bug Fix + +Fix crash when exporting with destructuring and sparse array ([#170](https://github.com/babel/babylon/pull/170)) (Jeroen Engels) + +```js +// was failing due to sparse array +export const { foo: [ ,, qux7 ] } = bar; +``` + +Allow keyword in Flow object declaration property names with type parameters ([#146](https://github.com/babel/babylon/pull/146)) (Dan Harper) + +```js +declare class X { + foobar(): void; + static foobar(): void; +} +``` + +Allow keyword in object/class property names with Flow type parameters ([#145](https://github.com/babel/babylon/pull/145)) (Dan Harper) + +```js +class Foo { + delete(item: T): T { + return item; + } +} +``` + +Allow typeAnnotations for yield expressions ([#174](https://github.com/babel/babylon/pull/174))) (Daniel Tschinder) + +```js +function *foo() { + const x = (yield 5: any); +} +``` + +### :nail_care: Polish + +Annotate more errors with expected token ([#172](https://github.com/babel/babylon/pull/172))) (Moti Zilberman) + +```js +// Unexpected token, expected ; (1:6) +{ set 1 } +``` + +### :house: Internal + +Remove kcheck ([#173](https://github.com/babel/babylon/pull/173))) (Daniel Tschinder) + +Also run flow, linting, babel tests on separate instances (add back node 0.10) + +## v6.11.6 (2016-10-12) + +### :bug: Bug Fix/Regression + +Fix crash when exporting with destructuring and sparse array ([#170](https://github.com/babel/babylon/pull/170)) (Jeroen Engels) + +```js +// was failing with `Cannot read property 'type' of null` because of null identifiers +export const { foo: [ ,, qux7 ] } = bar; +``` + +## v6.11.5 (2016-10-12) + +### :eyeglasses: Spec Compliance + +Fix: Check for duplicate named exports in exported destructuring assignments ([#144](https://github.com/babel/babylon/pull/144)) (Kai Cataldo) + +```js +// `foo` has already been exported. Exported identifiers must be unique. (2:20) +export function foo() {}; +export const { a: [{foo}] } = bar; +``` + +Fix: Check for duplicate named exports in exported rest elements/properties ([#164](https://github.com/babel/babylon/pull/164)) (Kai Cataldo) + +```js +// `foo` has already been exported. Exported identifiers must be unique. (2:22) +export const foo = 1; +export const [bar, ...foo] = baz; +``` + +### :bug: Bug Fix + +Fix: Allow identifier `async` for default param in arrow expression ([#165](https://github.com/babel/babylon/pull/165)) (Kai Cataldo) + +```js +// this is ok now +const test = ({async = true}) => {}; +``` + +### :nail_care: Polish + +Babylon will now print out the token it's expecting if there's a `SyntaxError` ([#150](https://github.com/babel/babylon/pull/150)) (Daniel Tschinder) + +```bash +# So in the case of a missing ending curly (`}`) +Module build failed: SyntaxError: Unexpected token, expected } (30:0) + 28 | } + 29 | +> 30 | + | ^ +``` + +## v6.11.4 (2016-10-03) + +Temporary rollback for erroring on trailing comma with spread (#154) (Henry Zhu) + +## v6.11.3 (2016-10-01) + +### :eyeglasses: Spec Compliance + +Add static errors for object rest (#149) ([@danez](https://github.com/danez)) + +> https://github.com/sebmarkbage/ecmascript-rest-spread + +Object rest copies the *rest* of properties from the right hand side `obj` starting from the left to right. + +```js +let { x, y, ...z } = { x: 1, y: 2, z: 3 }; +// x = 1 +// y = 2 +// z = { z: 3 } +``` + +#### New Syntax Errors: + +**SyntaxError**: The rest element has to be the last element when destructuring (1:10) +```bash +> 1 | let { ...x, y, z } = { x: 1, y: 2, z: 3}; + | ^ +# Previous behavior: +# x = { x: 1, y: 2, z: 3 } +# y = 2 +# z = 3 +``` + +Before, this was just a more verbose way of shallow copying `obj` since it doesn't actually do what you think. + +**SyntaxError**: Cannot have multiple rest elements when destructuring (1:13) + +```bash +> 1 | let { x, ...y, ...z } = { x: 1, y: 2, z: 3}; + | ^ +# Previous behavior: +# x = 1 +# y = { y: 2, z: 3 } +# z = { y: 2, z: 3 } +``` + +Before y and z would just be the same value anyway so there is no reason to need to have both. + +**SyntaxError**: A trailing comma is not permitted after the rest element (1:16) + +```js +let { x, y, ...z, } = obj; +``` + +The rationale for this is that the use case for trailing comma is that you can add something at the end without affecting the line above. Since a RestProperty always has to be the last property it doesn't make sense. + +--- + +get / set are valid property names in default assignment (#142) ([@jezell](https://github.com/jezell)) + +```js +// valid +function something({ set = null, get = null }) {} +``` + +## v6.11.2 (2016-09-23) + +### Bug Fix + +- [#139](https://github.com/babel/babylon/issues/139) Don't do the duplicate check if not an identifier (#140) @hzoo + +```js +// regression with duplicate export check +SyntaxError: ./typography.js: `undefined` has already been exported. Exported identifiers must be unique. (22:13) + 20 | + 21 | export const { rhythm } = typography; +> 22 | export const { TypographyStyle } = typography +``` + +Bail out for now, and make a change to account for destructuring in the next release. + +## 6.11.1 (2016-09-22) + +### Bug Fix +- [#137](https://github.com/babel/babylon/pull/137) - Fix a regression with duplicate exports - it was erroring on all keys in `Object.prototype`. @danez + +```javascript +export toString from './toString'; +``` + +```bash +`toString` has already been exported. Exported identifiers must be unique. (1:7) +> 1 | export toString from './toString'; + | ^ + 2 | +``` + +## 6.11.0 (2016-09-22) + +### Spec Compliance (will break CI) + +- Disallow duplicate named exports ([#107](https://github.com/babel/babylon/pull/107)) @kaicataldo + +```js +// Only one default export allowed per module. (2:9) +export default function() {}; +export { foo as default }; + +// Only one default export allowed per module. (2:0) +export default {}; +export default function() {}; + +// `Foo` has already been exported. Exported identifiers must be unique. (2:0) +export { Foo }; +export class Foo {}; +``` + +### New Feature (Syntax) + +- Add support for computed class property names ([#121](https://github.com/babel/babylon/pull/121)) @motiz88 + +```js +// AST +interface ClassProperty <: Node { + type: "ClassProperty"; + key: Identifier; + value: Expression; + computed: boolean; // added +} +``` + +```js +// with "plugins": ["classProperties"] +class Foo { + [x] + ['y'] +} + +class Bar { + [p] + [m] () {} +} + ``` + +### Bug Fix + +- Fix `static` property falling through in the declare class Flow AST ([#135](https://github.com/babel/babylon/pull/135)) @danharper + +```js +declare class X { + a: number; + static b: number; // static + c: number; // this was being marked as static in the AST as well +} +``` + +### Polish + +- Rephrase "assigning/binding to rvalue" errors to include context ([#119](https://github.com/babel/babylon/pull/119)) @motiz88 + +```js +// Used to error with: +// SyntaxError: Assigning to rvalue (1:0) + +// Now: +// Invalid left-hand side in assignment expression (1:0) +3 = 4 + +// Invalid left-hand side in for-in statement (1:5) +for (+i in {}); +``` + +### Internal + +- Fix call to `this.parseMaybeAssign` with correct arguments ([#133](https://github.com/babel/babylon/pull/133)) @danez +- Add semver note to changelog ([#131](https://github.com/babel/babylon/pull/131)) @hzoo + +## 6.10.0 (2016-09-19) + +> We plan to include some spec compliance bugs in patch versions. An example was the multiple default exports issue. + +### Spec Compliance + +* Implement ES2016 check for simple parameter list in strict mode ([#106](https://github.com/babel/babylon/pull/106)) (Timothy Gu) + +> It is a Syntax Error if ContainsUseStrict of FunctionBody is true and IsSimpleParameterList of FormalParameters is false. https://tc39.github.io/ecma262/2016/#sec-function-definitions-static-semantics-early-errors + +More Context: [tc39-notes](https://github.com/rwaldron/tc39-notes/blob/master/es7/2015-07/july-29.md#611-the-scope-of-use-strict-with-respect-to-destructuring-in-parameter-lists) + +For example: + +```js +// this errors because it uses destructuring and default parameters +// in a function with a "use strict" directive +function a([ option1, option2 ] = []) { + "use strict"; +} + ``` + +The solution would be to use a top level "use strict" or to remove the destructuring or default parameters when using a function + "use strict" or to. + +### New Feature + +* Exact object type annotations for Flow plugin ([#104](https://github.com/babel/babylon/pull/104)) (Basil Hosmer) + +Added to flow in https://github.com/facebook/flow/commit/c710c40aa2a115435098d6c0dfeaadb023cd39b8 + +Looks like: + +```js +var a : {| x: number, y: string |} = { x: 0, y: 'foo' }; +``` + +### Bug Fixes + +* Include `typeParameter` location in `ArrowFunctionExpression` ([#126](https://github.com/babel/babylon/pull/126)) (Daniel Tschinder) +* Error on invalid flow type annotation with default assignment ([#122](https://github.com/babel/babylon/pull/122)) (Dan Harper) +* Fix Flow return types on arrow functions ([#124](https://github.com/babel/babylon/pull/124)) (Dan Harper) + +### Misc + +* Add tests for export extensions ([#127](https://github.com/babel/babylon/pull/127)) (Daniel Tschinder) +* Fix Contributing guidelines [skip ci] (Daniel Tschinder) + +## 6.9.2 (2016-09-09) + +The only change is to remove the `babel-runtime` dependency by compiling with Babel's ES2015 loose mode. So using babylon standalone should be smaller. + +## 6.9.1 (2016-08-23) + +This release contains mainly small bugfixes but also updates babylons default mode to es2017. The features for `exponentiationOperator`, `asyncFunctions` and `trailingFunctionCommas` which previously needed to be activated via plugin are now enabled by default and the plugins are now no-ops. + +### Bug Fixes + +- Fix issues with default object params in async functions ([#96](https://github.com/babel/babylon/pull/96)) @danez +- Fix issues with flow-types and async function ([#95](https://github.com/babel/babylon/pull/95)) @danez +- Fix arrow functions with destructuring, types & default value ([#94](https://github.com/babel/babylon/pull/94)) @danharper +- Fix declare class with qualified type identifier ([#97](https://github.com/babel/babylon/pull/97)) @danez +- Remove exponentiationOperator, asyncFunctions, trailingFunctionCommas plugins and enable them by default ([#98](https://github.com/babel/babylon/pull/98)) @danez + +## 6.9.0 (2016-08-16) + +### New syntax support + +- Add JSX spread children ([#42](https://github.com/babel/babylon/pull/42)) @calebmer + +(Be aware that React is not going to support this syntax) + +```js +
+ {...todos.map(todo => )} +
+``` + +- Add support for declare module.exports ([#72](https://github.com/babel/babylon/pull/72)) @danez + +```js +declare module "foo" { + declare module.exports: {} +} +``` + +### New Features + +- If supplied, attach filename property to comment node loc. ([#80](https://github.com/babel/babylon/pull/80)) @divmain +- Add identifier name to node loc field ([#90](https://github.com/babel/babylon/pull/90)) @kittens + +### Bug Fixes + +- Fix exponential operator to behave according to spec ([#75](https://github.com/babel/babylon/pull/75)) @danez +- Fix lookahead to not add comments to arrays which are not cloned ([#76](https://github.com/babel/babylon/pull/76)) @danez +- Fix accidental fall-through in Flow type parsing. ([#82](https://github.com/babel/babylon/pull/82)) @xiemaisi +- Only allow declares inside declare module ([#73](https://github.com/babel/babylon/pull/73)) @danez +- Small fix for parsing type parameter declarations ([#83](https://github.com/babel/babylon/pull/83)) @gabelevi +- Fix arrow param locations with flow types ([#57](https://github.com/babel/babylon/pull/57)) @danez +- Fixes SyntaxError position with flow optional type ([#65](https://github.com/babel/babylon/pull/65)) @danez + +### Internal + +- Add codecoverage to tests @danez +- Fix tests to not save expected output if we expect the test to fail @danez +- Make a shallow clone of babel for testing @danez +- chore(package): update cross-env to version 2.0.0 ([#77](https://github.com/babel/babylon/pull/77)) @greenkeeperio-bot +- chore(package): update ava to version 0.16.0 ([#86](https://github.com/babel/babylon/pull/86)) @greenkeeperio-bot +- chore(package): update babel-plugin-istanbul to version 2.0.0 ([#89](https://github.com/babel/babylon/pull/89)) @greenkeeperio-bot +- chore(package): update nyc to version 8.0.0 ([#88](https://github.com/babel/babylon/pull/88)) @greenkeeperio-bot + +## 6.8.4 (2016-07-06) + +### Bug Fixes + +- Fix the location of params, when flow and default value used ([#68](https://github.com/babel/babylon/pull/68)) @danez + +## 6.8.3 (2016-07-02) + +### Bug Fixes + +- Fix performance regression introduced in 6.8.2 with conditionals ([#63](https://github.com/babel/babylon/pull/63)) @danez + +## 6.8.2 (2016-06-24) + +### Bug Fixes + +- Fix parse error with yielding jsx elements in generators `function* it() { yield ; }` ([#31](https://github.com/babel/babylon/pull/31)) @eldereal +- When cloning nodes do not clone its comments ([#24](https://github.com/babel/babylon/pull/24)) @danez +- Fix parse errors when using arrow functions with an spread element and return type `(...props): void => {}` ([#10](https://github.com/babel/babylon/pull/10)) @danez +- Fix leading comments added from previous node ([#23](https://github.com/babel/babylon/pull/23)) @danez +- Fix parse errors with flow's optional arguments `(arg?) => {}` ([#19](https://github.com/babel/babylon/pull/19)) @danez +- Support negative numeric type literals @kittens +- Remove line terminator restriction after await keyword @kittens +- Remove grouped type arrow restriction as it seems flow no longer has it @kittens +- Fix parse error with generic methods that have the name `get` or `set` `class foo { get() {} }` ([#55](https://github.com/babel/babylon/pull/55)) @vkurchatkin +- Fix parse error with arrow functions that have flow type parameter declarations `(x: T): T => x;` ([#54](https://github.com/babel/babylon/pull/54)) @gabelevi + +### Documentation + +- Document AST differences from ESTree ([#41](https://github.com/babel/babylon/pull/41)) @nene +- Move ast spec from babel/babel ([#46](https://github.com/babel/babylon/pull/46)) @hzoo + +### Internal + +- Enable skipped tests ([#16](https://github.com/babel/babylon/pull/16)) @danez +- Add script to test latest version of babylon with babel ([#21](https://github.com/babel/babylon/pull/21)) @danez +- Upgrade test runner ava @kittens +- Add missing generate-identifier-regex script @kittens +- Rename parser context types @kittens +- Add node v6 to travis testing @hzoo +- Update to Unicode v9 ([#45](https://github.com/babel/babylon/pull/45)) @mathiasbynens + +## 6.8.1 (2016-06-06) + +### New Feature + +- Parse type parameter declarations with defaults like `type Foo = T` + +### Bug Fixes +- Type parameter declarations need 1 or more type parameters. +- The existential type `*` is not a valid type parameter. +- The existential type `*` is a primary type + +### Spec Compliance +- The param list for type parameter declarations now consists of `TypeParameter` nodes +- New `TypeParameter` AST Node (replaces using the `Identifier` node before) + +``` +interface TypeParameter <: Node { + bound: TypeAnnotation; + default: TypeAnnotation; + name: string; + variance: "plus" | "minus"; +} +``` + +## 6.8.0 (2016-05-02) + +#### New Feature + +##### Parse Method Parameter Decorators ([#12](https://github.com/babel/babylon/pull/12)) + +> [Method Parameter Decorators](https://goo.gl/8MmCMG) is now a TC39 [stage 0 proposal](https://github.com/tc39/ecma262/blob/master/stage0.md). + +Examples: + +```js +class Foo { + constructor(@foo() x, @bar({ a: 123 }) @baz() y) {} +} + +export default function func(@foo() x, @bar({ a: 123 }) @baz() y) {} + +var obj = { + method(@foo() x, @bar({ a: 123 }) @baz() y) {} +}; +``` + +##### Parse for-await statements (w/ `asyncGenerators` plugin) ([#17](https://github.com/babel/babylon/pull/17)) + +There is also a new node type, `ForAwaitStatement`. + +> [Async generators and for-await](https://github.com/tc39/proposal-async-iteration) are now a [stage 2 proposal](https://github.com/tc39/ecma262#current-proposals). + +Example: + +```js +async function f() { + for await (let x of y); +} +``` diff --git a/node_modules/@babel/parser/LICENSE b/node_modules/@babel/parser/LICENSE new file mode 100644 index 0000000..d4c7fc5 --- /dev/null +++ b/node_modules/@babel/parser/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012-2014 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@babel/parser/README.md b/node_modules/@babel/parser/README.md new file mode 100644 index 0000000..513748c --- /dev/null +++ b/node_modules/@babel/parser/README.md @@ -0,0 +1,19 @@ +# @babel/parser + +> A JavaScript parser + +See our website [@babel/parser](https://babeljs.io/docs/en/babel-parser) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20parser%20(babylon)%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/parser +``` + +or using yarn: + +```sh +yarn add @babel/parser --dev +``` diff --git a/node_modules/@babel/parser/bin/babel-parser.js b/node_modules/@babel/parser/bin/babel-parser.js new file mode 100644 index 0000000..3aca314 --- /dev/null +++ b/node_modules/@babel/parser/bin/babel-parser.js @@ -0,0 +1,15 @@ +#!/usr/bin/env node +/* eslint no-var: 0 */ + +var parser = require(".."); +var fs = require("fs"); + +var filename = process.argv[2]; +if (!filename) { + console.error("no filename specified"); +} else { + var file = fs.readFileSync(filename, "utf8"); + var ast = parser.parse(file); + + console.log(JSON.stringify(ast, null, " ")); +} diff --git a/node_modules/@babel/parser/lib/index.js b/node_modules/@babel/parser/lib/index.js new file mode 100644 index 0000000..a558758 --- /dev/null +++ b/node_modules/@babel/parser/lib/index.js @@ -0,0 +1,14572 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +const beforeExpr = true; +const startsExpr = true; +const isLoop = true; +const isAssign = true; +const prefix = true; +const postfix = true; +class TokenType { + constructor(label, conf = {}) { + this.label = void 0; + this.keyword = void 0; + this.beforeExpr = void 0; + this.startsExpr = void 0; + this.rightAssociative = void 0; + this.isLoop = void 0; + this.isAssign = void 0; + this.prefix = void 0; + this.postfix = void 0; + this.binop = void 0; + this.updateContext = void 0; + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.rightAssociative = !!conf.rightAssociative; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop != null ? conf.binop : null; + this.updateContext = null; + } + +} +const keywords$1 = new Map(); + +function createKeyword(name, options = {}) { + options.keyword = name; + const token = new TokenType(name, options); + keywords$1.set(name, token); + return token; +} + +function createBinop(name, binop) { + return new TokenType(name, { + beforeExpr, + binop + }); +} + +const types$1 = { + num: new TokenType("num", { + startsExpr + }), + bigint: new TokenType("bigint", { + startsExpr + }), + decimal: new TokenType("decimal", { + startsExpr + }), + regexp: new TokenType("regexp", { + startsExpr + }), + string: new TokenType("string", { + startsExpr + }), + name: new TokenType("name", { + startsExpr + }), + privateName: new TokenType("#name", { + startsExpr + }), + eof: new TokenType("eof"), + bracketL: new TokenType("[", { + beforeExpr, + startsExpr + }), + bracketHashL: new TokenType("#[", { + beforeExpr, + startsExpr + }), + bracketBarL: new TokenType("[|", { + beforeExpr, + startsExpr + }), + bracketR: new TokenType("]"), + bracketBarR: new TokenType("|]"), + braceL: new TokenType("{", { + beforeExpr, + startsExpr + }), + braceBarL: new TokenType("{|", { + beforeExpr, + startsExpr + }), + braceHashL: new TokenType("#{", { + beforeExpr, + startsExpr + }), + braceR: new TokenType("}", { + beforeExpr + }), + braceBarR: new TokenType("|}"), + parenL: new TokenType("(", { + beforeExpr, + startsExpr + }), + parenR: new TokenType(")"), + comma: new TokenType(",", { + beforeExpr + }), + semi: new TokenType(";", { + beforeExpr + }), + colon: new TokenType(":", { + beforeExpr + }), + doubleColon: new TokenType("::", { + beforeExpr + }), + dot: new TokenType("."), + question: new TokenType("?", { + beforeExpr + }), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", { + beforeExpr + }), + template: new TokenType("template"), + ellipsis: new TokenType("...", { + beforeExpr + }), + backQuote: new TokenType("`", { + startsExpr + }), + dollarBraceL: new TokenType("${", { + beforeExpr, + startsExpr + }), + at: new TokenType("@"), + hash: new TokenType("#", { + startsExpr + }), + interpreterDirective: new TokenType("#!..."), + eq: new TokenType("=", { + beforeExpr, + isAssign + }), + assign: new TokenType("_=", { + beforeExpr, + isAssign + }), + slashAssign: new TokenType("_=", { + beforeExpr, + isAssign + }), + moduloAssign: new TokenType("_=", { + beforeExpr, + isAssign + }), + incDec: new TokenType("++/--", { + prefix, + postfix, + startsExpr + }), + bang: new TokenType("!", { + beforeExpr, + prefix, + startsExpr + }), + tilde: new TokenType("~", { + beforeExpr, + prefix, + startsExpr + }), + pipeline: createBinop("|>", 0), + nullishCoalescing: createBinop("??", 1), + logicalOR: createBinop("||", 1), + logicalAND: createBinop("&&", 2), + bitwiseOR: createBinop("|", 3), + bitwiseXOR: createBinop("^", 4), + bitwiseAND: createBinop("&", 5), + equality: createBinop("==/!=/===/!==", 6), + relational: createBinop("/<=/>=", 7), + bitShift: createBinop("<>/>>>", 8), + plusMin: new TokenType("+/-", { + beforeExpr, + binop: 9, + prefix, + startsExpr + }), + modulo: new TokenType("%", { + binop: 10, + startsExpr + }), + star: new TokenType("*", { + binop: 10 + }), + slash: createBinop("/", 10), + exponent: new TokenType("**", { + beforeExpr, + binop: 11, + rightAssociative: true + }), + _break: createKeyword("break"), + _case: createKeyword("case", { + beforeExpr + }), + _catch: createKeyword("catch"), + _continue: createKeyword("continue"), + _debugger: createKeyword("debugger"), + _default: createKeyword("default", { + beforeExpr + }), + _do: createKeyword("do", { + isLoop, + beforeExpr + }), + _else: createKeyword("else", { + beforeExpr + }), + _finally: createKeyword("finally"), + _for: createKeyword("for", { + isLoop + }), + _function: createKeyword("function", { + startsExpr + }), + _if: createKeyword("if"), + _return: createKeyword("return", { + beforeExpr + }), + _switch: createKeyword("switch"), + _throw: createKeyword("throw", { + beforeExpr, + prefix, + startsExpr + }), + _try: createKeyword("try"), + _var: createKeyword("var"), + _const: createKeyword("const"), + _while: createKeyword("while", { + isLoop + }), + _with: createKeyword("with"), + _new: createKeyword("new", { + beforeExpr, + startsExpr + }), + _this: createKeyword("this", { + startsExpr + }), + _super: createKeyword("super", { + startsExpr + }), + _class: createKeyword("class", { + startsExpr + }), + _extends: createKeyword("extends", { + beforeExpr + }), + _export: createKeyword("export"), + _import: createKeyword("import", { + startsExpr + }), + _null: createKeyword("null", { + startsExpr + }), + _true: createKeyword("true", { + startsExpr + }), + _false: createKeyword("false", { + startsExpr + }), + _in: createKeyword("in", { + beforeExpr, + binop: 7 + }), + _instanceof: createKeyword("instanceof", { + beforeExpr, + binop: 7 + }), + _typeof: createKeyword("typeof", { + beforeExpr, + prefix, + startsExpr + }), + _void: createKeyword("void", { + beforeExpr, + prefix, + startsExpr + }), + _delete: createKeyword("delete", { + beforeExpr, + prefix, + startsExpr + }) +}; + +const lineBreak = /\r\n?|[\n\u2028\u2029]/; +const lineBreakG = new RegExp(lineBreak.source, "g"); +function isNewLine(code) { + switch (code) { + case 10: + case 13: + case 8232: + case 8233: + return true; + + default: + return false; + } +} +const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y; +const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y"); +function isWhitespace(code) { + switch (code) { + case 0x0009: + case 0x000b: + case 0x000c: + case 32: + case 160: + case 5760: + case 0x2000: + case 0x2001: + case 0x2002: + case 0x2003: + case 0x2004: + case 0x2005: + case 0x2006: + case 0x2007: + case 0x2008: + case 0x2009: + case 0x200a: + case 0x202f: + case 0x205f: + case 0x3000: + case 0xfeff: + return true; + + default: + return false; + } +} + +class Position { + constructor(line, col) { + this.line = void 0; + this.column = void 0; + this.line = line; + this.column = col; + } + +} +class SourceLocation { + constructor(start, end) { + this.start = void 0; + this.end = void 0; + this.filename = void 0; + this.identifierName = void 0; + this.start = start; + this.end = end; + } + +} +function getLineInfo(input, offset) { + let line = 1; + let lineStart = 0; + let match; + lineBreakG.lastIndex = 0; + + while ((match = lineBreakG.exec(input)) && match.index < offset) { + line++; + lineStart = lineBreakG.lastIndex; + } + + return new Position(line, offset - lineStart); +} + +class BaseParser { + constructor() { + this.sawUnambiguousESM = false; + this.ambiguousScriptDifferentAst = false; + } + + hasPlugin(name) { + return this.plugins.has(name); + } + + getPluginOption(plugin, name) { + if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name]; + } + +} + +function setTrailingComments(node, comments) { + if (node.trailingComments === undefined) { + node.trailingComments = comments; + } else { + node.trailingComments.unshift(...comments); + } +} + +function setInnerComments(node, comments) { + if (node.innerComments === undefined) { + node.innerComments = comments; + } else if (comments !== undefined) { + node.innerComments.unshift(...comments); + } +} + +function adjustInnerComments(node, elements, commentWS) { + let lastElement = null; + let i = elements.length; + + while (lastElement === null && i > 0) { + lastElement = elements[--i]; + } + + if (lastElement === null || lastElement.start > commentWS.start) { + setInnerComments(node, commentWS.comments); + } else { + setTrailingComments(lastElement, commentWS.comments); + } +} + +class CommentsParser extends BaseParser { + addComment(comment) { + if (this.filename) comment.loc.filename = this.filename; + this.state.comments.push(comment); + } + + processComment(node) { + const { + commentStack + } = this.state; + const commentStackLength = commentStack.length; + if (commentStackLength === 0) return; + let i = commentStackLength - 1; + const lastCommentWS = commentStack[i]; + + if (lastCommentWS.start === node.end) { + lastCommentWS.leadingNode = node; + i--; + } + + const { + start: nodeStart + } = node; + + for (; i >= 0; i--) { + const commentWS = commentStack[i]; + const commentEnd = commentWS.end; + + if (commentEnd > nodeStart) { + commentWS.containingNode = node; + this.finalizeComment(commentWS); + commentStack.splice(i, 1); + } else { + if (commentEnd === nodeStart) { + commentWS.trailingNode = node; + } + + break; + } + } + } + + finalizeComment(commentWS) { + const { + comments + } = commentWS; + + if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) { + if (commentWS.leadingNode !== null) { + setTrailingComments(commentWS.leadingNode, comments); + } + + if (commentWS.trailingNode !== null) { + commentWS.trailingNode.leadingComments = comments; + } + } else { + const { + containingNode: node, + start: commentStart + } = commentWS; + + if (this.input.charCodeAt(commentStart - 1) === 44) { + switch (node.type) { + case "ObjectExpression": + case "ObjectPattern": + case "RecordExpression": + adjustInnerComments(node, node.properties, commentWS); + break; + + case "CallExpression": + case "OptionalCallExpression": + adjustInnerComments(node, node.arguments, commentWS); + break; + + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "ObjectMethod": + case "ClassMethod": + case "ClassPrivateMethod": + adjustInnerComments(node, node.params, commentWS); + break; + + case "ArrayExpression": + case "ArrayPattern": + case "TupleExpression": + adjustInnerComments(node, node.elements, commentWS); + break; + + case "ExportNamedDeclaration": + case "ImportDeclaration": + adjustInnerComments(node, node.specifiers, commentWS); + break; + + default: + { + setInnerComments(node, comments); + } + } + } else { + setInnerComments(node, comments); + } + } + } + + finalizeRemainingComments() { + const { + commentStack + } = this.state; + + for (let i = commentStack.length - 1; i >= 0; i--) { + this.finalizeComment(commentStack[i]); + } + + this.state.commentStack = []; + } + + resetPreviousNodeTrailingComments(node) { + const { + commentStack + } = this.state; + const { + length + } = commentStack; + if (length === 0) return; + const commentWS = commentStack[length - 1]; + + if (commentWS.leadingNode === node) { + commentWS.leadingNode = null; + } + } + +} + +const ErrorCodes = Object.freeze({ + SyntaxError: "BABEL_PARSER_SYNTAX_ERROR", + SourceTypeModuleError: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED" +}); + +const ErrorMessages = makeErrorTemplates({ + AccessorIsGenerator: "A %0ter cannot be a generator.", + ArgumentsInClass: "'arguments' is only allowed in functions and class methods.", + AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.", + AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.", + AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.", + AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.", + AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.", + AwaitNotInAsyncFunction: "'await' is only allowed within async functions.", + BadGetterArity: "A 'get' accesor must not have any formal parameters.", + BadSetterArity: "A 'set' accesor must have exactly one formal parameter.", + BadSetterRestParameter: "A 'set' accesor function argument must not be a rest parameter.", + ConstructorClassField: "Classes may not have a field named 'constructor'.", + ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.", + ConstructorIsAccessor: "Class constructor may not be an accessor.", + ConstructorIsAsync: "Constructor can't be an async function.", + ConstructorIsGenerator: "Constructor can't be a generator.", + DeclarationMissingInitializer: "'%0' require an initialization value.", + DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax.", + DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?", + DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.", + DecoratorSemicolon: "Decorators must not be followed by a semicolon.", + DecoratorStaticBlock: "Decorators can't be used with a static block.", + DeletePrivateField: "Deleting a private field is not allowed.", + DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.", + DuplicateConstructor: "Duplicate constructor in the same class.", + DuplicateDefaultExport: "Only one default export allowed per module.", + DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.", + DuplicateProto: "Redefinition of __proto__ property.", + DuplicateRegExpFlags: "Duplicate regular expression flag.", + ElementAfterRest: "Rest element must be last element.", + EscapedCharNotAnIdentifier: "Invalid Unicode escape.", + ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { '%0' as '%1' } from 'some-module'`?", + ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.", + ForInOfLoopInitializer: "'%0' loop variable declaration may not have an initializer.", + ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.", + ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.", + GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.", + IllegalBreakContinue: "Unsyntactic %0.", + IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.", + IllegalReturn: "'return' outside of function.", + ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?', + ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.", + ImportCallArity: "`import()` requires exactly %0.", + ImportCallNotNewExpression: "Cannot use new with import(...).", + ImportCallSpreadArgument: "`...` is not allowed in `import()`.", + InvalidBigIntLiteral: "Invalid BigIntLiteral.", + InvalidCodePoint: "Code point out of bounds.", + InvalidDecimal: "Invalid decimal.", + InvalidDigit: "Expected number in radix %0.", + InvalidEscapeSequence: "Bad character escape sequence.", + InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.", + InvalidEscapedReservedWord: "Escape sequence in keyword %0.", + InvalidIdentifier: "Invalid identifier %0.", + InvalidLhs: "Invalid left-hand side in %0.", + InvalidLhsBinding: "Binding invalid left-hand side in %0.", + InvalidNumber: "Invalid number.", + InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.", + InvalidOrUnexpectedToken: "Unexpected character '%0'.", + InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.", + InvalidPrivateFieldResolution: "Private name #%0 is not defined.", + InvalidPropertyBindingPattern: "Binding member expression.", + InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.", + InvalidRestAssignmentPattern: "Invalid rest operator's argument.", + LabelRedeclaration: "Label '%0' is already declared.", + LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.", + LineTerminatorBeforeArrow: "No line break is allowed before '=>'.", + MalformedRegExpFlags: "Invalid regular expression flag.", + MissingClassName: "A class name is required.", + MissingEqInAssignment: "Only '=' operator can be used for specifying default value.", + MissingSemicolon: "Missing semicolon.", + MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.", + MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.", + ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.", + ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.", + ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes.', + ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'.", + ModuleExportUndefined: "Export '%0' is not defined.", + MultipleDefaultsInSwitch: "Multiple default clauses.", + NewlineAfterThrow: "Illegal newline after throw.", + NoCatchOrFinally: "Missing catch or finally clause.", + NumberIdentifier: "Identifier directly after number.", + NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.", + ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.", + OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.", + OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.", + OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.", + ParamDupe: "Argument name clash.", + PatternHasAccessor: "Object pattern can't contain getter or setter.", + PatternHasMethod: "Object pattern can't contain methods.", + PipeBodyIsTighter: "Unexpected %0 after pipeline body; any %0 expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.", + PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.', + PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.", + PipeTopicUnconfiguredToken: 'Invalid topic token %0. In order to use %0 as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "%0" }.', + PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.", + PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.', + PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.", + PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.", + PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.", + PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.", + PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.', + PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`).", + PrivateNameRedeclaration: "Duplicate private name #%0.", + RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", + RecordNoProto: "'__proto__' is not allowed in Record expressions.", + RestTrailingComma: "Unexpected trailing comma after rest element.", + SloppyFunction: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.", + StaticPrototype: "Classes may not have static property named prototype.", + StrictDelete: "Deleting local variable in strict mode.", + StrictEvalArguments: "Assigning to '%0' in strict mode.", + StrictEvalArgumentsBinding: "Binding '%0' in strict mode.", + StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.", + StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.", + StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.", + StrictWith: "'with' in strict mode.", + SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?", + SuperPrivateField: "Private fields can't be accessed on super.", + TrailingDecorator: "Decorators must be attached to a class element.", + TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", + UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.", + UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.', + UnexpectedDigitAfterHash: "Unexpected digit after hash token.", + UnexpectedImportExport: "'import' and 'export' may only appear at the top level.", + UnexpectedKeyword: "Unexpected keyword '%0'.", + UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.", + UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.", + UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.", + UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.", + UnexpectedPrivateField: "Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).", + UnexpectedReservedWord: "Unexpected reserved word '%0'.", + UnexpectedSuper: "'super' is only allowed in object methods and classes.", + UnexpectedToken: "Unexpected token '%0'.", + UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.", + UnsupportedBind: "Binding should be performed on object property.", + UnsupportedDecoratorExport: "A decorated export must export a class declaration.", + UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.", + UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.", + UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1.", + UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.", + UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.", + UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).", + UnterminatedComment: "Unterminated comment.", + UnterminatedRegExp: "Unterminated regular expression.", + UnterminatedString: "Unterminated string constant.", + UnterminatedTemplate: "Unterminated template.", + VarRedeclaration: "Identifier '%0' has already been declared.", + YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.", + YieldInParameter: "Yield expression is not allowed in formal parameters.", + ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0." +}, ErrorCodes.SyntaxError); +const SourceTypeModuleErrorMessages = makeErrorTemplates({ + ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`, + ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'` +}, ErrorCodes.SourceTypeModuleError); + +function keepReasonCodeCompat(reasonCode, syntaxPlugin) { + { + if (syntaxPlugin === "flow" && reasonCode === "PatternIsOptional") { + return "OptionalBindingPattern"; + } + } + return reasonCode; +} + +function makeErrorTemplates(messages, code, syntaxPlugin) { + const templates = {}; + Object.keys(messages).forEach(reasonCode => { + templates[reasonCode] = Object.freeze({ + code, + reasonCode: keepReasonCodeCompat(reasonCode, syntaxPlugin), + template: messages[reasonCode] + }); + }); + return Object.freeze(templates); +} +class ParserError extends CommentsParser { + getLocationForPosition(pos) { + let loc; + if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos); + return loc; + } + + raise(pos, { + code, + reasonCode, + template + }, ...params) { + return this.raiseWithData(pos, { + code, + reasonCode + }, template, ...params); + } + + raiseOverwrite(pos, { + code, + template + }, ...params) { + const loc = this.getLocationForPosition(pos); + const message = template.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`; + + if (this.options.errorRecovery) { + const errors = this.state.errors; + + for (let i = errors.length - 1; i >= 0; i--) { + const error = errors[i]; + + if (error.pos === pos) { + return Object.assign(error, { + message + }); + } else if (error.pos < pos) { + break; + } + } + } + + return this._raise({ + code, + loc, + pos + }, message); + } + + raiseWithData(pos, data, errorTemplate, ...params) { + const loc = this.getLocationForPosition(pos); + const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`; + return this._raise(Object.assign({ + loc, + pos + }, data), message); + } + + _raise(errorContext, message) { + const err = new SyntaxError(message); + Object.assign(err, errorContext); + + if (this.options.errorRecovery) { + if (!this.isLookahead) this.state.errors.push(err); + return err; + } else { + throw err; + } + } + +} + +var estree = (superClass => class extends superClass { + parseRegExpLiteral({ + pattern, + flags + }) { + let regex = null; + + try { + regex = new RegExp(pattern, flags); + } catch (e) {} + + const node = this.estreeParseLiteral(regex); + node.regex = { + pattern, + flags + }; + return node; + } + + parseBigIntLiteral(value) { + let bigInt; + + try { + bigInt = BigInt(value); + } catch (_unused) { + bigInt = null; + } + + const node = this.estreeParseLiteral(bigInt); + node.bigint = String(node.value || value); + return node; + } + + parseDecimalLiteral(value) { + const decimal = null; + const node = this.estreeParseLiteral(decimal); + node.decimal = String(node.value || value); + return node; + } + + estreeParseLiteral(value) { + return this.parseLiteral(value, "Literal"); + } + + parseStringLiteral(value) { + return this.estreeParseLiteral(value); + } + + parseNumericLiteral(value) { + return this.estreeParseLiteral(value); + } + + parseNullLiteral() { + return this.estreeParseLiteral(null); + } + + parseBooleanLiteral(value) { + return this.estreeParseLiteral(value); + } + + directiveToStmt(directive) { + const directiveLiteral = directive.value; + const stmt = this.startNodeAt(directive.start, directive.loc.start); + const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start); + expression.value = directiveLiteral.extra.expressionValue; + expression.raw = directiveLiteral.extra.raw; + stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end); + stmt.directive = directiveLiteral.extra.raw.slice(1, -1); + return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end); + } + + initFunction(node, isAsync) { + super.initFunction(node, isAsync); + node.expression = false; + } + + checkDeclaration(node) { + if (node != null && this.isObjectProperty(node)) { + this.checkDeclaration(node.value); + } else { + super.checkDeclaration(node); + } + } + + getObjectOrClassMethodParams(method) { + return method.value.params; + } + + isValidDirective(stmt) { + var _stmt$expression$extr; + + return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized); + } + + stmtToDirective(stmt) { + const value = stmt.expression.value; + const directive = super.stmtToDirective(stmt); + this.addExtra(directive.value, "expressionValue", value); + return directive; + } + + parseBlockBody(node, ...args) { + super.parseBlockBody(node, ...args); + const directiveStatements = node.directives.map(d => this.directiveToStmt(d)); + node.body = directiveStatements.concat(node.body); + delete node.directives; + } + + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true); + + if (method.typeParameters) { + method.value.typeParameters = method.typeParameters; + delete method.typeParameters; + } + + classBody.body.push(method); + } + + parseMaybePrivateName(...args) { + const node = super.parseMaybePrivateName(...args); + + if (node.type === "PrivateName" && this.getPluginOption("estree", "classFeatures")) { + return this.convertPrivateNameToPrivateIdentifier(node); + } + + return node; + } + + convertPrivateNameToPrivateIdentifier(node) { + const name = super.getPrivateNameSV(node); + node = node; + delete node.id; + node.name = name; + node.type = "PrivateIdentifier"; + return node; + } + + isPrivateName(node) { + if (!this.getPluginOption("estree", "classFeatures")) { + return super.isPrivateName(node); + } + + return node.type === "PrivateIdentifier"; + } + + getPrivateNameSV(node) { + if (!this.getPluginOption("estree", "classFeatures")) { + return super.getPrivateNameSV(node); + } + + return node.name; + } + + parseLiteral(value, type) { + const node = super.parseLiteral(value, type); + node.raw = node.extra.raw; + delete node.extra; + return node; + } + + parseFunctionBody(node, allowExpression, isMethod = false) { + super.parseFunctionBody(node, allowExpression, isMethod); + node.expression = node.body.type !== "BlockStatement"; + } + + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { + let funcNode = this.startNode(); + funcNode.kind = node.kind; + funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); + funcNode.type = "FunctionExpression"; + delete funcNode.kind; + node.value = funcNode; + + if (type === "ClassPrivateMethod") { + node.computed = false; + } + + type = "MethodDefinition"; + return this.finishNode(node, type); + } + + parseClassProperty(...args) { + const propertyNode = super.parseClassProperty(...args); + + if (this.getPluginOption("estree", "classFeatures")) { + propertyNode.type = "PropertyDefinition"; + } + + return propertyNode; + } + + parseClassPrivateProperty(...args) { + const propertyNode = super.parseClassPrivateProperty(...args); + + if (this.getPluginOption("estree", "classFeatures")) { + propertyNode.type = "PropertyDefinition"; + propertyNode.computed = false; + } + + return propertyNode; + } + + parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { + const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor); + + if (node) { + node.type = "Property"; + if (node.kind === "method") node.kind = "init"; + node.shorthand = false; + } + + return node; + } + + parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) { + const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors); + + if (node) { + node.kind = "init"; + node.type = "Property"; + } + + return node; + } + + isAssignable(node, isBinding) { + if (node != null && this.isObjectProperty(node)) { + return this.isAssignable(node.value, isBinding); + } + + return super.isAssignable(node, isBinding); + } + + toAssignable(node, isLHS = false) { + if (node != null && this.isObjectProperty(node)) { + this.toAssignable(node.value, isLHS); + return node; + } + + return super.toAssignable(node, isLHS); + } + + toAssignableObjectExpressionProp(prop, ...args) { + if (prop.kind === "get" || prop.kind === "set") { + this.raise(prop.key.start, ErrorMessages.PatternHasAccessor); + } else if (prop.method) { + this.raise(prop.key.start, ErrorMessages.PatternHasMethod); + } else { + super.toAssignableObjectExpressionProp(prop, ...args); + } + } + + finishCallExpression(node, optional) { + super.finishCallExpression(node, optional); + + if (node.callee.type === "Import") { + node.type = "ImportExpression"; + node.source = node.arguments[0]; + + if (this.hasPlugin("importAssertions")) { + var _node$arguments$; + + node.attributes = (_node$arguments$ = node.arguments[1]) != null ? _node$arguments$ : null; + } + + delete node.arguments; + delete node.callee; + } + + return node; + } + + toReferencedArguments(node) { + if (node.type === "ImportExpression") { + return; + } + + super.toReferencedArguments(node); + } + + parseExport(node) { + super.parseExport(node); + + switch (node.type) { + case "ExportAllDeclaration": + node.exported = null; + break; + + case "ExportNamedDeclaration": + if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") { + node.type = "ExportAllDeclaration"; + node.exported = node.specifiers[0].exported; + delete node.specifiers; + } + + break; + } + + return node; + } + + parseSubscript(base, startPos, startLoc, noCalls, state) { + const node = super.parseSubscript(base, startPos, startLoc, noCalls, state); + + if (state.optionalChainMember) { + if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") { + node.type = node.type.substring(8); + } + + if (state.stop) { + const chain = this.startNodeAtNode(node); + chain.expression = node; + return this.finishNode(chain, "ChainExpression"); + } + } else if (node.type === "MemberExpression" || node.type === "CallExpression") { + node.optional = false; + } + + return node; + } + + hasPropertyAsPrivateName(node) { + if (node.type === "ChainExpression") { + node = node.expression; + } + + return super.hasPropertyAsPrivateName(node); + } + + isOptionalChain(node) { + return node.type === "ChainExpression"; + } + + isObjectProperty(node) { + return node.type === "Property" && node.kind === "init" && !node.method; + } + + isObjectMethod(node) { + return node.method || node.kind === "get" || node.kind === "set"; + } + +}); + +class TokContext { + constructor(token, preserveSpace) { + this.token = void 0; + this.preserveSpace = void 0; + this.token = token; + this.preserveSpace = !!preserveSpace; + } + +} +const types = { + brace: new TokContext("{"), + template: new TokContext("`", true) +}; + +types$1.braceR.updateContext = context => { + context.pop(); +}; + +types$1.braceL.updateContext = types$1.braceHashL.updateContext = types$1.dollarBraceL.updateContext = context => { + context.push(types.brace); +}; + +types$1.backQuote.updateContext = context => { + if (context[context.length - 1] === types.template) { + context.pop(); + } else { + context.push(types.template); + } +}; + +let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; +const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; +const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + +function isInAstralSet(code, set) { + let pos = 0x10000; + + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + + return false; +} + +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes); +} +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} + +const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +const keywords = new Set(reservedWords.keyword); +const reservedWordsStrictSet = new Set(reservedWords.strict); +const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); +function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; +} +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); +} +function isKeyword(word) { + return keywords.has(word); +} + +function isIteratorStart(current, next) { + return current === 64 && next === 64; +} +const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]); +function canBeReservedWord(word) { + return reservedWordLikeSet.has(word); +} + +const SCOPE_OTHER = 0b000000000, + SCOPE_PROGRAM = 0b000000001, + SCOPE_FUNCTION = 0b000000010, + SCOPE_ARROW = 0b000000100, + SCOPE_SIMPLE_CATCH = 0b000001000, + SCOPE_SUPER = 0b000010000, + SCOPE_DIRECT_SUPER = 0b000100000, + SCOPE_CLASS = 0b001000000, + SCOPE_STATIC_BLOCK = 0b010000000, + SCOPE_TS_MODULE = 0b100000000, + SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE; +const BIND_KIND_VALUE = 0b000000000001, + BIND_KIND_TYPE = 0b000000000010, + BIND_SCOPE_VAR = 0b000000000100, + BIND_SCOPE_LEXICAL = 0b000000001000, + BIND_SCOPE_FUNCTION = 0b000000010000, + BIND_FLAGS_NONE = 0b000001000000, + BIND_FLAGS_CLASS = 0b000010000000, + BIND_FLAGS_TS_ENUM = 0b000100000000, + BIND_FLAGS_TS_CONST_ENUM = 0b001000000000, + BIND_FLAGS_TS_EXPORT_ONLY = 0b010000000000, + BIND_FLAGS_FLOW_DECLARE_FN = 0b100000000000; +const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS, + BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0, + BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0, + BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0, + BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS, + BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0, + BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM, + BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY, + BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE, + BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE, + BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM, + BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY, + BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN; +const CLASS_ELEMENT_FLAG_STATIC = 0b100, + CLASS_ELEMENT_KIND_GETTER = 0b010, + CLASS_ELEMENT_KIND_SETTER = 0b001, + CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER; +const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC, + CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC, + CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER, + CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER, + CLASS_ELEMENT_OTHER = 0; + +class Scope { + constructor(flags) { + this.var = new Set(); + this.lexical = new Set(); + this.functions = new Set(); + this.flags = flags; + } + +} +class ScopeHandler { + constructor(raise, inModule) { + this.scopeStack = []; + this.undefinedExports = new Map(); + this.undefinedPrivateNames = new Map(); + this.raise = raise; + this.inModule = inModule; + } + + get inFunction() { + return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0; + } + + get allowSuper() { + return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0; + } + + get allowDirectSuper() { + return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0; + } + + get inClass() { + return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0; + } + + get inClassAndNotInNonArrowFunction() { + const flags = this.currentThisScopeFlags(); + return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0; + } + + get inStaticBlock() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + + if (flags & SCOPE_STATIC_BLOCK) { + return true; + } + + if (flags & (SCOPE_VAR | SCOPE_CLASS)) { + return false; + } + } + } + + get inNonArrowFunction() { + return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0; + } + + get treatFunctionsAsVar() { + return this.treatFunctionsAsVarInScope(this.currentScope()); + } + + createScope(flags) { + return new Scope(flags); + } + + enter(flags) { + this.scopeStack.push(this.createScope(flags)); + } + + exit() { + this.scopeStack.pop(); + } + + treatFunctionsAsVarInScope(scope) { + return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM); + } + + declareName(name, bindingType, pos) { + let scope = this.currentScope(); + + if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) { + this.checkRedeclarationInScope(scope, name, bindingType, pos); + + if (bindingType & BIND_SCOPE_FUNCTION) { + scope.functions.add(name); + } else { + scope.lexical.add(name); + } + + if (bindingType & BIND_SCOPE_LEXICAL) { + this.maybeExportDefined(scope, name); + } + } else if (bindingType & BIND_SCOPE_VAR) { + for (let i = this.scopeStack.length - 1; i >= 0; --i) { + scope = this.scopeStack[i]; + this.checkRedeclarationInScope(scope, name, bindingType, pos); + scope.var.add(name); + this.maybeExportDefined(scope, name); + if (scope.flags & SCOPE_VAR) break; + } + } + + if (this.inModule && scope.flags & SCOPE_PROGRAM) { + this.undefinedExports.delete(name); + } + } + + maybeExportDefined(scope, name) { + if (this.inModule && scope.flags & SCOPE_PROGRAM) { + this.undefinedExports.delete(name); + } + } + + checkRedeclarationInScope(scope, name, bindingType, pos) { + if (this.isRedeclaredInScope(scope, name, bindingType)) { + this.raise(pos, ErrorMessages.VarRedeclaration, name); + } + } + + isRedeclaredInScope(scope, name, bindingType) { + if (!(bindingType & BIND_KIND_VALUE)) return false; + + if (bindingType & BIND_SCOPE_LEXICAL) { + return scope.lexical.has(name) || scope.functions.has(name) || scope.var.has(name); + } + + if (bindingType & BIND_SCOPE_FUNCTION) { + return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name); + } + + return scope.lexical.has(name) && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name); + } + + checkLocalExport(id) { + const { + name + } = id; + const topLevelScope = this.scopeStack[0]; + + if (!topLevelScope.lexical.has(name) && !topLevelScope.var.has(name) && !topLevelScope.functions.has(name)) { + this.undefinedExports.set(name, id.start); + } + } + + currentScope() { + return this.scopeStack[this.scopeStack.length - 1]; + } + + currentVarScopeFlags() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + + if (flags & SCOPE_VAR) { + return flags; + } + } + } + + currentThisScopeFlags() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + + if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) { + return flags; + } + } + } + +} + +class FlowScope extends Scope { + constructor(...args) { + super(...args); + this.declareFunctions = new Set(); + } + +} + +class FlowScopeHandler extends ScopeHandler { + createScope(flags) { + return new FlowScope(flags); + } + + declareName(name, bindingType, pos) { + const scope = this.currentScope(); + + if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) { + this.checkRedeclarationInScope(scope, name, bindingType, pos); + this.maybeExportDefined(scope, name); + scope.declareFunctions.add(name); + return; + } + + super.declareName(...arguments); + } + + isRedeclaredInScope(scope, name, bindingType) { + if (super.isRedeclaredInScope(...arguments)) return true; + + if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) { + return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name)); + } + + return false; + } + + checkLocalExport(id) { + if (!this.scopeStack[0].declareFunctions.has(id.name)) { + super.checkLocalExport(id); + } + } + +} + +class State { + constructor() { + this.strict = void 0; + this.curLine = void 0; + this.startLoc = void 0; + this.endLoc = void 0; + this.errors = []; + this.potentialArrowAt = -1; + this.noArrowAt = []; + this.noArrowParamsConversionAt = []; + this.maybeInArrowParameters = false; + this.inType = false; + this.noAnonFunctionType = false; + this.inPropertyName = false; + this.hasFlowComment = false; + this.isAmbientContext = false; + this.inAbstractClass = false; + this.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + this.soloAwait = false; + this.inFSharpPipelineDirectBody = false; + this.labels = []; + this.decoratorStack = [[]]; + this.comments = []; + this.commentStack = []; + this.pos = 0; + this.lineStart = 0; + this.type = types$1.eof; + this.value = null; + this.start = 0; + this.end = 0; + this.lastTokEndLoc = null; + this.lastTokStartLoc = null; + this.lastTokStart = 0; + this.lastTokEnd = 0; + this.context = [types.brace]; + this.exprAllowed = true; + this.containsEsc = false; + this.strictErrors = new Map(); + this.tokensLength = 0; + } + + init(options) { + this.strict = options.strictMode === false ? false : options.strictMode === true ? true : options.sourceType === "module"; + this.curLine = options.startLine; + this.startLoc = this.endLoc = this.curPosition(); + } + + curPosition() { + return new Position(this.curLine, this.pos - this.lineStart); + } + + clone(skipArrays) { + const state = new State(); + const keys = Object.keys(this); + + for (let i = 0, length = keys.length; i < length; i++) { + const key = keys[i]; + let val = this[key]; + + if (!skipArrays && Array.isArray(val)) { + val = val.slice(); + } + + state[key] = val; + } + + return state; + } + +} + +var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; +}; +const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100]); +const forbiddenNumericSeparatorSiblings = { + decBinOct: [46, 66, 69, 79, 95, 98, 101, 111], + hex: [46, 88, 95, 120] +}; +const allowedNumericSeparatorSiblings = {}; +allowedNumericSeparatorSiblings.bin = [48, 49]; +allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55]; +allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57]; +allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102]; +class Token { + constructor(state) { + this.type = state.type; + this.value = state.value; + this.start = state.start; + this.end = state.end; + this.loc = new SourceLocation(state.startLoc, state.endLoc); + } + +} +class Tokenizer extends ParserError { + constructor(options, input) { + super(); + this.isLookahead = void 0; + this.tokens = []; + this.state = new State(); + this.state.init(options); + this.input = input; + this.length = input.length; + this.isLookahead = false; + } + + pushToken(token) { + this.tokens.length = this.state.tokensLength; + this.tokens.push(token); + ++this.state.tokensLength; + } + + next() { + this.checkKeywordEscapes(); + + if (this.options.tokens) { + this.pushToken(new Token(this.state)); + } + + this.state.lastTokEnd = this.state.end; + this.state.lastTokStart = this.state.start; + this.state.lastTokEndLoc = this.state.endLoc; + this.state.lastTokStartLoc = this.state.startLoc; + this.nextToken(); + } + + eat(type) { + if (this.match(type)) { + this.next(); + return true; + } else { + return false; + } + } + + match(type) { + return this.state.type === type; + } + + createLookaheadState(state) { + return { + pos: state.pos, + value: null, + type: state.type, + start: state.start, + end: state.end, + lastTokEnd: state.end, + context: [this.curContext()], + inType: state.inType + }; + } + + lookahead() { + const old = this.state; + this.state = this.createLookaheadState(old); + this.isLookahead = true; + this.nextToken(); + this.isLookahead = false; + const curr = this.state; + this.state = old; + return curr; + } + + nextTokenStart() { + return this.nextTokenStartSince(this.state.pos); + } + + nextTokenStartSince(pos) { + skipWhiteSpace.lastIndex = pos; + return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos; + } + + lookaheadCharCode() { + return this.input.charCodeAt(this.nextTokenStart()); + } + + codePointAtPos(pos) { + let cp = this.input.charCodeAt(pos); + + if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) { + const trail = this.input.charCodeAt(pos); + + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + + return cp; + } + + setStrict(strict) { + this.state.strict = strict; + + if (strict) { + this.state.strictErrors.forEach((message, pos) => this.raise(pos, message)); + this.state.strictErrors.clear(); + } + } + + curContext() { + return this.state.context[this.state.context.length - 1]; + } + + nextToken() { + const curContext = this.curContext(); + if (!curContext.preserveSpace) this.skipSpace(); + this.state.start = this.state.pos; + if (!this.isLookahead) this.state.startLoc = this.state.curPosition(); + + if (this.state.pos >= this.length) { + this.finishToken(types$1.eof); + return; + } + + if (curContext === types.template) { + this.readTmplToken(); + } else { + this.getTokenFromCode(this.codePointAtPos(this.state.pos)); + } + } + + skipBlockComment() { + let startLoc; + if (!this.isLookahead) startLoc = this.state.curPosition(); + const start = this.state.pos; + const end = this.input.indexOf("*/", start + 2); + if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment); + this.state.pos = end + 2; + lineBreakG.lastIndex = start + 2; + + while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) { + ++this.state.curLine; + this.state.lineStart = lineBreakG.lastIndex; + } + + if (this.isLookahead) return; + const comment = { + type: "CommentBlock", + value: this.input.slice(start + 2, end), + start, + end: end + 2, + loc: new SourceLocation(startLoc, this.state.curPosition()) + }; + if (this.options.tokens) this.pushToken(comment); + return comment; + } + + skipLineComment(startSkip) { + const start = this.state.pos; + let startLoc; + if (!this.isLookahead) startLoc = this.state.curPosition(); + let ch = this.input.charCodeAt(this.state.pos += startSkip); + + if (this.state.pos < this.length) { + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + } + + if (this.isLookahead) return; + const end = this.state.pos; + const value = this.input.slice(start + startSkip, end); + const comment = { + type: "CommentLine", + value, + start, + end, + loc: new SourceLocation(startLoc, this.state.curPosition()) + }; + if (this.options.tokens) this.pushToken(comment); + return comment; + } + + skipSpace() { + const spaceStart = this.state.pos; + const comments = []; + + loop: while (this.state.pos < this.length) { + const ch = this.input.charCodeAt(this.state.pos); + + switch (ch) { + case 32: + case 160: + case 9: + ++this.state.pos; + break; + + case 13: + if (this.input.charCodeAt(this.state.pos + 1) === 10) { + ++this.state.pos; + } + + case 10: + case 8232: + case 8233: + ++this.state.pos; + ++this.state.curLine; + this.state.lineStart = this.state.pos; + break; + + case 47: + switch (this.input.charCodeAt(this.state.pos + 1)) { + case 42: + { + const comment = this.skipBlockComment(); + + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + + break; + } + + case 47: + { + const comment = this.skipLineComment(2); + + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + + break; + } + + default: + break loop; + } + + break; + + default: + if (isWhitespace(ch)) { + ++this.state.pos; + } else if (ch === 45 && !this.inModule) { + const pos = this.state.pos; + + if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) { + const comment = this.skipLineComment(3); + + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + } else { + break loop; + } + } else if (ch === 60 && !this.inModule) { + const pos = this.state.pos; + + if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) { + const comment = this.skipLineComment(4); + + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + } else { + break loop; + } + } else { + break loop; + } + + } + } + + if (comments.length > 0) { + const end = this.state.pos; + const CommentWhitespace = { + start: spaceStart, + end, + comments, + leadingNode: null, + trailingNode: null, + containingNode: null + }; + this.state.commentStack.push(CommentWhitespace); + } + } + + finishToken(type, val) { + this.state.end = this.state.pos; + const prevType = this.state.type; + this.state.type = type; + this.state.value = val; + + if (!this.isLookahead) { + this.state.endLoc = this.state.curPosition(); + this.updateContext(prevType); + } + } + + readToken_numberSign() { + if (this.state.pos === 0 && this.readToken_interpreter()) { + return; + } + + const nextPos = this.state.pos + 1; + const next = this.codePointAtPos(nextPos); + + if (next >= 48 && next <= 57) { + throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash); + } + + if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) { + this.expectPlugin("recordAndTuple"); + + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") { + throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType); + } + + this.state.pos += 2; + + if (next === 123) { + this.finishToken(types$1.braceHashL); + } else { + this.finishToken(types$1.bracketHashL); + } + } else if (isIdentifierStart(next)) { + ++this.state.pos; + this.finishToken(types$1.privateName, this.readWord1(next)); + } else if (next === 92) { + ++this.state.pos; + this.finishToken(types$1.privateName, this.readWord1()); + } else { + this.finishOp(types$1.hash, 1); + } + } + + readToken_dot() { + const next = this.input.charCodeAt(this.state.pos + 1); + + if (next >= 48 && next <= 57) { + this.readNumber(true); + return; + } + + if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) { + this.state.pos += 3; + this.finishToken(types$1.ellipsis); + } else { + ++this.state.pos; + this.finishToken(types$1.dot); + } + } + + readToken_slash() { + const next = this.input.charCodeAt(this.state.pos + 1); + + if (next === 61) { + this.finishOp(types$1.slashAssign, 2); + } else { + this.finishOp(types$1.slash, 1); + } + } + + readToken_interpreter() { + if (this.state.pos !== 0 || this.length < 2) return false; + let ch = this.input.charCodeAt(this.state.pos + 1); + if (ch !== 33) return false; + const start = this.state.pos; + this.state.pos += 1; + + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + + const value = this.input.slice(start + 2, this.state.pos); + this.finishToken(types$1.interpreterDirective, value); + return true; + } + + readToken_mult_modulo(code) { + let type = code === 42 ? types$1.star : types$1.modulo; + let width = 1; + let next = this.input.charCodeAt(this.state.pos + 1); + + if (code === 42 && next === 42) { + width++; + next = this.input.charCodeAt(this.state.pos + 2); + type = types$1.exponent; + } + + if (next === 61 && !this.state.inType) { + width++; + type = code === 37 ? types$1.moduloAssign : types$1.assign; + } + + this.finishOp(type, width); + } + + readToken_pipe_amp(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + + if (next === code) { + if (this.input.charCodeAt(this.state.pos + 2) === 61) { + this.finishOp(types$1.assign, 3); + } else { + this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2); + } + + return; + } + + if (code === 124) { + if (next === 62) { + this.finishOp(types$1.pipeline, 2); + return; + } + + if (this.hasPlugin("recordAndTuple") && next === 125) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType); + } + + this.state.pos += 2; + this.finishToken(types$1.braceBarR); + return; + } + + if (this.hasPlugin("recordAndTuple") && next === 93) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType); + } + + this.state.pos += 2; + this.finishToken(types$1.bracketBarR); + return; + } + } + + if (next === 61) { + this.finishOp(types$1.assign, 2); + return; + } + + this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1); + } + + readToken_caret() { + const next = this.input.charCodeAt(this.state.pos + 1); + + if (next === 61) { + this.finishOp(types$1.assign, 2); + } else { + this.finishOp(types$1.bitwiseXOR, 1); + } + } + + readToken_plus_min(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + + if (next === code) { + this.finishOp(types$1.incDec, 2); + return; + } + + if (next === 61) { + this.finishOp(types$1.assign, 2); + } else { + this.finishOp(types$1.plusMin, 1); + } + } + + readToken_lt_gt(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + let size = 1; + + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2; + + if (this.input.charCodeAt(this.state.pos + size) === 61) { + this.finishOp(types$1.assign, size + 1); + return; + } + + this.finishOp(types$1.bitShift, size); + return; + } + + if (next === 61) { + size = 2; + } + + this.finishOp(types$1.relational, size); + } + + readToken_eq_excl(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + + if (next === 61) { + this.finishOp(types$1.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2); + return; + } + + if (code === 61 && next === 62) { + this.state.pos += 2; + this.finishToken(types$1.arrow); + return; + } + + this.finishOp(code === 61 ? types$1.eq : types$1.bang, 1); + } + + readToken_question() { + const next = this.input.charCodeAt(this.state.pos + 1); + const next2 = this.input.charCodeAt(this.state.pos + 2); + + if (next === 63) { + if (next2 === 61) { + this.finishOp(types$1.assign, 3); + } else { + this.finishOp(types$1.nullishCoalescing, 2); + } + } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) { + this.state.pos += 2; + this.finishToken(types$1.questionDot); + } else { + ++this.state.pos; + this.finishToken(types$1.question); + } + } + + getTokenFromCode(code) { + switch (code) { + case 46: + this.readToken_dot(); + return; + + case 40: + ++this.state.pos; + this.finishToken(types$1.parenL); + return; + + case 41: + ++this.state.pos; + this.finishToken(types$1.parenR); + return; + + case 59: + ++this.state.pos; + this.finishToken(types$1.semi); + return; + + case 44: + ++this.state.pos; + this.finishToken(types$1.comma); + return; + + case 91: + if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType); + } + + this.state.pos += 2; + this.finishToken(types$1.bracketBarL); + } else { + ++this.state.pos; + this.finishToken(types$1.bracketL); + } + + return; + + case 93: + ++this.state.pos; + this.finishToken(types$1.bracketR); + return; + + case 123: + if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType); + } + + this.state.pos += 2; + this.finishToken(types$1.braceBarL); + } else { + ++this.state.pos; + this.finishToken(types$1.braceL); + } + + return; + + case 125: + ++this.state.pos; + this.finishToken(types$1.braceR); + return; + + case 58: + if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) { + this.finishOp(types$1.doubleColon, 2); + } else { + ++this.state.pos; + this.finishToken(types$1.colon); + } + + return; + + case 63: + this.readToken_question(); + return; + + case 96: + ++this.state.pos; + this.finishToken(types$1.backQuote); + return; + + case 48: + { + const next = this.input.charCodeAt(this.state.pos + 1); + + if (next === 120 || next === 88) { + this.readRadixNumber(16); + return; + } + + if (next === 111 || next === 79) { + this.readRadixNumber(8); + return; + } + + if (next === 98 || next === 66) { + this.readRadixNumber(2); + return; + } + } + + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + this.readNumber(false); + return; + + case 34: + case 39: + this.readString(code); + return; + + case 47: + this.readToken_slash(); + return; + + case 37: + case 42: + this.readToken_mult_modulo(code); + return; + + case 124: + case 38: + this.readToken_pipe_amp(code); + return; + + case 94: + this.readToken_caret(); + return; + + case 43: + case 45: + this.readToken_plus_min(code); + return; + + case 60: + case 62: + this.readToken_lt_gt(code); + return; + + case 61: + case 33: + this.readToken_eq_excl(code); + return; + + case 126: + this.finishOp(types$1.tilde, 1); + return; + + case 64: + ++this.state.pos; + this.finishToken(types$1.at); + return; + + case 35: + this.readToken_numberSign(); + return; + + case 92: + this.readWord(); + return; + + default: + if (isIdentifierStart(code)) { + this.readWord(code); + return; + } + + } + + throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code)); + } + + finishOp(type, size) { + const str = this.input.slice(this.state.pos, this.state.pos + size); + this.state.pos += size; + this.finishToken(type, str); + } + + readRegexp() { + const start = this.state.start + 1; + let escaped, inClass; + let { + pos + } = this.state; + + for (;; ++pos) { + if (pos >= this.length) { + throw this.raise(start, ErrorMessages.UnterminatedRegExp); + } + + const ch = this.input.charCodeAt(pos); + + if (isNewLine(ch)) { + throw this.raise(start, ErrorMessages.UnterminatedRegExp); + } + + if (escaped) { + escaped = false; + } else { + if (ch === 91) { + inClass = true; + } else if (ch === 93 && inClass) { + inClass = false; + } else if (ch === 47 && !inClass) { + break; + } + + escaped = ch === 92; + } + } + + const content = this.input.slice(start, pos); + ++pos; + let mods = ""; + + while (pos < this.length) { + const cp = this.codePointAtPos(pos); + const char = String.fromCharCode(cp); + + if (VALID_REGEX_FLAGS.has(cp)) { + if (mods.includes(char)) { + this.raise(pos + 1, ErrorMessages.DuplicateRegExpFlags); + } + } else if (isIdentifierChar(cp) || cp === 92) { + this.raise(pos + 1, ErrorMessages.MalformedRegExpFlags); + } else { + break; + } + + ++pos; + mods += char; + } + + this.state.pos = pos; + this.finishToken(types$1.regexp, { + pattern: content, + flags: mods + }); + } + + readInt(radix, len, forceLen, allowNumSeparator = true) { + const start = this.state.pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin; + let invalid = false; + let total = 0; + + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = this.input.charCodeAt(this.state.pos); + let val; + + if (code === 95) { + const prev = this.input.charCodeAt(this.state.pos - 1); + const next = this.input.charCodeAt(this.state.pos + 1); + + if (allowedSiblings.indexOf(next) === -1) { + this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator); + } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) { + this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator); + } + + if (!allowNumSeparator) { + this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence); + } + + ++this.state.pos; + continue; + } + + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + + if (val >= radix) { + if (this.options.errorRecovery && val <= 9) { + val = 0; + this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix); + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + + ++this.state.pos; + total = total * radix + val; + } + + if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) { + return null; + } + + return total; + } + + readRadixNumber(radix) { + const start = this.state.pos; + let isBigInt = false; + this.state.pos += 2; + const val = this.readInt(radix); + + if (val == null) { + this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix); + } + + const next = this.input.charCodeAt(this.state.pos); + + if (next === 110) { + ++this.state.pos; + isBigInt = true; + } else if (next === 109) { + throw this.raise(start, ErrorMessages.InvalidDecimal); + } + + if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { + throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier); + } + + if (isBigInt) { + const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, ""); + this.finishToken(types$1.bigint, str); + return; + } + + this.finishToken(types$1.num, val); + } + + readNumber(startsWithDot) { + const start = this.state.pos; + let isFloat = false; + let isBigInt = false; + let isDecimal = false; + let hasExponent = false; + let isOctal = false; + + if (!startsWithDot && this.readInt(10) === null) { + this.raise(start, ErrorMessages.InvalidNumber); + } + + const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; + + if (hasLeadingZero) { + const integer = this.input.slice(start, this.state.pos); + this.recordStrictModeErrors(start, ErrorMessages.StrictOctalLiteral); + + if (!this.state.strict) { + const underscorePos = integer.indexOf("_"); + + if (underscorePos > 0) { + this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator); + } + } + + isOctal = hasLeadingZero && !/[89]/.test(integer); + } + + let next = this.input.charCodeAt(this.state.pos); + + if (next === 46 && !isOctal) { + ++this.state.pos; + this.readInt(10); + isFloat = true; + next = this.input.charCodeAt(this.state.pos); + } + + if ((next === 69 || next === 101) && !isOctal) { + next = this.input.charCodeAt(++this.state.pos); + + if (next === 43 || next === 45) { + ++this.state.pos; + } + + if (this.readInt(10) === null) { + this.raise(start, ErrorMessages.InvalidOrMissingExponent); + } + + isFloat = true; + hasExponent = true; + next = this.input.charCodeAt(this.state.pos); + } + + if (next === 110) { + if (isFloat || hasLeadingZero) { + this.raise(start, ErrorMessages.InvalidBigIntLiteral); + } + + ++this.state.pos; + isBigInt = true; + } + + if (next === 109) { + this.expectPlugin("decimal", this.state.pos); + + if (hasExponent || hasLeadingZero) { + this.raise(start, ErrorMessages.InvalidDecimal); + } + + ++this.state.pos; + isDecimal = true; + } + + if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { + throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier); + } + + const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, ""); + + if (isBigInt) { + this.finishToken(types$1.bigint, str); + return; + } + + if (isDecimal) { + this.finishToken(types$1.decimal, str); + return; + } + + const val = isOctal ? parseInt(str, 8) : parseFloat(str); + this.finishToken(types$1.num, val); + } + + readCodePoint(throwOnInvalid) { + const ch = this.input.charCodeAt(this.state.pos); + let code; + + if (ch === 123) { + const codePos = ++this.state.pos; + code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid); + ++this.state.pos; + + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + this.raise(codePos, ErrorMessages.InvalidCodePoint); + } else { + return null; + } + } + } else { + code = this.readHexChar(4, false, throwOnInvalid); + } + + return code; + } + + readString(quote) { + let out = "", + chunkStart = ++this.state.pos; + + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(this.state.start, ErrorMessages.UnterminatedString); + } + + const ch = this.input.charCodeAt(this.state.pos); + if (ch === quote) break; + + if (ch === 92) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.readEscapedChar(false); + chunkStart = this.state.pos; + } else if (ch === 8232 || ch === 8233) { + ++this.state.pos; + ++this.state.curLine; + this.state.lineStart = this.state.pos; + } else if (isNewLine(ch)) { + throw this.raise(this.state.start, ErrorMessages.UnterminatedString); + } else { + ++this.state.pos; + } + } + + out += this.input.slice(chunkStart, this.state.pos++); + this.finishToken(types$1.string, out); + } + + readTmplToken() { + let out = "", + chunkStart = this.state.pos, + containsInvalid = false; + + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate); + } + + const ch = this.input.charCodeAt(this.state.pos); + + if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) { + if (this.state.pos === this.state.start && this.match(types$1.template)) { + if (ch === 36) { + this.state.pos += 2; + this.finishToken(types$1.dollarBraceL); + return; + } else { + ++this.state.pos; + this.finishToken(types$1.backQuote); + return; + } + } + + out += this.input.slice(chunkStart, this.state.pos); + this.finishToken(types$1.template, containsInvalid ? null : out); + return; + } + + if (ch === 92) { + out += this.input.slice(chunkStart, this.state.pos); + const escaped = this.readEscapedChar(true); + + if (escaped === null) { + containsInvalid = true; + } else { + out += escaped; + } + + chunkStart = this.state.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + ++this.state.pos; + + switch (ch) { + case 13: + if (this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + } + + case 10: + out += "\n"; + break; + + default: + out += String.fromCharCode(ch); + break; + } + + ++this.state.curLine; + this.state.lineStart = this.state.pos; + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + } + + recordStrictModeErrors(pos, message) { + if (this.state.strict && !this.state.strictErrors.has(pos)) { + this.raise(pos, message); + } else { + this.state.strictErrors.set(pos, message); + } + } + + readEscapedChar(inTemplate) { + const throwOnInvalid = !inTemplate; + const ch = this.input.charCodeAt(++this.state.pos); + ++this.state.pos; + + switch (ch) { + case 110: + return "\n"; + + case 114: + return "\r"; + + case 120: + { + const code = this.readHexChar(2, false, throwOnInvalid); + return code === null ? null : String.fromCharCode(code); + } + + case 117: + { + const code = this.readCodePoint(throwOnInvalid); + return code === null ? null : String.fromCodePoint(code); + } + + case 116: + return "\t"; + + case 98: + return "\b"; + + case 118: + return "\u000b"; + + case 102: + return "\f"; + + case 13: + if (this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + } + + case 10: + this.state.lineStart = this.state.pos; + ++this.state.curLine; + + case 8232: + case 8233: + return ""; + + case 56: + case 57: + if (inTemplate) { + return null; + } else { + this.recordStrictModeErrors(this.state.pos - 1, ErrorMessages.StrictNumericEscape); + } + + default: + if (ch >= 48 && ch <= 55) { + const codePos = this.state.pos - 1; + const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + + this.state.pos += octalStr.length - 1; + const next = this.input.charCodeAt(this.state.pos); + + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return null; + } else { + this.recordStrictModeErrors(codePos, ErrorMessages.StrictNumericEscape); + } + } + + return String.fromCharCode(octal); + } + + return String.fromCharCode(ch); + } + } + + readHexChar(len, forceLen, throwOnInvalid) { + const codePos = this.state.pos; + const n = this.readInt(16, len, forceLen, false); + + if (n === null) { + if (throwOnInvalid) { + this.raise(codePos, ErrorMessages.InvalidEscapeSequence); + } else { + this.state.pos = codePos - 1; + } + } + + return n; + } + + readWord1(firstCode) { + this.state.containsEsc = false; + let word = ""; + const start = this.state.pos; + let chunkStart = this.state.pos; + + if (firstCode !== undefined) { + this.state.pos += firstCode <= 0xffff ? 1 : 2; + } + + while (this.state.pos < this.length) { + const ch = this.codePointAtPos(this.state.pos); + + if (isIdentifierChar(ch)) { + this.state.pos += ch <= 0xffff ? 1 : 2; + } else if (ch === 92) { + this.state.containsEsc = true; + word += this.input.slice(chunkStart, this.state.pos); + const escStart = this.state.pos; + const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar; + + if (this.input.charCodeAt(++this.state.pos) !== 117) { + this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape); + chunkStart = this.state.pos - 1; + continue; + } + + ++this.state.pos; + const esc = this.readCodePoint(true); + + if (esc !== null) { + if (!identifierCheck(esc)) { + this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier); + } + + word += String.fromCodePoint(esc); + } + + chunkStart = this.state.pos; + } else { + break; + } + } + + return word + this.input.slice(chunkStart, this.state.pos); + } + + readWord(firstCode) { + const word = this.readWord1(firstCode); + const type = keywords$1.get(word) || types$1.name; + this.finishToken(type, word); + } + + checkKeywordEscapes() { + const kw = this.state.type.keyword; + + if (kw && this.state.containsEsc) { + this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, kw); + } + } + + updateContext(prevType) { + var _this$state$type$upda, _this$state$type; + + (_this$state$type$upda = (_this$state$type = this.state.type).updateContext) == null ? void 0 : _this$state$type$upda.call(_this$state$type, this.state.context); + } + +} + +class ClassScope { + constructor() { + this.privateNames = new Set(); + this.loneAccessors = new Map(); + this.undefinedPrivateNames = new Map(); + } + +} +class ClassScopeHandler { + constructor(raise) { + this.stack = []; + this.undefinedPrivateNames = new Map(); + this.raise = raise; + } + + current() { + return this.stack[this.stack.length - 1]; + } + + enter() { + this.stack.push(new ClassScope()); + } + + exit() { + const oldClassScope = this.stack.pop(); + const current = this.current(); + + for (const [name, pos] of Array.from(oldClassScope.undefinedPrivateNames)) { + if (current) { + if (!current.undefinedPrivateNames.has(name)) { + current.undefinedPrivateNames.set(name, pos); + } + } else { + this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name); + } + } + } + + declarePrivateName(name, elementType, pos) { + const classScope = this.current(); + let redefined = classScope.privateNames.has(name); + + if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) { + const accessor = redefined && classScope.loneAccessors.get(name); + + if (accessor) { + const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC; + const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC; + const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR; + const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR; + redefined = oldKind === newKind || oldStatic !== newStatic; + if (!redefined) classScope.loneAccessors.delete(name); + } else if (!redefined) { + classScope.loneAccessors.set(name, elementType); + } + } + + if (redefined) { + this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name); + } + + classScope.privateNames.add(name); + classScope.undefinedPrivateNames.delete(name); + } + + usePrivateName(name, pos) { + let classScope; + + for (classScope of this.stack) { + if (classScope.privateNames.has(name)) return; + } + + if (classScope) { + classScope.undefinedPrivateNames.set(name, pos); + } else { + this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name); + } + } + +} + +const kExpression = 0, + kMaybeArrowParameterDeclaration = 1, + kMaybeAsyncArrowParameterDeclaration = 2, + kParameterDeclaration = 3; + +class ExpressionScope { + constructor(type = kExpression) { + this.type = void 0; + this.type = type; + } + + canBeArrowParameterDeclaration() { + return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration; + } + + isCertainlyParameterDeclaration() { + return this.type === kParameterDeclaration; + } + +} + +class ArrowHeadParsingScope extends ExpressionScope { + constructor(type) { + super(type); + this.errors = new Map(); + } + + recordDeclarationError(pos, template) { + this.errors.set(pos, template); + } + + clearDeclarationError(pos) { + this.errors.delete(pos); + } + + iterateErrors(iterator) { + this.errors.forEach(iterator); + } + +} + +class ExpressionScopeHandler { + constructor(raise) { + this.stack = [new ExpressionScope()]; + this.raise = raise; + } + + enter(scope) { + this.stack.push(scope); + } + + exit() { + this.stack.pop(); + } + + recordParameterInitializerError(pos, template) { + const { + stack + } = this; + let i = stack.length - 1; + let scope = stack[i]; + + while (!scope.isCertainlyParameterDeclaration()) { + if (scope.canBeArrowParameterDeclaration()) { + scope.recordDeclarationError(pos, template); + } else { + return; + } + + scope = stack[--i]; + } + + this.raise(pos, template); + } + + recordParenthesizedIdentifierError(pos, template) { + const { + stack + } = this; + const scope = stack[stack.length - 1]; + + if (scope.isCertainlyParameterDeclaration()) { + this.raise(pos, template); + } else if (scope.canBeArrowParameterDeclaration()) { + scope.recordDeclarationError(pos, template); + } else { + return; + } + } + + recordAsyncArrowParametersError(pos, template) { + const { + stack + } = this; + let i = stack.length - 1; + let scope = stack[i]; + + while (scope.canBeArrowParameterDeclaration()) { + if (scope.type === kMaybeAsyncArrowParameterDeclaration) { + scope.recordDeclarationError(pos, template); + } + + scope = stack[--i]; + } + } + + validateAsPattern() { + const { + stack + } = this; + const currentScope = stack[stack.length - 1]; + if (!currentScope.canBeArrowParameterDeclaration()) return; + currentScope.iterateErrors((template, pos) => { + this.raise(pos, template); + let i = stack.length - 2; + let scope = stack[i]; + + while (scope.canBeArrowParameterDeclaration()) { + scope.clearDeclarationError(pos); + scope = stack[--i]; + } + }); + } + +} +function newParameterDeclarationScope() { + return new ExpressionScope(kParameterDeclaration); +} +function newArrowHeadScope() { + return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration); +} +function newAsyncArrowScope() { + return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration); +} +function newExpressionScope() { + return new ExpressionScope(); +} + +const PARAM = 0b0000, + PARAM_YIELD = 0b0001, + PARAM_AWAIT = 0b0010, + PARAM_RETURN = 0b0100, + PARAM_IN = 0b1000; +class ProductionParameterHandler { + constructor() { + this.stacks = []; + } + + enter(flags) { + this.stacks.push(flags); + } + + exit() { + this.stacks.pop(); + } + + currentFlags() { + return this.stacks[this.stacks.length - 1]; + } + + get hasAwait() { + return (this.currentFlags() & PARAM_AWAIT) > 0; + } + + get hasYield() { + return (this.currentFlags() & PARAM_YIELD) > 0; + } + + get hasReturn() { + return (this.currentFlags() & PARAM_RETURN) > 0; + } + + get hasIn() { + return (this.currentFlags() & PARAM_IN) > 0; + } + +} +function functionFlags(isAsync, isGenerator) { + return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0); +} + +class UtilParser extends Tokenizer { + addExtra(node, key, val) { + if (!node) return; + const extra = node.extra = node.extra || {}; + extra[key] = val; + } + + isRelational(op) { + return this.match(types$1.relational) && this.state.value === op; + } + + expectRelational(op) { + if (this.isRelational(op)) { + this.next(); + } else { + this.unexpected(null, types$1.relational); + } + } + + isContextual(name) { + return this.match(types$1.name) && this.state.value === name && !this.state.containsEsc; + } + + isUnparsedContextual(nameStart, name) { + const nameEnd = nameStart + name.length; + + if (this.input.slice(nameStart, nameEnd) === name) { + const nextCh = this.input.charCodeAt(nameEnd); + return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800); + } + + return false; + } + + isLookaheadContextual(name) { + const next = this.nextTokenStart(); + return this.isUnparsedContextual(next, name); + } + + eatContextual(name) { + return this.isContextual(name) && this.eat(types$1.name); + } + + expectContextual(name, template) { + if (!this.eatContextual(name)) this.unexpected(null, template); + } + + canInsertSemicolon() { + return this.match(types$1.eof) || this.match(types$1.braceR) || this.hasPrecedingLineBreak(); + } + + hasPrecedingLineBreak() { + return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start)); + } + + hasFollowingLineBreak() { + skipWhiteSpaceToLineBreak.lastIndex = this.state.end; + return skipWhiteSpaceToLineBreak.test(this.input); + } + + isLineTerminator() { + return this.eat(types$1.semi) || this.canInsertSemicolon(); + } + + semicolon(allowAsi = true) { + if (allowAsi ? this.isLineTerminator() : this.eat(types$1.semi)) return; + this.raise(this.state.lastTokEnd, ErrorMessages.MissingSemicolon); + } + + expect(type, pos) { + this.eat(type) || this.unexpected(pos, type); + } + + assertNoSpace(message = "Unexpected space.") { + if (this.state.start > this.state.lastTokEnd) { + this.raise(this.state.lastTokEnd, { + code: ErrorCodes.SyntaxError, + reasonCode: "UnexpectedSpace", + template: message + }); + } + } + + unexpected(pos, messageOrType = { + code: ErrorCodes.SyntaxError, + reasonCode: "UnexpectedToken", + template: "Unexpected token" + }) { + if (messageOrType instanceof TokenType) { + messageOrType = { + code: ErrorCodes.SyntaxError, + reasonCode: "UnexpectedToken", + template: `Unexpected token, expected "${messageOrType.label}"` + }; + } + + throw this.raise(pos != null ? pos : this.state.start, messageOrType); + } + + expectPlugin(name, pos) { + if (!this.hasPlugin(name)) { + throw this.raiseWithData(pos != null ? pos : this.state.start, { + missingPlugin: [name] + }, `This experimental syntax requires enabling the parser plugin: '${name}'`); + } + + return true; + } + + expectOnePlugin(names, pos) { + if (!names.some(n => this.hasPlugin(n))) { + throw this.raiseWithData(pos != null ? pos : this.state.start, { + missingPlugin: names + }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`); + } + } + + tryParse(fn, oldState = this.state.clone()) { + const abortSignal = { + node: null + }; + + try { + const node = fn((node = null) => { + abortSignal.node = node; + throw abortSignal; + }); + + if (this.state.errors.length > oldState.errors.length) { + const failState = this.state; + this.state = oldState; + this.state.tokensLength = failState.tokensLength; + return { + node, + error: failState.errors[oldState.errors.length], + thrown: false, + aborted: false, + failState + }; + } + + return { + node, + error: null, + thrown: false, + aborted: false, + failState: null + }; + } catch (error) { + const failState = this.state; + this.state = oldState; + + if (error instanceof SyntaxError) { + return { + node: null, + error, + thrown: true, + aborted: false, + failState + }; + } + + if (error === abortSignal) { + return { + node: abortSignal.node, + error: null, + thrown: false, + aborted: true, + failState + }; + } + + throw error; + } + } + + checkExpressionErrors(refExpressionErrors, andThrow) { + if (!refExpressionErrors) return false; + const { + shorthandAssign, + doubleProto, + optionalParameters + } = refExpressionErrors; + + if (!andThrow) { + return shorthandAssign >= 0 || doubleProto >= 0 || optionalParameters >= 0; + } + + if (shorthandAssign >= 0) { + this.unexpected(shorthandAssign); + } + + if (doubleProto >= 0) { + this.raise(doubleProto, ErrorMessages.DuplicateProto); + } + + if (optionalParameters >= 0) { + this.unexpected(optionalParameters); + } + } + + isLiteralPropertyName() { + return this.match(types$1.name) || !!this.state.type.keyword || this.match(types$1.string) || this.match(types$1.num) || this.match(types$1.bigint) || this.match(types$1.decimal); + } + + isPrivateName(node) { + return node.type === "PrivateName"; + } + + getPrivateNameSV(node) { + return node.id.name; + } + + hasPropertyAsPrivateName(node) { + return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property); + } + + isOptionalChain(node) { + return node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression"; + } + + isObjectProperty(node) { + return node.type === "ObjectProperty"; + } + + isObjectMethod(node) { + return node.type === "ObjectMethod"; + } + + initializeScopes(inModule = this.options.sourceType === "module") { + const oldLabels = this.state.labels; + this.state.labels = []; + const oldExportedIdentifiers = this.exportedIdentifiers; + this.exportedIdentifiers = new Set(); + const oldInModule = this.inModule; + this.inModule = inModule; + const oldScope = this.scope; + const ScopeHandler = this.getScopeHandler(); + this.scope = new ScopeHandler(this.raise.bind(this), this.inModule); + const oldProdParam = this.prodParam; + this.prodParam = new ProductionParameterHandler(); + const oldClassScope = this.classScope; + this.classScope = new ClassScopeHandler(this.raise.bind(this)); + const oldExpressionScope = this.expressionScope; + this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this)); + return () => { + this.state.labels = oldLabels; + this.exportedIdentifiers = oldExportedIdentifiers; + this.inModule = oldInModule; + this.scope = oldScope; + this.prodParam = oldProdParam; + this.classScope = oldClassScope; + this.expressionScope = oldExpressionScope; + }; + } + + enterInitialScopes() { + let paramFlags = PARAM; + + if (this.inModule) { + paramFlags |= PARAM_AWAIT; + } + + this.scope.enter(SCOPE_PROGRAM); + this.prodParam.enter(paramFlags); + } + +} +class ExpressionErrors { + constructor() { + this.shorthandAssign = -1; + this.doubleProto = -1; + this.optionalParameters = -1; + } + +} + +class Node { + constructor(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + this.loc = new SourceLocation(loc); + if (parser != null && parser.options.ranges) this.range = [pos, 0]; + if (parser != null && parser.filename) this.loc.filename = parser.filename; + } + +} + +const NodePrototype = Node.prototype; +{ + NodePrototype.__clone = function () { + const newNode = new Node(); + const keys = Object.keys(this); + + for (let i = 0, length = keys.length; i < length; i++) { + const key = keys[i]; + + if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") { + newNode[key] = this[key]; + } + } + + return newNode; + }; +} + +function clonePlaceholder(node) { + return cloneIdentifier(node); +} + +function cloneIdentifier(node) { + const { + type, + start, + end, + loc, + range, + extra, + name + } = node; + const cloned = Object.create(NodePrototype); + cloned.type = type; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + cloned.extra = extra; + cloned.name = name; + + if (type === "Placeholder") { + cloned.expectedNode = node.expectedNode; + } + + return cloned; +} +function cloneStringLiteral(node) { + const { + type, + start, + end, + loc, + range, + extra + } = node; + + if (type === "Placeholder") { + return clonePlaceholder(node); + } + + const cloned = Object.create(NodePrototype); + cloned.type = "StringLiteral"; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + cloned.extra = extra; + cloned.value = node.value; + return cloned; +} +class NodeUtils extends UtilParser { + startNode() { + return new Node(this, this.state.start, this.state.startLoc); + } + + startNodeAt(pos, loc) { + return new Node(this, pos, loc); + } + + startNodeAtNode(type) { + return this.startNodeAt(type.start, type.loc.start); + } + + finishNode(node, type) { + return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc); + } + + finishNodeAt(node, type, pos, loc) { + + node.type = type; + node.end = pos; + node.loc.end = loc; + if (this.options.ranges) node.range[1] = pos; + if (this.options.attachComment) this.processComment(node); + return node; + } + + resetStartLocation(node, start, startLoc) { + node.start = start; + node.loc.start = startLoc; + if (this.options.ranges) node.range[0] = start; + } + + resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) { + node.end = end; + node.loc.end = endLoc; + if (this.options.ranges) node.range[1] = end; + } + + resetStartLocationFromNode(node, locationNode) { + this.resetStartLocation(node, locationNode.start, locationNode.loc.start); + } + +} + +const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]); +const FlowErrors = makeErrorTemplates({ + AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.", + AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.", + AssignReservedType: "Cannot overwrite reserved type %0.", + DeclareClassElement: "The `declare` modifier can only appear on class fields.", + DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.", + DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.", + EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.", + EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.", + EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.", + EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.", + EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.", + EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.", + EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.", + EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.", + EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.", + EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.", + EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.", + GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.", + ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.", + InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.", + InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.", + InexactVariance: "Explicit inexact syntax cannot have variance.", + InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.", + MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.", + NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.", + NestedFlowComment: "Cannot have a flow comment inside another flow comment.", + PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.", + SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.", + SpreadVariance: "Spread properties cannot have variance.", + ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.", + ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.", + ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.", + ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.", + ThisParamNoDefault: "The `this` parameter may not have a default value.", + TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.", + UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.", + UnexpectedReservedType: "Unexpected reserved type %0.", + UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.", + UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.", + UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.", + UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".', + UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.", + UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of ` async () => {}`, use `async () => {}`.", + UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead.", + UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.", + UnterminatedFlowComment: "Unterminated flow-comment." +}, ErrorCodes.SyntaxError, "flow"); + +function isEsModuleType(bodyElement) { + return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration"); +} + +function hasTypeImportKind(node) { + return node.importKind === "type" || node.importKind === "typeof"; +} + +function isMaybeDefaultImport(state) { + return (state.type === types$1.name || !!state.type.keyword) && state.value !== "from"; +} + +const exportSuggestions = { + const: "declare export var", + let: "declare export var", + type: "export type", + interface: "export interface" +}; + +function partition(list, test) { + const list1 = []; + const list2 = []; + + for (let i = 0; i < list.length; i++) { + (test(list[i], i, list) ? list1 : list2).push(list[i]); + } + + return [list1, list2]; +} + +const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/; +var flow = (superClass => class extends superClass { + constructor(...args) { + super(...args); + this.flowPragma = undefined; + } + + getScopeHandler() { + return FlowScopeHandler; + } + + shouldParseTypes() { + return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; + } + + shouldParseEnums() { + return !!this.getPluginOption("flow", "enums"); + } + + finishToken(type, val) { + if (type !== types$1.string && type !== types$1.semi && type !== types$1.interpreterDirective) { + if (this.flowPragma === undefined) { + this.flowPragma = null; + } + } + + return super.finishToken(type, val); + } + + addComment(comment) { + if (this.flowPragma === undefined) { + const matches = FLOW_PRAGMA_REGEX.exec(comment.value); + + if (!matches) ; else if (matches[1] === "flow") { + this.flowPragma = "flow"; + } else if (matches[1] === "noflow") { + this.flowPragma = "noflow"; + } else { + throw new Error("Unexpected flow pragma"); + } + } + + return super.addComment(comment); + } + + flowParseTypeInitialiser(tok) { + const oldInType = this.state.inType; + this.state.inType = true; + this.expect(tok || types$1.colon); + const type = this.flowParseType(); + this.state.inType = oldInType; + return type; + } + + flowParsePredicate() { + const node = this.startNode(); + const moduloPos = this.state.start; + this.next(); + this.expectContextual("checks"); + + if (this.state.lastTokStart > moduloPos + 1) { + this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks); + } + + if (this.eat(types$1.parenL)) { + node.value = this.parseExpression(); + this.expect(types$1.parenR); + return this.finishNode(node, "DeclaredPredicate"); + } else { + return this.finishNode(node, "InferredPredicate"); + } + } + + flowParseTypeAndPredicateInitialiser() { + const oldInType = this.state.inType; + this.state.inType = true; + this.expect(types$1.colon); + let type = null; + let predicate = null; + + if (this.match(types$1.modulo)) { + this.state.inType = oldInType; + predicate = this.flowParsePredicate(); + } else { + type = this.flowParseType(); + this.state.inType = oldInType; + + if (this.match(types$1.modulo)) { + predicate = this.flowParsePredicate(); + } + } + + return [type, predicate]; + } + + flowParseDeclareClass(node) { + this.next(); + this.flowParseInterfaceish(node, true); + return this.finishNode(node, "DeclareClass"); + } + + flowParseDeclareFunction(node) { + this.next(); + const id = node.id = this.parseIdentifier(); + const typeNode = this.startNode(); + const typeContainer = this.startNode(); + + if (this.isRelational("<")) { + typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + typeNode.typeParameters = null; + } + + this.expect(types$1.parenL); + const tmp = this.flowParseFunctionTypeParams(); + typeNode.params = tmp.params; + typeNode.rest = tmp.rest; + typeNode.this = tmp._this; + this.expect(types$1.parenR); + [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); + id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); + this.resetEndLocation(id); + this.semicolon(); + this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.start); + return this.finishNode(node, "DeclareFunction"); + } + + flowParseDeclare(node, insideModule) { + if (this.match(types$1._class)) { + return this.flowParseDeclareClass(node); + } else if (this.match(types$1._function)) { + return this.flowParseDeclareFunction(node); + } else if (this.match(types$1._var)) { + return this.flowParseDeclareVariable(node); + } else if (this.eatContextual("module")) { + if (this.match(types$1.dot)) { + return this.flowParseDeclareModuleExports(node); + } else { + if (insideModule) { + this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule); + } + + return this.flowParseDeclareModule(node); + } + } else if (this.isContextual("type")) { + return this.flowParseDeclareTypeAlias(node); + } else if (this.isContextual("opaque")) { + return this.flowParseDeclareOpaqueType(node); + } else if (this.isContextual("interface")) { + return this.flowParseDeclareInterface(node); + } else if (this.match(types$1._export)) { + return this.flowParseDeclareExportDeclaration(node, insideModule); + } else { + throw this.unexpected(); + } + } + + flowParseDeclareVariable(node) { + this.next(); + node.id = this.flowParseTypeAnnotatableIdentifier(true); + this.scope.declareName(node.id.name, BIND_VAR, node.id.start); + this.semicolon(); + return this.finishNode(node, "DeclareVariable"); + } + + flowParseDeclareModule(node) { + this.scope.enter(SCOPE_OTHER); + + if (this.match(types$1.string)) { + node.id = this.parseExprAtom(); + } else { + node.id = this.parseIdentifier(); + } + + const bodyNode = node.body = this.startNode(); + const body = bodyNode.body = []; + this.expect(types$1.braceL); + + while (!this.match(types$1.braceR)) { + let bodyNode = this.startNode(); + + if (this.match(types$1._import)) { + this.next(); + + if (!this.isContextual("type") && !this.match(types$1._typeof)) { + this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule); + } + + this.parseImport(bodyNode); + } else { + this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule); + bodyNode = this.flowParseDeclare(bodyNode, true); + } + + body.push(bodyNode); + } + + this.scope.exit(); + this.expect(types$1.braceR); + this.finishNode(bodyNode, "BlockStatement"); + let kind = null; + let hasModuleExport = false; + body.forEach(bodyElement => { + if (isEsModuleType(bodyElement)) { + if (kind === "CommonJS") { + this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind); + } + + kind = "ES"; + } else if (bodyElement.type === "DeclareModuleExports") { + if (hasModuleExport) { + this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports); + } + + if (kind === "ES") { + this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind); + } + + kind = "CommonJS"; + hasModuleExport = true; + } + }); + node.kind = kind || "CommonJS"; + return this.finishNode(node, "DeclareModule"); + } + + flowParseDeclareExportDeclaration(node, insideModule) { + this.expect(types$1._export); + + if (this.eat(types$1._default)) { + if (this.match(types$1._function) || this.match(types$1._class)) { + node.declaration = this.flowParseDeclare(this.startNode()); + } else { + node.declaration = this.flowParseType(); + this.semicolon(); + } + + node.default = true; + return this.finishNode(node, "DeclareExportDeclaration"); + } else { + if (this.match(types$1._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) { + const label = this.state.value; + const suggestion = exportSuggestions[label]; + throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion); + } + + if (this.match(types$1._var) || this.match(types$1._function) || this.match(types$1._class) || this.isContextual("opaque")) { + node.declaration = this.flowParseDeclare(this.startNode()); + node.default = false; + return this.finishNode(node, "DeclareExportDeclaration"); + } else if (this.match(types$1.star) || this.match(types$1.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) { + node = this.parseExport(node); + + if (node.type === "ExportNamedDeclaration") { + node.type = "ExportDeclaration"; + node.default = false; + delete node.exportKind; + } + + node.type = "Declare" + node.type; + return node; + } + } + + throw this.unexpected(); + } + + flowParseDeclareModuleExports(node) { + this.next(); + this.expectContextual("exports"); + node.typeAnnotation = this.flowParseTypeAnnotation(); + this.semicolon(); + return this.finishNode(node, "DeclareModuleExports"); + } + + flowParseDeclareTypeAlias(node) { + this.next(); + this.flowParseTypeAlias(node); + node.type = "DeclareTypeAlias"; + return node; + } + + flowParseDeclareOpaqueType(node) { + this.next(); + this.flowParseOpaqueType(node, true); + node.type = "DeclareOpaqueType"; + return node; + } + + flowParseDeclareInterface(node) { + this.next(); + this.flowParseInterfaceish(node); + return this.finishNode(node, "DeclareInterface"); + } + + flowParseInterfaceish(node, isClass = false) { + node.id = this.flowParseRestrictedIdentifier(!isClass, true); + this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start); + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + + node.extends = []; + node.implements = []; + node.mixins = []; + + if (this.eat(types$1._extends)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (!isClass && this.eat(types$1.comma)); + } + + if (this.isContextual("mixins")) { + this.next(); + + do { + node.mixins.push(this.flowParseInterfaceExtends()); + } while (this.eat(types$1.comma)); + } + + if (this.isContextual("implements")) { + this.next(); + + do { + node.implements.push(this.flowParseInterfaceExtends()); + } while (this.eat(types$1.comma)); + } + + node.body = this.flowParseObjectType({ + allowStatic: isClass, + allowExact: false, + allowSpread: false, + allowProto: isClass, + allowInexact: false + }); + } + + flowParseInterfaceExtends() { + const node = this.startNode(); + node.id = this.flowParseQualifiedTypeIdentifier(); + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + + return this.finishNode(node, "InterfaceExtends"); + } + + flowParseInterface(node) { + this.flowParseInterfaceish(node); + return this.finishNode(node, "InterfaceDeclaration"); + } + + checkNotUnderscore(word) { + if (word === "_") { + this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore); + } + } + + checkReservedType(word, startLoc, declaration) { + if (!reservedTypes.has(word)) return; + this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word); + } + + flowParseRestrictedIdentifier(liberal, declaration) { + this.checkReservedType(this.state.value, this.state.start, declaration); + return this.parseIdentifier(liberal); + } + + flowParseTypeAlias(node) { + node.id = this.flowParseRestrictedIdentifier(false, true); + this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start); + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + + node.right = this.flowParseTypeInitialiser(types$1.eq); + this.semicolon(); + return this.finishNode(node, "TypeAlias"); + } + + flowParseOpaqueType(node, declare) { + this.expectContextual("type"); + node.id = this.flowParseRestrictedIdentifier(true, true); + this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start); + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + + node.supertype = null; + + if (this.match(types$1.colon)) { + node.supertype = this.flowParseTypeInitialiser(types$1.colon); + } + + node.impltype = null; + + if (!declare) { + node.impltype = this.flowParseTypeInitialiser(types$1.eq); + } + + this.semicolon(); + return this.finishNode(node, "OpaqueType"); + } + + flowParseTypeParameter(requireDefault = false) { + const nodeStart = this.state.start; + const node = this.startNode(); + const variance = this.flowParseVariance(); + const ident = this.flowParseTypeAnnotatableIdentifier(); + node.name = ident.name; + node.variance = variance; + node.bound = ident.typeAnnotation; + + if (this.match(types$1.eq)) { + this.eat(types$1.eq); + node.default = this.flowParseType(); + } else { + if (requireDefault) { + this.raise(nodeStart, FlowErrors.MissingTypeParamDefault); + } + } + + return this.finishNode(node, "TypeParameter"); + } + + flowParseTypeParameterDeclaration() { + const oldInType = this.state.inType; + const node = this.startNode(); + node.params = []; + this.state.inType = true; + + if (this.isRelational("<") || this.match(types$1.jsxTagStart)) { + this.next(); + } else { + this.unexpected(); + } + + let defaultRequired = false; + + do { + const typeParameter = this.flowParseTypeParameter(defaultRequired); + node.params.push(typeParameter); + + if (typeParameter.default) { + defaultRequired = true; + } + + if (!this.isRelational(">")) { + this.expect(types$1.comma); + } + } while (!this.isRelational(">")); + + this.expectRelational(">"); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterDeclaration"); + } + + flowParseTypeParameterInstantiation() { + const node = this.startNode(); + const oldInType = this.state.inType; + node.params = []; + this.state.inType = true; + this.expectRelational("<"); + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = false; + + while (!this.isRelational(">")) { + node.params.push(this.flowParseType()); + + if (!this.isRelational(">")) { + this.expect(types$1.comma); + } + } + + this.state.noAnonFunctionType = oldNoAnonFunctionType; + this.expectRelational(">"); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterInstantiation"); + } + + flowParseTypeParameterInstantiationCallOrNew() { + const node = this.startNode(); + const oldInType = this.state.inType; + node.params = []; + this.state.inType = true; + this.expectRelational("<"); + + while (!this.isRelational(">")) { + node.params.push(this.flowParseTypeOrImplicitInstantiation()); + + if (!this.isRelational(">")) { + this.expect(types$1.comma); + } + } + + this.expectRelational(">"); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterInstantiation"); + } + + flowParseInterfaceType() { + const node = this.startNode(); + this.expectContextual("interface"); + node.extends = []; + + if (this.eat(types$1._extends)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (this.eat(types$1.comma)); + } + + node.body = this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: false, + allowProto: false, + allowInexact: false + }); + return this.finishNode(node, "InterfaceTypeAnnotation"); + } + + flowParseObjectPropertyKey() { + return this.match(types$1.num) || this.match(types$1.string) ? this.parseExprAtom() : this.parseIdentifier(true); + } + + flowParseObjectTypeIndexer(node, isStatic, variance) { + node.static = isStatic; + + if (this.lookahead().type === types$1.colon) { + node.id = this.flowParseObjectPropertyKey(); + node.key = this.flowParseTypeInitialiser(); + } else { + node.id = null; + node.key = this.flowParseType(); + } + + this.expect(types$1.bracketR); + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + return this.finishNode(node, "ObjectTypeIndexer"); + } + + flowParseObjectTypeInternalSlot(node, isStatic) { + node.static = isStatic; + node.id = this.flowParseObjectPropertyKey(); + this.expect(types$1.bracketR); + this.expect(types$1.bracketR); + + if (this.isRelational("<") || this.match(types$1.parenL)) { + node.method = true; + node.optional = false; + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start)); + } else { + node.method = false; + + if (this.eat(types$1.question)) { + node.optional = true; + } + + node.value = this.flowParseTypeInitialiser(); + } + + return this.finishNode(node, "ObjectTypeInternalSlot"); + } + + flowParseObjectTypeMethodish(node) { + node.params = []; + node.rest = null; + node.typeParameters = null; + node.this = null; + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + + this.expect(types$1.parenL); + + if (this.match(types$1._this)) { + node.this = this.flowParseFunctionTypeParam(true); + node.this.name = null; + + if (!this.match(types$1.parenR)) { + this.expect(types$1.comma); + } + } + + while (!this.match(types$1.parenR) && !this.match(types$1.ellipsis)) { + node.params.push(this.flowParseFunctionTypeParam(false)); + + if (!this.match(types$1.parenR)) { + this.expect(types$1.comma); + } + } + + if (this.eat(types$1.ellipsis)) { + node.rest = this.flowParseFunctionTypeParam(false); + } + + this.expect(types$1.parenR); + node.returnType = this.flowParseTypeInitialiser(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + + flowParseObjectTypeCallProperty(node, isStatic) { + const valueNode = this.startNode(); + node.static = isStatic; + node.value = this.flowParseObjectTypeMethodish(valueNode); + return this.finishNode(node, "ObjectTypeCallProperty"); + } + + flowParseObjectType({ + allowStatic, + allowExact, + allowSpread, + allowProto, + allowInexact + }) { + const oldInType = this.state.inType; + this.state.inType = true; + const nodeStart = this.startNode(); + nodeStart.callProperties = []; + nodeStart.properties = []; + nodeStart.indexers = []; + nodeStart.internalSlots = []; + let endDelim; + let exact; + let inexact = false; + + if (allowExact && this.match(types$1.braceBarL)) { + this.expect(types$1.braceBarL); + endDelim = types$1.braceBarR; + exact = true; + } else { + this.expect(types$1.braceL); + endDelim = types$1.braceR; + exact = false; + } + + nodeStart.exact = exact; + + while (!this.match(endDelim)) { + let isStatic = false; + let protoStart = null; + let inexactStart = null; + const node = this.startNode(); + + if (allowProto && this.isContextual("proto")) { + const lookahead = this.lookahead(); + + if (lookahead.type !== types$1.colon && lookahead.type !== types$1.question) { + this.next(); + protoStart = this.state.start; + allowStatic = false; + } + } + + if (allowStatic && this.isContextual("static")) { + const lookahead = this.lookahead(); + + if (lookahead.type !== types$1.colon && lookahead.type !== types$1.question) { + this.next(); + isStatic = true; + } + } + + const variance = this.flowParseVariance(); + + if (this.eat(types$1.bracketL)) { + if (protoStart != null) { + this.unexpected(protoStart); + } + + if (this.eat(types$1.bracketL)) { + if (variance) { + this.unexpected(variance.start); + } + + nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic)); + } else { + nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance)); + } + } else if (this.match(types$1.parenL) || this.isRelational("<")) { + if (protoStart != null) { + this.unexpected(protoStart); + } + + if (variance) { + this.unexpected(variance.start); + } + + nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic)); + } else { + let kind = "init"; + + if (this.isContextual("get") || this.isContextual("set")) { + const lookahead = this.lookahead(); + + if (lookahead.type === types$1.name || lookahead.type === types$1.string || lookahead.type === types$1.num) { + kind = this.state.value; + this.next(); + } + } + + const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact); + + if (propOrInexact === null) { + inexact = true; + inexactStart = this.state.lastTokStart; + } else { + nodeStart.properties.push(propOrInexact); + } + } + + this.flowObjectTypeSemicolon(); + + if (inexactStart && !this.match(types$1.braceR) && !this.match(types$1.braceBarR)) { + this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject); + } + } + + this.expect(endDelim); + + if (allowSpread) { + nodeStart.inexact = inexact; + } + + const out = this.finishNode(nodeStart, "ObjectTypeAnnotation"); + this.state.inType = oldInType; + return out; + } + + flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) { + if (this.eat(types$1.ellipsis)) { + const isInexactToken = this.match(types$1.comma) || this.match(types$1.semi) || this.match(types$1.braceR) || this.match(types$1.braceBarR); + + if (isInexactToken) { + if (!allowSpread) { + this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject); + } else if (!allowInexact) { + this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact); + } + + if (variance) { + this.raise(variance.start, FlowErrors.InexactVariance); + } + + return null; + } + + if (!allowSpread) { + this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType); + } + + if (protoStart != null) { + this.unexpected(protoStart); + } + + if (variance) { + this.raise(variance.start, FlowErrors.SpreadVariance); + } + + node.argument = this.flowParseType(); + return this.finishNode(node, "ObjectTypeSpreadProperty"); + } else { + node.key = this.flowParseObjectPropertyKey(); + node.static = isStatic; + node.proto = protoStart != null; + node.kind = kind; + let optional = false; + + if (this.isRelational("<") || this.match(types$1.parenL)) { + node.method = true; + + if (protoStart != null) { + this.unexpected(protoStart); + } + + if (variance) { + this.unexpected(variance.start); + } + + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start)); + + if (kind === "get" || kind === "set") { + this.flowCheckGetterSetterParams(node); + } + + if (!allowSpread && node.key.name === "constructor" && node.value.this) { + this.raise(node.value.this.start, FlowErrors.ThisParamBannedInConstructor); + } + } else { + if (kind !== "init") this.unexpected(); + node.method = false; + + if (this.eat(types$1.question)) { + optional = true; + } + + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + } + + node.optional = optional; + return this.finishNode(node, "ObjectTypeProperty"); + } + } + + flowCheckGetterSetterParams(property) { + const paramCount = property.kind === "get" ? 0 : 1; + const start = property.start; + const length = property.value.params.length + (property.value.rest ? 1 : 0); + + if (property.value.this) { + this.raise(property.value.this.start, property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam); + } + + if (length !== paramCount) { + if (property.kind === "get") { + this.raise(start, ErrorMessages.BadGetterArity); + } else { + this.raise(start, ErrorMessages.BadSetterArity); + } + } + + if (property.kind === "set" && property.value.rest) { + this.raise(start, ErrorMessages.BadSetterRestParameter); + } + } + + flowObjectTypeSemicolon() { + if (!this.eat(types$1.semi) && !this.eat(types$1.comma) && !this.match(types$1.braceR) && !this.match(types$1.braceBarR)) { + this.unexpected(); + } + } + + flowParseQualifiedTypeIdentifier(startPos, startLoc, id) { + startPos = startPos || this.state.start; + startLoc = startLoc || this.state.startLoc; + let node = id || this.flowParseRestrictedIdentifier(true); + + while (this.eat(types$1.dot)) { + const node2 = this.startNodeAt(startPos, startLoc); + node2.qualification = node; + node2.id = this.flowParseRestrictedIdentifier(true); + node = this.finishNode(node2, "QualifiedTypeIdentifier"); + } + + return node; + } + + flowParseGenericType(startPos, startLoc, id) { + const node = this.startNodeAt(startPos, startLoc); + node.typeParameters = null; + node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id); + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } + + return this.finishNode(node, "GenericTypeAnnotation"); + } + + flowParseTypeofType() { + const node = this.startNode(); + this.expect(types$1._typeof); + node.argument = this.flowParsePrimaryType(); + return this.finishNode(node, "TypeofTypeAnnotation"); + } + + flowParseTupleType() { + const node = this.startNode(); + node.types = []; + this.expect(types$1.bracketL); + + while (this.state.pos < this.length && !this.match(types$1.bracketR)) { + node.types.push(this.flowParseType()); + if (this.match(types$1.bracketR)) break; + this.expect(types$1.comma); + } + + this.expect(types$1.bracketR); + return this.finishNode(node, "TupleTypeAnnotation"); + } + + flowParseFunctionTypeParam(first) { + let name = null; + let optional = false; + let typeAnnotation = null; + const node = this.startNode(); + const lh = this.lookahead(); + const isThis = this.state.type === types$1._this; + + if (lh.type === types$1.colon || lh.type === types$1.question) { + if (isThis && !first) { + this.raise(node.start, FlowErrors.ThisParamMustBeFirst); + } + + name = this.parseIdentifier(isThis); + + if (this.eat(types$1.question)) { + optional = true; + + if (isThis) { + this.raise(node.start, FlowErrors.ThisParamMayNotBeOptional); + } + } + + typeAnnotation = this.flowParseTypeInitialiser(); + } else { + typeAnnotation = this.flowParseType(); + } + + node.name = name; + node.optional = optional; + node.typeAnnotation = typeAnnotation; + return this.finishNode(node, "FunctionTypeParam"); + } + + reinterpretTypeAsFunctionTypeParam(type) { + const node = this.startNodeAt(type.start, type.loc.start); + node.name = null; + node.optional = false; + node.typeAnnotation = type; + return this.finishNode(node, "FunctionTypeParam"); + } + + flowParseFunctionTypeParams(params = []) { + let rest = null; + let _this = null; + + if (this.match(types$1._this)) { + _this = this.flowParseFunctionTypeParam(true); + _this.name = null; + + if (!this.match(types$1.parenR)) { + this.expect(types$1.comma); + } + } + + while (!this.match(types$1.parenR) && !this.match(types$1.ellipsis)) { + params.push(this.flowParseFunctionTypeParam(false)); + + if (!this.match(types$1.parenR)) { + this.expect(types$1.comma); + } + } + + if (this.eat(types$1.ellipsis)) { + rest = this.flowParseFunctionTypeParam(false); + } + + return { + params, + rest, + _this + }; + } + + flowIdentToTypeAnnotation(startPos, startLoc, node, id) { + switch (id.name) { + case "any": + return this.finishNode(node, "AnyTypeAnnotation"); + + case "bool": + case "boolean": + return this.finishNode(node, "BooleanTypeAnnotation"); + + case "mixed": + return this.finishNode(node, "MixedTypeAnnotation"); + + case "empty": + return this.finishNode(node, "EmptyTypeAnnotation"); + + case "number": + return this.finishNode(node, "NumberTypeAnnotation"); + + case "string": + return this.finishNode(node, "StringTypeAnnotation"); + + case "symbol": + return this.finishNode(node, "SymbolTypeAnnotation"); + + default: + this.checkNotUnderscore(id.name); + return this.flowParseGenericType(startPos, startLoc, id); + } + } + + flowParsePrimaryType() { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + const node = this.startNode(); + let tmp; + let type; + let isGroupedType = false; + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + + switch (this.state.type) { + case types$1.name: + if (this.isContextual("interface")) { + return this.flowParseInterfaceType(); + } + + return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier()); + + case types$1.braceL: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: true, + allowProto: false, + allowInexact: true + }); + + case types$1.braceBarL: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: true, + allowSpread: true, + allowProto: false, + allowInexact: false + }); + + case types$1.bracketL: + this.state.noAnonFunctionType = false; + type = this.flowParseTupleType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + return type; + + case types$1.relational: + if (this.state.value === "<") { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + this.expect(types$1.parenL); + tmp = this.flowParseFunctionTypeParams(); + node.params = tmp.params; + node.rest = tmp.rest; + node.this = tmp._this; + this.expect(types$1.parenR); + this.expect(types$1.arrow); + node.returnType = this.flowParseType(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + + break; + + case types$1.parenL: + this.next(); + + if (!this.match(types$1.parenR) && !this.match(types$1.ellipsis)) { + if (this.match(types$1.name) || this.match(types$1._this)) { + const token = this.lookahead().type; + isGroupedType = token !== types$1.question && token !== types$1.colon; + } else { + isGroupedType = true; + } + } + + if (isGroupedType) { + this.state.noAnonFunctionType = false; + type = this.flowParseType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + + if (this.state.noAnonFunctionType || !(this.match(types$1.comma) || this.match(types$1.parenR) && this.lookahead().type === types$1.arrow)) { + this.expect(types$1.parenR); + return type; + } else { + this.eat(types$1.comma); + } + } + + if (type) { + tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]); + } else { + tmp = this.flowParseFunctionTypeParams(); + } + + node.params = tmp.params; + node.rest = tmp.rest; + node.this = tmp._this; + this.expect(types$1.parenR); + this.expect(types$1.arrow); + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + + case types$1.string: + return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation"); + + case types$1._true: + case types$1._false: + node.value = this.match(types$1._true); + this.next(); + return this.finishNode(node, "BooleanLiteralTypeAnnotation"); + + case types$1.plusMin: + if (this.state.value === "-") { + this.next(); + + if (this.match(types$1.num)) { + return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node); + } + + if (this.match(types$1.bigint)) { + return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node); + } + + throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand); + } + + throw this.unexpected(); + + case types$1.num: + return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); + + case types$1.bigint: + return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation"); + + case types$1._void: + this.next(); + return this.finishNode(node, "VoidTypeAnnotation"); + + case types$1._null: + this.next(); + return this.finishNode(node, "NullLiteralTypeAnnotation"); + + case types$1._this: + this.next(); + return this.finishNode(node, "ThisTypeAnnotation"); + + case types$1.star: + this.next(); + return this.finishNode(node, "ExistsTypeAnnotation"); + + default: + if (this.state.type.keyword === "typeof") { + return this.flowParseTypeofType(); + } else if (this.state.type.keyword) { + const label = this.state.type.label; + this.next(); + return super.createIdentifier(node, label); + } + + } + + throw this.unexpected(); + } + + flowParsePostfixType() { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + let type = this.flowParsePrimaryType(); + let seenOptionalIndexedAccess = false; + + while ((this.match(types$1.bracketL) || this.match(types$1.questionDot)) && !this.canInsertSemicolon()) { + const node = this.startNodeAt(startPos, startLoc); + const optional = this.eat(types$1.questionDot); + seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional; + this.expect(types$1.bracketL); + + if (!optional && this.match(types$1.bracketR)) { + node.elementType = type; + this.next(); + type = this.finishNode(node, "ArrayTypeAnnotation"); + } else { + node.objectType = type; + node.indexType = this.flowParseType(); + this.expect(types$1.bracketR); + + if (seenOptionalIndexedAccess) { + node.optional = optional; + type = this.finishNode(node, "OptionalIndexedAccessType"); + } else { + type = this.finishNode(node, "IndexedAccessType"); + } + } + } + + return type; + } + + flowParsePrefixType() { + const node = this.startNode(); + + if (this.eat(types$1.question)) { + node.typeAnnotation = this.flowParsePrefixType(); + return this.finishNode(node, "NullableTypeAnnotation"); + } else { + return this.flowParsePostfixType(); + } + } + + flowParseAnonFunctionWithoutParens() { + const param = this.flowParsePrefixType(); + + if (!this.state.noAnonFunctionType && this.eat(types$1.arrow)) { + const node = this.startNodeAt(param.start, param.loc.start); + node.params = [this.reinterpretTypeAsFunctionTypeParam(param)]; + node.rest = null; + node.this = null; + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + } + + return param; + } + + flowParseIntersectionType() { + const node = this.startNode(); + this.eat(types$1.bitwiseAND); + const type = this.flowParseAnonFunctionWithoutParens(); + node.types = [type]; + + while (this.eat(types$1.bitwiseAND)) { + node.types.push(this.flowParseAnonFunctionWithoutParens()); + } + + return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); + } + + flowParseUnionType() { + const node = this.startNode(); + this.eat(types$1.bitwiseOR); + const type = this.flowParseIntersectionType(); + node.types = [type]; + + while (this.eat(types$1.bitwiseOR)) { + node.types.push(this.flowParseIntersectionType()); + } + + return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); + } + + flowParseType() { + const oldInType = this.state.inType; + this.state.inType = true; + const type = this.flowParseUnionType(); + this.state.inType = oldInType; + return type; + } + + flowParseTypeOrImplicitInstantiation() { + if (this.state.type === types$1.name && this.state.value === "_") { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + const node = this.parseIdentifier(); + return this.flowParseGenericType(startPos, startLoc, node); + } else { + return this.flowParseType(); + } + } + + flowParseTypeAnnotation() { + const node = this.startNode(); + node.typeAnnotation = this.flowParseTypeInitialiser(); + return this.finishNode(node, "TypeAnnotation"); + } + + flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) { + const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier(); + + if (this.match(types$1.colon)) { + ident.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(ident); + } + + return ident; + } + + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end); + return node.expression; + } + + flowParseVariance() { + let variance = null; + + if (this.match(types$1.plusMin)) { + variance = this.startNode(); + + if (this.state.value === "+") { + variance.kind = "plus"; + } else { + variance.kind = "minus"; + } + + this.next(); + this.finishNode(variance, "Variance"); + } + + return variance; + } + + parseFunctionBody(node, allowExpressionBody, isMethod = false) { + if (allowExpressionBody) { + return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod)); + } + + return super.parseFunctionBody(node, false, isMethod); + } + + parseFunctionBodyAndFinish(node, type, isMethod = false) { + if (this.match(types$1.colon)) { + const typeNode = this.startNode(); + [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; + } + + super.parseFunctionBodyAndFinish(node, type, isMethod); + } + + parseStatement(context, topLevel) { + if (this.state.strict && this.match(types$1.name) && this.state.value === "interface") { + const lookahead = this.lookahead(); + + if (lookahead.type === types$1.name || isKeyword(lookahead.value)) { + const node = this.startNode(); + this.next(); + return this.flowParseInterface(node); + } + } else if (this.shouldParseEnums() && this.isContextual("enum")) { + const node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } + + const stmt = super.parseStatement(context, topLevel); + + if (this.flowPragma === undefined && !this.isValidDirective(stmt)) { + this.flowPragma = null; + } + + return stmt; + } + + parseExpressionStatement(node, expr) { + if (expr.type === "Identifier") { + if (expr.name === "declare") { + if (this.match(types$1._class) || this.match(types$1.name) || this.match(types$1._function) || this.match(types$1._var) || this.match(types$1._export)) { + return this.flowParseDeclare(node); + } + } else if (this.match(types$1.name)) { + if (expr.name === "interface") { + return this.flowParseInterface(node); + } else if (expr.name === "type") { + return this.flowParseTypeAlias(node); + } else if (expr.name === "opaque") { + return this.flowParseOpaqueType(node, false); + } + } + } + + return super.parseExpressionStatement(node, expr); + } + + shouldParseExportDeclaration() { + return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration(); + } + + isExportDefaultSpecifier() { + if (this.match(types$1.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) { + return false; + } + + return super.isExportDefaultSpecifier(); + } + + parseExportDefaultExpression() { + if (this.shouldParseEnums() && this.isContextual("enum")) { + const node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } + + return super.parseExportDefaultExpression(); + } + + parseConditional(expr, startPos, startLoc, refExpressionErrors) { + if (!this.match(types$1.question)) return expr; + + if (this.state.maybeInArrowParameters) { + const nextCh = this.lookaheadCharCode(); + + if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) { + this.setOptionalParametersError(refExpressionErrors); + return expr; + } + } + + this.expect(types$1.question); + const state = this.state.clone(); + const originalNoArrowAt = this.state.noArrowAt; + const node = this.startNodeAt(startPos, startLoc); + let { + consequent, + failed + } = this.tryParseConditionalConsequent(); + let [valid, invalid] = this.getArrowLikeExpressions(consequent); + + if (failed || invalid.length > 0) { + const noArrowAt = [...originalNoArrowAt]; + + if (invalid.length > 0) { + this.state = state; + this.state.noArrowAt = noArrowAt; + + for (let i = 0; i < invalid.length; i++) { + noArrowAt.push(invalid[i].start); + } + + ({ + consequent, + failed + } = this.tryParseConditionalConsequent()); + [valid, invalid] = this.getArrowLikeExpressions(consequent); + } + + if (failed && valid.length > 1) { + this.raise(state.start, FlowErrors.AmbiguousConditionalArrow); + } + + if (failed && valid.length === 1) { + this.state = state; + noArrowAt.push(valid[0].start); + this.state.noArrowAt = noArrowAt; + ({ + consequent, + failed + } = this.tryParseConditionalConsequent()); + } + } + + this.getArrowLikeExpressions(consequent, true); + this.state.noArrowAt = originalNoArrowAt; + this.expect(types$1.colon); + node.test = expr; + node.consequent = consequent; + node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined)); + return this.finishNode(node, "ConditionalExpression"); + } + + tryParseConditionalConsequent() { + this.state.noArrowParamsConversionAt.push(this.state.start); + const consequent = this.parseMaybeAssignAllowIn(); + const failed = !this.match(types$1.colon); + this.state.noArrowParamsConversionAt.pop(); + return { + consequent, + failed + }; + } + + getArrowLikeExpressions(node, disallowInvalid) { + const stack = [node]; + const arrows = []; + + while (stack.length !== 0) { + const node = stack.pop(); + + if (node.type === "ArrowFunctionExpression") { + if (node.typeParameters || !node.returnType) { + this.finishArrowValidation(node); + } else { + arrows.push(node); + } + + stack.push(node.body); + } else if (node.type === "ConditionalExpression") { + stack.push(node.consequent); + stack.push(node.alternate); + } + } + + if (disallowInvalid) { + arrows.forEach(node => this.finishArrowValidation(node)); + return [arrows, []]; + } + + return partition(arrows, node => node.params.every(param => this.isAssignable(param, true))); + } + + finishArrowValidation(node) { + var _node$extra; + + this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false); + this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW); + super.checkParams(node, false, true); + this.scope.exit(); + } + + forwardNoArrowParamsConversionAt(node, parse) { + let result; + + if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { + this.state.noArrowParamsConversionAt.push(this.state.start); + result = parse(); + this.state.noArrowParamsConversionAt.pop(); + } else { + result = parse(); + } + + return result; + } + + parseParenItem(node, startPos, startLoc) { + node = super.parseParenItem(node, startPos, startLoc); + + if (this.eat(types$1.question)) { + node.optional = true; + this.resetEndLocation(node); + } + + if (this.match(types$1.colon)) { + const typeCastNode = this.startNodeAt(startPos, startLoc); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TypeCastExpression"); + } + + return node; + } + + assertModuleNodeAllowed(node) { + if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") { + return; + } + + super.assertModuleNodeAllowed(node); + } + + parseExport(node) { + const decl = super.parseExport(node); + + if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") { + decl.exportKind = decl.exportKind || "value"; + } + + return decl; + } + + parseExportDeclaration(node) { + if (this.isContextual("type")) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + + if (this.match(types$1.braceL)) { + node.specifiers = this.parseExportSpecifiers(); + this.parseExportFrom(node); + return null; + } else { + return this.flowParseTypeAlias(declarationNode); + } + } else if (this.isContextual("opaque")) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseOpaqueType(declarationNode, false); + } else if (this.isContextual("interface")) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseInterface(declarationNode); + } else if (this.shouldParseEnums() && this.isContextual("enum")) { + node.exportKind = "value"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(declarationNode); + } else { + return super.parseExportDeclaration(node); + } + } + + eatExportStar(node) { + if (super.eatExportStar(...arguments)) return true; + + if (this.isContextual("type") && this.lookahead().type === types$1.star) { + node.exportKind = "type"; + this.next(); + this.next(); + return true; + } + + return false; + } + + maybeParseExportNamespaceSpecifier(node) { + const pos = this.state.start; + const hasNamespace = super.maybeParseExportNamespaceSpecifier(node); + + if (hasNamespace && node.exportKind === "type") { + this.unexpected(pos); + } + + return hasNamespace; + } + + parseClassId(node, isStatement, optionalId) { + super.parseClassId(node, isStatement, optionalId); + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + } + + parseClassMember(classBody, member, state) { + const pos = this.state.start; + + if (this.isContextual("declare")) { + if (this.parseClassMemberFromModifier(classBody, member)) { + return; + } + + member.declare = true; + } + + super.parseClassMember(classBody, member, state); + + if (member.declare) { + if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") { + this.raise(pos, FlowErrors.DeclareClassElement); + } else if (member.value) { + this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer); + } + } + } + + isIterator(word) { + return word === "iterator" || word === "asyncIterator"; + } + + readIterator() { + const word = super.readWord1(); + const fullWord = "@@" + word; + + if (!this.isIterator(word) || !this.state.inType) { + this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, fullWord); + } + + this.finishToken(types$1.name, fullWord); + } + + getTokenFromCode(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + + if (code === 123 && next === 124) { + return this.finishOp(types$1.braceBarL, 2); + } else if (this.state.inType && (code === 62 || code === 60)) { + return this.finishOp(types$1.relational, 1); + } else if (this.state.inType && code === 63) { + if (next === 46) { + return this.finishOp(types$1.questionDot, 2); + } + + return this.finishOp(types$1.question, 1); + } else if (isIteratorStart(code, next)) { + this.state.pos += 2; + return this.readIterator(); + } else { + return super.getTokenFromCode(code); + } + } + + isAssignable(node, isBinding) { + if (node.type === "TypeCastExpression") { + return this.isAssignable(node.expression, isBinding); + } else { + return super.isAssignable(node, isBinding); + } + } + + toAssignable(node, isLHS = false) { + if (node.type === "TypeCastExpression") { + return super.toAssignable(this.typeCastToParameter(node), isLHS); + } else { + return super.toAssignable(node, isLHS); + } + } + + toAssignableList(exprList, trailingCommaPos, isLHS) { + for (let i = 0; i < exprList.length; i++) { + const expr = exprList[i]; + + if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") { + exprList[i] = this.typeCastToParameter(expr); + } + } + + return super.toAssignableList(exprList, trailingCommaPos, isLHS); + } + + toReferencedList(exprList, isParenthesizedExpr) { + for (let i = 0; i < exprList.length; i++) { + var _expr$extra; + + const expr = exprList[i]; + + if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { + this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern); + } + } + + return exprList; + } + + parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { + const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors); + + if (canBePattern && !this.state.maybeInArrowParameters) { + this.toReferencedList(node.elements); + } + + return node; + } + + checkLVal(expr, ...args) { + if (expr.type !== "TypeCastExpression") { + return super.checkLVal(expr, ...args); + } + } + + parseClassProperty(node) { + if (this.match(types$1.colon)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + + return super.parseClassProperty(node); + } + + parseClassPrivateProperty(node) { + if (this.match(types$1.colon)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + + return super.parseClassPrivateProperty(node); + } + + isClassMethod() { + return this.isRelational("<") || super.isClassMethod(); + } + + isClassProperty() { + return this.match(types$1.colon) || super.isClassProperty(); + } + + isNonstaticConstructor(method) { + return !this.match(types$1.colon) && super.isNonstaticConstructor(method); + } + + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + if (method.variance) { + this.unexpected(method.variance.start); + } + + delete method.variance; + + if (this.isRelational("<")) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + + super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + + if (method.params && isConstructor) { + const params = method.params; + + if (params.length > 0 && this.isThisParam(params[0])) { + this.raise(method.start, FlowErrors.ThisParamBannedInConstructor); + } + } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) { + const params = method.value.params; + + if (params.length > 0 && this.isThisParam(params[0])) { + this.raise(method.start, FlowErrors.ThisParamBannedInConstructor); + } + } + } + + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + if (method.variance) { + this.unexpected(method.variance.start); + } + + delete method.variance; + + if (this.isRelational("<")) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + + super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); + } + + parseClassSuper(node) { + super.parseClassSuper(node); + + if (node.superClass && this.isRelational("<")) { + node.superTypeParameters = this.flowParseTypeParameterInstantiation(); + } + + if (this.isContextual("implements")) { + this.next(); + const implemented = node.implements = []; + + do { + const node = this.startNode(); + node.id = this.flowParseRestrictedIdentifier(true); + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + + implemented.push(this.finishNode(node, "ClassImplements")); + } while (this.eat(types$1.comma)); + } + } + + checkGetterSetterParams(method) { + super.checkGetterSetterParams(method); + const params = this.getObjectOrClassMethodParams(method); + + if (params.length > 0) { + const param = params[0]; + + if (this.isThisParam(param) && method.kind === "get") { + this.raise(param.start, FlowErrors.GetterMayNotHaveThisParam); + } else if (this.isThisParam(param)) { + this.raise(param.start, FlowErrors.SetterMayNotHaveThisParam); + } + } + } + + parsePropertyName(node, isPrivateNameAllowed) { + const variance = this.flowParseVariance(); + const key = super.parsePropertyName(node, isPrivateNameAllowed); + node.variance = variance; + return key; + } + + parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + if (prop.variance) { + this.unexpected(prop.variance.start); + } + + delete prop.variance; + let typeParameters; + + if (this.isRelational("<") && !isAccessor) { + typeParameters = this.flowParseTypeParameterDeclaration(); + if (!this.match(types$1.parenL)) this.unexpected(); + } + + super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); + + if (typeParameters) { + (prop.value || prop).typeParameters = typeParameters; + } + } + + parseAssignableListItemTypes(param) { + if (this.eat(types$1.question)) { + if (param.type !== "Identifier") { + this.raise(param.start, FlowErrors.PatternIsOptional); + } + + if (this.isThisParam(param)) { + this.raise(param.start, FlowErrors.ThisParamMayNotBeOptional); + } + + param.optional = true; + } + + if (this.match(types$1.colon)) { + param.typeAnnotation = this.flowParseTypeAnnotation(); + } else if (this.isThisParam(param)) { + this.raise(param.start, FlowErrors.ThisParamAnnotationRequired); + } + + if (this.match(types$1.eq) && this.isThisParam(param)) { + this.raise(param.start, FlowErrors.ThisParamNoDefault); + } + + this.resetEndLocation(param); + return param; + } + + parseMaybeDefault(startPos, startLoc, left) { + const node = super.parseMaybeDefault(startPos, startLoc, left); + + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer); + } + + return node; + } + + shouldParseDefaultImport(node) { + if (!hasTypeImportKind(node)) { + return super.shouldParseDefaultImport(node); + } + + return isMaybeDefaultImport(this.state); + } + + parseImportSpecifierLocal(node, specifier, type, contextDescription) { + specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier(); + this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL); + node.specifiers.push(this.finishNode(specifier, type)); + } + + maybeParseDefaultImportSpecifier(node) { + node.importKind = "value"; + let kind = null; + + if (this.match(types$1._typeof)) { + kind = "typeof"; + } else if (this.isContextual("type")) { + kind = "type"; + } + + if (kind) { + const lh = this.lookahead(); + + if (kind === "type" && lh.type === types$1.star) { + this.unexpected(lh.start); + } + + if (isMaybeDefaultImport(lh) || lh.type === types$1.braceL || lh.type === types$1.star) { + this.next(); + node.importKind = kind; + } + } + + return super.maybeParseDefaultImportSpecifier(node); + } + + parseImportSpecifier(node) { + const specifier = this.startNode(); + const firstIdentIsString = this.match(types$1.string); + const firstIdent = this.parseModuleExportName(); + let specifierTypeKind = null; + + if (firstIdent.type === "Identifier") { + if (firstIdent.name === "type") { + specifierTypeKind = "type"; + } else if (firstIdent.name === "typeof") { + specifierTypeKind = "typeof"; + } + } + + let isBinding = false; + + if (this.isContextual("as") && !this.isLookaheadContextual("as")) { + const as_ident = this.parseIdentifier(true); + + if (specifierTypeKind !== null && !this.match(types$1.name) && !this.state.type.keyword) { + specifier.imported = as_ident; + specifier.importKind = specifierTypeKind; + specifier.local = cloneIdentifier(as_ident); + } else { + specifier.imported = firstIdent; + specifier.importKind = null; + specifier.local = this.parseIdentifier(); + } + } else { + if (specifierTypeKind !== null && (this.match(types$1.name) || this.state.type.keyword)) { + specifier.imported = this.parseIdentifier(true); + specifier.importKind = specifierTypeKind; + } else { + if (firstIdentIsString) { + throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value); + } + + specifier.imported = firstIdent; + specifier.importKind = null; + } + + if (this.eatContextual("as")) { + specifier.local = this.parseIdentifier(); + } else { + isBinding = true; + specifier.local = cloneIdentifier(specifier.imported); + } + } + + const nodeIsTypeImport = hasTypeImportKind(node); + const specifierIsTypeImport = hasTypeImportKind(specifier); + + if (nodeIsTypeImport && specifierIsTypeImport) { + this.raise(specifier.start, FlowErrors.ImportTypeShorthandOnlyInPureImport); + } + + if (nodeIsTypeImport || specifierIsTypeImport) { + this.checkReservedType(specifier.local.name, specifier.local.start, true); + } + + if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) { + this.checkReservedWord(specifier.local.name, specifier.start, true, true); + } + + this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL); + node.specifiers.push(this.finishNode(specifier, "ImportSpecifier")); + } + + parseBindingAtom() { + switch (this.state.type) { + case types$1._this: + return this.parseIdentifier(true); + + default: + return super.parseBindingAtom(); + } + } + + parseFunctionParams(node, allowModifiers) { + const kind = node.kind; + + if (kind !== "get" && kind !== "set" && this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + + super.parseFunctionParams(node, allowModifiers); + } + + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + + if (this.match(types$1.colon)) { + decl.id.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(decl.id); + } + } + + parseAsyncArrowFromCallExpression(node, call) { + if (this.match(types$1.colon)) { + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + node.returnType = this.flowParseTypeAnnotation(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + } + + return super.parseAsyncArrowFromCallExpression(node, call); + } + + shouldParseAsyncArrow() { + return this.match(types$1.colon) || super.shouldParseAsyncArrow(); + } + + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + var _jsx; + + let state = null; + let jsx; + + if (this.hasPlugin("jsx") && (this.match(types$1.jsxTagStart) || this.isRelational("<"))) { + state = this.state.clone(); + jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!jsx.error) return jsx.node; + const { + context + } = this.state; + const curContext = context[context.length - 1]; + + if (curContext === types.j_oTag) { + context.length -= 2; + } else if (curContext === types.j_expr) { + context.length -= 1; + } + } + + if ((_jsx = jsx) != null && _jsx.error || this.isRelational("<")) { + var _jsx2, _jsx3; + + state = state || this.state.clone(); + let typeParameters; + const arrow = this.tryParse(abort => { + var _arrowExpression$extr; + + typeParameters = this.flowParseTypeParameterDeclaration(); + const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => { + const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + this.resetStartLocationFromNode(result, typeParameters); + return result; + }); + if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort(); + const expr = this.maybeUnwrapTypeCastExpression(arrowExpression); + if (expr.type !== "ArrowFunctionExpression") abort(); + expr.typeParameters = typeParameters; + this.resetStartLocationFromNode(expr, typeParameters); + return arrowExpression; + }, state); + let arrowExpression = null; + + if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") { + if (!arrow.error && !arrow.aborted) { + if (arrow.node.async) { + this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction); + } + + return arrow.node; + } + + arrowExpression = arrow.node; + } + + if ((_jsx2 = jsx) != null && _jsx2.node) { + this.state = jsx.failState; + return jsx.node; + } + + if (arrowExpression) { + this.state = arrow.failState; + return arrowExpression; + } + + if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error; + if (arrow.thrown) throw arrow.error; + throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter); + } + + return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + } + + parseArrow(node) { + if (this.match(types$1.colon)) { + const result = this.tryParse(() => { + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + const typeNode = this.startNode(); + [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + if (this.canInsertSemicolon()) this.unexpected(); + if (!this.match(types$1.arrow)) this.unexpected(); + return typeNode; + }); + if (result.thrown) return null; + if (result.error) this.state = result.failState; + node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null; + } + + return super.parseArrow(node); + } + + shouldParseArrow(params) { + return this.match(types$1.colon) || super.shouldParseArrow(params); + } + + setArrowFunctionParameters(node, params) { + if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { + node.params = params; + } else { + super.setArrowFunctionParameters(node, params); + } + } + + checkParams(node, allowDuplicates, isArrowFunction) { + if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { + return; + } + + for (let i = 0; i < node.params.length; i++) { + if (this.isThisParam(node.params[i]) && i > 0) { + this.raise(node.params[i].start, FlowErrors.ThisParamMustBeFirst); + } + } + + return super.checkParams(...arguments); + } + + parseParenAndDistinguishExpression(canBeArrow) { + return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1); + } + + parseSubscripts(base, startPos, startLoc, noCalls) { + if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) { + this.next(); + const node = this.startNodeAt(startPos, startLoc); + node.callee = base; + node.arguments = this.parseCallExpressionArguments(types$1.parenR, false); + base = this.finishNode(node, "CallExpression"); + } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) { + const state = this.state.clone(); + const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state); + if (!arrow.error && !arrow.aborted) return arrow.node; + const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state); + if (result.node && !result.error) return result.node; + + if (arrow.node) { + this.state = arrow.failState; + return arrow.node; + } + + if (result.node) { + this.state = result.failState; + return result.node; + } + + throw arrow.error || result.error; + } + + return super.parseSubscripts(base, startPos, startLoc, noCalls); + } + + parseSubscript(base, startPos, startLoc, noCalls, subscriptState) { + if (this.match(types$1.questionDot) && this.isLookaheadToken_lt()) { + subscriptState.optionalChainMember = true; + + if (noCalls) { + subscriptState.stop = true; + return base; + } + + this.next(); + const node = this.startNodeAt(startPos, startLoc); + node.callee = base; + node.typeArguments = this.flowParseTypeParameterInstantiation(); + this.expect(types$1.parenL); + node.arguments = this.parseCallExpressionArguments(types$1.parenR, false); + node.optional = true; + return this.finishCallExpression(node, true); + } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) { + const node = this.startNodeAt(startPos, startLoc); + node.callee = base; + const result = this.tryParse(() => { + node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew(); + this.expect(types$1.parenL); + node.arguments = this.parseCallExpressionArguments(types$1.parenR, false); + if (subscriptState.optionalChainMember) node.optional = false; + return this.finishCallExpression(node, subscriptState.optionalChainMember); + }); + + if (result.node) { + if (result.error) this.state = result.failState; + return result.node; + } + } + + return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState); + } + + parseNewArguments(node) { + let targs = null; + + if (this.shouldParseTypes() && this.isRelational("<")) { + targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node; + } + + node.typeArguments = targs; + super.parseNewArguments(node); + } + + parseAsyncArrowWithTypeParameters(startPos, startLoc) { + const node = this.startNodeAt(startPos, startLoc); + this.parseFunctionParams(node); + if (!this.parseArrow(node)) return; + return this.parseArrowExpression(node, undefined, true); + } + + readToken_mult_modulo(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + + if (code === 42 && next === 47 && this.state.hasFlowComment) { + this.state.hasFlowComment = false; + this.state.pos += 2; + this.nextToken(); + return; + } + + super.readToken_mult_modulo(code); + } + + readToken_pipe_amp(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + + if (code === 124 && next === 125) { + this.finishOp(types$1.braceBarR, 2); + return; + } + + super.readToken_pipe_amp(code); + } + + parseTopLevel(file, program) { + const fileNode = super.parseTopLevel(file, program); + + if (this.state.hasFlowComment) { + this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment); + } + + return fileNode; + } + + skipBlockComment() { + if (this.hasPlugin("flowComments") && this.skipFlowComment()) { + if (this.state.hasFlowComment) { + this.unexpected(null, FlowErrors.NestedFlowComment); + } + + this.hasFlowCommentCompletion(); + this.state.pos += this.skipFlowComment(); + this.state.hasFlowComment = true; + return; + } + + if (this.state.hasFlowComment) { + const end = this.input.indexOf("*-/", this.state.pos += 2); + + if (end === -1) { + throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment); + } + + this.state.pos = end + 3; + return; + } + + return super.skipBlockComment(); + } + + skipFlowComment() { + const { + pos + } = this.state; + let shiftToFirstNonWhiteSpace = 2; + + while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) { + shiftToFirstNonWhiteSpace++; + } + + const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos); + const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1); + + if (ch2 === 58 && ch3 === 58) { + return shiftToFirstNonWhiteSpace + 2; + } + + if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") { + return shiftToFirstNonWhiteSpace + 12; + } + + if (ch2 === 58 && ch3 !== 58) { + return shiftToFirstNonWhiteSpace; + } + + return false; + } + + hasFlowCommentCompletion() { + const end = this.input.indexOf("*/", this.state.pos); + + if (end === -1) { + throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment); + } + } + + flowEnumErrorBooleanMemberNotInitialized(pos, { + enumName, + memberName + }) { + this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName); + } + + flowEnumErrorInvalidMemberName(pos, { + enumName, + memberName + }) { + const suggestion = memberName[0].toUpperCase() + memberName.slice(1); + this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName); + } + + flowEnumErrorDuplicateMemberName(pos, { + enumName, + memberName + }) { + this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName); + } + + flowEnumErrorInconsistentMemberValues(pos, { + enumName + }) { + this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName); + } + + flowEnumErrorInvalidExplicitType(pos, { + enumName, + suppliedType + }) { + return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType); + } + + flowEnumErrorInvalidMemberInitializer(pos, { + enumName, + explicitType, + memberName + }) { + let message = null; + + switch (explicitType) { + case "boolean": + case "number": + case "string": + message = FlowErrors.EnumInvalidMemberInitializerPrimaryType; + break; + + case "symbol": + message = FlowErrors.EnumInvalidMemberInitializerSymbolType; + break; + + default: + message = FlowErrors.EnumInvalidMemberInitializerUnknownType; + } + + return this.raise(pos, message, enumName, memberName, explicitType); + } + + flowEnumErrorNumberMemberNotInitialized(pos, { + enumName, + memberName + }) { + this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName); + } + + flowEnumErrorStringMemberInconsistentlyInitailized(pos, { + enumName + }) { + this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName); + } + + flowEnumMemberInit() { + const startPos = this.state.start; + + const endOfInit = () => this.match(types$1.comma) || this.match(types$1.braceR); + + switch (this.state.type) { + case types$1.num: + { + const literal = this.parseNumericLiteral(this.state.value); + + if (endOfInit()) { + return { + type: "number", + pos: literal.start, + value: literal + }; + } + + return { + type: "invalid", + pos: startPos + }; + } + + case types$1.string: + { + const literal = this.parseStringLiteral(this.state.value); + + if (endOfInit()) { + return { + type: "string", + pos: literal.start, + value: literal + }; + } + + return { + type: "invalid", + pos: startPos + }; + } + + case types$1._true: + case types$1._false: + { + const literal = this.parseBooleanLiteral(this.match(types$1._true)); + + if (endOfInit()) { + return { + type: "boolean", + pos: literal.start, + value: literal + }; + } + + return { + type: "invalid", + pos: startPos + }; + } + + default: + return { + type: "invalid", + pos: startPos + }; + } + } + + flowEnumMemberRaw() { + const pos = this.state.start; + const id = this.parseIdentifier(true); + const init = this.eat(types$1.eq) ? this.flowEnumMemberInit() : { + type: "none", + pos + }; + return { + id, + init + }; + } + + flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) { + const { + explicitType + } = context; + + if (explicitType === null) { + return; + } + + if (explicitType !== expectedType) { + this.flowEnumErrorInvalidMemberInitializer(pos, context); + } + } + + flowEnumMembers({ + enumName, + explicitType + }) { + const seenNames = new Set(); + const members = { + booleanMembers: [], + numberMembers: [], + stringMembers: [], + defaultedMembers: [] + }; + let hasUnknownMembers = false; + + while (!this.match(types$1.braceR)) { + if (this.eat(types$1.ellipsis)) { + hasUnknownMembers = true; + break; + } + + const memberNode = this.startNode(); + const { + id, + init + } = this.flowEnumMemberRaw(); + const memberName = id.name; + + if (memberName === "") { + continue; + } + + if (/^[a-z]/.test(memberName)) { + this.flowEnumErrorInvalidMemberName(id.start, { + enumName, + memberName + }); + } + + if (seenNames.has(memberName)) { + this.flowEnumErrorDuplicateMemberName(id.start, { + enumName, + memberName + }); + } + + seenNames.add(memberName); + const context = { + enumName, + explicitType, + memberName + }; + memberNode.id = id; + + switch (init.type) { + case "boolean": + { + this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean"); + memberNode.init = init.value; + members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember")); + break; + } + + case "number": + { + this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number"); + memberNode.init = init.value; + members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember")); + break; + } + + case "string": + { + this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string"); + memberNode.init = init.value; + members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember")); + break; + } + + case "invalid": + { + throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context); + } + + case "none": + { + switch (explicitType) { + case "boolean": + this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context); + break; + + case "number": + this.flowEnumErrorNumberMemberNotInitialized(init.pos, context); + break; + + default: + members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember")); + } + } + } + + if (!this.match(types$1.braceR)) { + this.expect(types$1.comma); + } + } + + return { + members, + hasUnknownMembers + }; + } + + flowEnumStringMembers(initializedMembers, defaultedMembers, { + enumName + }) { + if (initializedMembers.length === 0) { + return defaultedMembers; + } else if (defaultedMembers.length === 0) { + return initializedMembers; + } else if (defaultedMembers.length > initializedMembers.length) { + for (const member of initializedMembers) { + this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, { + enumName + }); + } + + return defaultedMembers; + } else { + for (const member of defaultedMembers) { + this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, { + enumName + }); + } + + return initializedMembers; + } + } + + flowEnumParseExplicitType({ + enumName + }) { + if (this.eatContextual("of")) { + if (!this.match(types$1.name)) { + throw this.flowEnumErrorInvalidExplicitType(this.state.start, { + enumName, + suppliedType: null + }); + } + + const { + value + } = this.state; + this.next(); + + if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") { + this.flowEnumErrorInvalidExplicitType(this.state.start, { + enumName, + suppliedType: value + }); + } + + return value; + } + + return null; + } + + flowEnumBody(node, { + enumName, + nameLoc + }) { + const explicitType = this.flowEnumParseExplicitType({ + enumName + }); + this.expect(types$1.braceL); + const { + members, + hasUnknownMembers + } = this.flowEnumMembers({ + enumName, + explicitType + }); + node.hasUnknownMembers = hasUnknownMembers; + + switch (explicitType) { + case "boolean": + node.explicitType = true; + node.members = members.booleanMembers; + this.expect(types$1.braceR); + return this.finishNode(node, "EnumBooleanBody"); + + case "number": + node.explicitType = true; + node.members = members.numberMembers; + this.expect(types$1.braceR); + return this.finishNode(node, "EnumNumberBody"); + + case "string": + node.explicitType = true; + node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { + enumName + }); + this.expect(types$1.braceR); + return this.finishNode(node, "EnumStringBody"); + + case "symbol": + node.members = members.defaultedMembers; + this.expect(types$1.braceR); + return this.finishNode(node, "EnumSymbolBody"); + + default: + { + const empty = () => { + node.members = []; + this.expect(types$1.braceR); + return this.finishNode(node, "EnumStringBody"); + }; + + node.explicitType = false; + const boolsLen = members.booleanMembers.length; + const numsLen = members.numberMembers.length; + const strsLen = members.stringMembers.length; + const defaultedLen = members.defaultedMembers.length; + + if (!boolsLen && !numsLen && !strsLen && !defaultedLen) { + return empty(); + } else if (!boolsLen && !numsLen) { + node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { + enumName + }); + this.expect(types$1.braceR); + return this.finishNode(node, "EnumStringBody"); + } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) { + for (const member of members.defaultedMembers) { + this.flowEnumErrorBooleanMemberNotInitialized(member.start, { + enumName, + memberName: member.id.name + }); + } + + node.members = members.booleanMembers; + this.expect(types$1.braceR); + return this.finishNode(node, "EnumBooleanBody"); + } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) { + for (const member of members.defaultedMembers) { + this.flowEnumErrorNumberMemberNotInitialized(member.start, { + enumName, + memberName: member.id.name + }); + } + + node.members = members.numberMembers; + this.expect(types$1.braceR); + return this.finishNode(node, "EnumNumberBody"); + } else { + this.flowEnumErrorInconsistentMemberValues(nameLoc, { + enumName + }); + return empty(); + } + } + } + } + + flowParseEnumDeclaration(node) { + const id = this.parseIdentifier(); + node.id = id; + node.body = this.flowEnumBody(this.startNode(), { + enumName: id.name, + nameLoc: id.start + }); + return this.finishNode(node, "EnumDeclaration"); + } + + isLookaheadToken_lt() { + const next = this.nextTokenStart(); + + if (this.input.charCodeAt(next) === 60) { + const afterNext = this.input.charCodeAt(next + 1); + return afterNext !== 60 && afterNext !== 61; + } + + return false; + } + + maybeUnwrapTypeCastExpression(node) { + return node.type === "TypeCastExpression" ? node.expression : node; + } + +}); + +const entities = { + quot: "\u0022", + amp: "&", + apos: "\u0027", + lt: "<", + gt: ">", + nbsp: "\u00A0", + iexcl: "\u00A1", + cent: "\u00A2", + pound: "\u00A3", + curren: "\u00A4", + yen: "\u00A5", + brvbar: "\u00A6", + sect: "\u00A7", + uml: "\u00A8", + copy: "\u00A9", + ordf: "\u00AA", + laquo: "\u00AB", + not: "\u00AC", + shy: "\u00AD", + reg: "\u00AE", + macr: "\u00AF", + deg: "\u00B0", + plusmn: "\u00B1", + sup2: "\u00B2", + sup3: "\u00B3", + acute: "\u00B4", + micro: "\u00B5", + para: "\u00B6", + middot: "\u00B7", + cedil: "\u00B8", + sup1: "\u00B9", + ordm: "\u00BA", + raquo: "\u00BB", + frac14: "\u00BC", + frac12: "\u00BD", + frac34: "\u00BE", + iquest: "\u00BF", + Agrave: "\u00C0", + Aacute: "\u00C1", + Acirc: "\u00C2", + Atilde: "\u00C3", + Auml: "\u00C4", + Aring: "\u00C5", + AElig: "\u00C6", + Ccedil: "\u00C7", + Egrave: "\u00C8", + Eacute: "\u00C9", + Ecirc: "\u00CA", + Euml: "\u00CB", + Igrave: "\u00CC", + Iacute: "\u00CD", + Icirc: "\u00CE", + Iuml: "\u00CF", + ETH: "\u00D0", + Ntilde: "\u00D1", + Ograve: "\u00D2", + Oacute: "\u00D3", + Ocirc: "\u00D4", + Otilde: "\u00D5", + Ouml: "\u00D6", + times: "\u00D7", + Oslash: "\u00D8", + Ugrave: "\u00D9", + Uacute: "\u00DA", + Ucirc: "\u00DB", + Uuml: "\u00DC", + Yacute: "\u00DD", + THORN: "\u00DE", + szlig: "\u00DF", + agrave: "\u00E0", + aacute: "\u00E1", + acirc: "\u00E2", + atilde: "\u00E3", + auml: "\u00E4", + aring: "\u00E5", + aelig: "\u00E6", + ccedil: "\u00E7", + egrave: "\u00E8", + eacute: "\u00E9", + ecirc: "\u00EA", + euml: "\u00EB", + igrave: "\u00EC", + iacute: "\u00ED", + icirc: "\u00EE", + iuml: "\u00EF", + eth: "\u00F0", + ntilde: "\u00F1", + ograve: "\u00F2", + oacute: "\u00F3", + ocirc: "\u00F4", + otilde: "\u00F5", + ouml: "\u00F6", + divide: "\u00F7", + oslash: "\u00F8", + ugrave: "\u00F9", + uacute: "\u00FA", + ucirc: "\u00FB", + uuml: "\u00FC", + yacute: "\u00FD", + thorn: "\u00FE", + yuml: "\u00FF", + OElig: "\u0152", + oelig: "\u0153", + Scaron: "\u0160", + scaron: "\u0161", + Yuml: "\u0178", + fnof: "\u0192", + circ: "\u02C6", + tilde: "\u02DC", + Alpha: "\u0391", + Beta: "\u0392", + Gamma: "\u0393", + Delta: "\u0394", + Epsilon: "\u0395", + Zeta: "\u0396", + Eta: "\u0397", + Theta: "\u0398", + Iota: "\u0399", + Kappa: "\u039A", + Lambda: "\u039B", + Mu: "\u039C", + Nu: "\u039D", + Xi: "\u039E", + Omicron: "\u039F", + Pi: "\u03A0", + Rho: "\u03A1", + Sigma: "\u03A3", + Tau: "\u03A4", + Upsilon: "\u03A5", + Phi: "\u03A6", + Chi: "\u03A7", + Psi: "\u03A8", + Omega: "\u03A9", + alpha: "\u03B1", + beta: "\u03B2", + gamma: "\u03B3", + delta: "\u03B4", + epsilon: "\u03B5", + zeta: "\u03B6", + eta: "\u03B7", + theta: "\u03B8", + iota: "\u03B9", + kappa: "\u03BA", + lambda: "\u03BB", + mu: "\u03BC", + nu: "\u03BD", + xi: "\u03BE", + omicron: "\u03BF", + pi: "\u03C0", + rho: "\u03C1", + sigmaf: "\u03C2", + sigma: "\u03C3", + tau: "\u03C4", + upsilon: "\u03C5", + phi: "\u03C6", + chi: "\u03C7", + psi: "\u03C8", + omega: "\u03C9", + thetasym: "\u03D1", + upsih: "\u03D2", + piv: "\u03D6", + ensp: "\u2002", + emsp: "\u2003", + thinsp: "\u2009", + zwnj: "\u200C", + zwj: "\u200D", + lrm: "\u200E", + rlm: "\u200F", + ndash: "\u2013", + mdash: "\u2014", + lsquo: "\u2018", + rsquo: "\u2019", + sbquo: "\u201A", + ldquo: "\u201C", + rdquo: "\u201D", + bdquo: "\u201E", + dagger: "\u2020", + Dagger: "\u2021", + bull: "\u2022", + hellip: "\u2026", + permil: "\u2030", + prime: "\u2032", + Prime: "\u2033", + lsaquo: "\u2039", + rsaquo: "\u203A", + oline: "\u203E", + frasl: "\u2044", + euro: "\u20AC", + image: "\u2111", + weierp: "\u2118", + real: "\u211C", + trade: "\u2122", + alefsym: "\u2135", + larr: "\u2190", + uarr: "\u2191", + rarr: "\u2192", + darr: "\u2193", + harr: "\u2194", + crarr: "\u21B5", + lArr: "\u21D0", + uArr: "\u21D1", + rArr: "\u21D2", + dArr: "\u21D3", + hArr: "\u21D4", + forall: "\u2200", + part: "\u2202", + exist: "\u2203", + empty: "\u2205", + nabla: "\u2207", + isin: "\u2208", + notin: "\u2209", + ni: "\u220B", + prod: "\u220F", + sum: "\u2211", + minus: "\u2212", + lowast: "\u2217", + radic: "\u221A", + prop: "\u221D", + infin: "\u221E", + ang: "\u2220", + and: "\u2227", + or: "\u2228", + cap: "\u2229", + cup: "\u222A", + int: "\u222B", + there4: "\u2234", + sim: "\u223C", + cong: "\u2245", + asymp: "\u2248", + ne: "\u2260", + equiv: "\u2261", + le: "\u2264", + ge: "\u2265", + sub: "\u2282", + sup: "\u2283", + nsub: "\u2284", + sube: "\u2286", + supe: "\u2287", + oplus: "\u2295", + otimes: "\u2297", + perp: "\u22A5", + sdot: "\u22C5", + lceil: "\u2308", + rceil: "\u2309", + lfloor: "\u230A", + rfloor: "\u230B", + lang: "\u2329", + rang: "\u232A", + loz: "\u25CA", + spades: "\u2660", + clubs: "\u2663", + hearts: "\u2665", + diams: "\u2666" +}; + +const HEX_NUMBER = /^[\da-fA-F]+$/; +const DECIMAL_NUMBER = /^\d+$/; +const JsxErrors = makeErrorTemplates({ + AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.", + MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>.", + MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.", + UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?", + UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.", + UnterminatedJsxContent: "Unterminated JSX contents.", + UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?" +}, ErrorCodes.SyntaxError, "jsx"); +types.j_oTag = new TokContext("...", true); +types$1.jsxName = new TokenType("jsxName"); +types$1.jsxText = new TokenType("jsxText", { + beforeExpr: true +}); +types$1.jsxTagStart = new TokenType("jsxTagStart", { + startsExpr: true +}); +types$1.jsxTagEnd = new TokenType("jsxTagEnd"); + +types$1.jsxTagStart.updateContext = context => { + context.push(types.j_expr, types.j_oTag); +}; + +function isFragment(object) { + return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false; +} + +function getQualifiedJSXName(object) { + if (object.type === "JSXIdentifier") { + return object.name; + } + + if (object.type === "JSXNamespacedName") { + return object.namespace.name + ":" + object.name.name; + } + + if (object.type === "JSXMemberExpression") { + return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property); + } + + throw new Error("Node had unexpected type: " + object.type); +} + +var jsx = (superClass => class extends superClass { + jsxReadToken() { + let out = ""; + let chunkStart = this.state.pos; + + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent); + } + + const ch = this.input.charCodeAt(this.state.pos); + + switch (ch) { + case 60: + case 123: + if (this.state.pos === this.state.start) { + if (ch === 60 && this.state.exprAllowed) { + ++this.state.pos; + return this.finishToken(types$1.jsxTagStart); + } + + return super.getTokenFromCode(ch); + } + + out += this.input.slice(chunkStart, this.state.pos); + return this.finishToken(types$1.jsxText, out); + + case 38: + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + break; + + case 62: + case 125: + + default: + if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(true); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + + } + } + } + + jsxReadNewLine(normalizeCRLF) { + const ch = this.input.charCodeAt(this.state.pos); + let out; + ++this.state.pos; + + if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + out = normalizeCRLF ? "\n" : "\r\n"; + } else { + out = String.fromCharCode(ch); + } + + ++this.state.curLine; + this.state.lineStart = this.state.pos; + return out; + } + + jsxReadString(quote) { + let out = ""; + let chunkStart = ++this.state.pos; + + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(this.state.start, ErrorMessages.UnterminatedString); + } + + const ch = this.input.charCodeAt(this.state.pos); + if (ch === quote) break; + + if (ch === 38) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(false); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + + out += this.input.slice(chunkStart, this.state.pos++); + return this.finishToken(types$1.string, out); + } + + jsxReadEntity() { + let str = ""; + let count = 0; + let entity; + let ch = this.input[this.state.pos]; + const startPos = ++this.state.pos; + + while (this.state.pos < this.length && count++ < 10) { + ch = this.input[this.state.pos++]; + + if (ch === ";") { + if (str[0] === "#") { + if (str[1] === "x") { + str = str.substr(2); + + if (HEX_NUMBER.test(str)) { + entity = String.fromCodePoint(parseInt(str, 16)); + } + } else { + str = str.substr(1); + + if (DECIMAL_NUMBER.test(str)) { + entity = String.fromCodePoint(parseInt(str, 10)); + } + } + } else { + entity = entities[str]; + } + + break; + } + + str += ch; + } + + if (!entity) { + this.state.pos = startPos; + return "&"; + } + + return entity; + } + + jsxReadWord() { + let ch; + const start = this.state.pos; + + do { + ch = this.input.charCodeAt(++this.state.pos); + } while (isIdentifierChar(ch) || ch === 45); + + return this.finishToken(types$1.jsxName, this.input.slice(start, this.state.pos)); + } + + jsxParseIdentifier() { + const node = this.startNode(); + + if (this.match(types$1.jsxName)) { + node.name = this.state.value; + } else if (this.state.type.keyword) { + node.name = this.state.type.keyword; + } else { + this.unexpected(); + } + + this.next(); + return this.finishNode(node, "JSXIdentifier"); + } + + jsxParseNamespacedName() { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + const name = this.jsxParseIdentifier(); + if (!this.eat(types$1.colon)) return name; + const node = this.startNodeAt(startPos, startLoc); + node.namespace = name; + node.name = this.jsxParseIdentifier(); + return this.finishNode(node, "JSXNamespacedName"); + } + + jsxParseElementName() { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + let node = this.jsxParseNamespacedName(); + + if (node.type === "JSXNamespacedName") { + return node; + } + + while (this.eat(types$1.dot)) { + const newNode = this.startNodeAt(startPos, startLoc); + newNode.object = node; + newNode.property = this.jsxParseIdentifier(); + node = this.finishNode(newNode, "JSXMemberExpression"); + } + + return node; + } + + jsxParseAttributeValue() { + let node; + + switch (this.state.type) { + case types$1.braceL: + node = this.startNode(); + this.next(); + node = this.jsxParseExpressionContainer(node); + + if (node.expression.type === "JSXEmptyExpression") { + this.raise(node.start, JsxErrors.AttributeIsEmpty); + } + + return node; + + case types$1.jsxTagStart: + case types$1.string: + return this.parseExprAtom(); + + default: + throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue); + } + } + + jsxParseEmptyExpression() { + const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc); + return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc); + } + + jsxParseSpreadChild(node) { + this.next(); + node.expression = this.parseExpression(); + this.expect(types$1.braceR); + return this.finishNode(node, "JSXSpreadChild"); + } + + jsxParseExpressionContainer(node) { + if (this.match(types$1.braceR)) { + node.expression = this.jsxParseEmptyExpression(); + } else { + const expression = this.parseExpression(); + node.expression = expression; + } + + this.expect(types$1.braceR); + return this.finishNode(node, "JSXExpressionContainer"); + } + + jsxParseAttribute() { + const node = this.startNode(); + + if (this.eat(types$1.braceL)) { + this.expect(types$1.ellipsis); + node.argument = this.parseMaybeAssignAllowIn(); + this.expect(types$1.braceR); + return this.finishNode(node, "JSXSpreadAttribute"); + } + + node.name = this.jsxParseNamespacedName(); + node.value = this.eat(types$1.eq) ? this.jsxParseAttributeValue() : null; + return this.finishNode(node, "JSXAttribute"); + } + + jsxParseOpeningElementAt(startPos, startLoc) { + const node = this.startNodeAt(startPos, startLoc); + + if (this.match(types$1.jsxTagEnd)) { + this.expect(types$1.jsxTagEnd); + return this.finishNode(node, "JSXOpeningFragment"); + } + + node.name = this.jsxParseElementName(); + return this.jsxParseOpeningElementAfterName(node); + } + + jsxParseOpeningElementAfterName(node) { + const attributes = []; + + while (!this.match(types$1.slash) && !this.match(types$1.jsxTagEnd)) { + attributes.push(this.jsxParseAttribute()); + } + + node.attributes = attributes; + node.selfClosing = this.eat(types$1.slash); + this.expect(types$1.jsxTagEnd); + return this.finishNode(node, "JSXOpeningElement"); + } + + jsxParseClosingElementAt(startPos, startLoc) { + const node = this.startNodeAt(startPos, startLoc); + + if (this.match(types$1.jsxTagEnd)) { + this.expect(types$1.jsxTagEnd); + return this.finishNode(node, "JSXClosingFragment"); + } + + node.name = this.jsxParseElementName(); + this.expect(types$1.jsxTagEnd); + return this.finishNode(node, "JSXClosingElement"); + } + + jsxParseElementAt(startPos, startLoc) { + const node = this.startNodeAt(startPos, startLoc); + const children = []; + const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc); + let closingElement = null; + + if (!openingElement.selfClosing) { + contents: for (;;) { + switch (this.state.type) { + case types$1.jsxTagStart: + startPos = this.state.start; + startLoc = this.state.startLoc; + this.next(); + + if (this.eat(types$1.slash)) { + closingElement = this.jsxParseClosingElementAt(startPos, startLoc); + break contents; + } + + children.push(this.jsxParseElementAt(startPos, startLoc)); + break; + + case types$1.jsxText: + children.push(this.parseExprAtom()); + break; + + case types$1.braceL: + { + const node = this.startNode(); + this.next(); + + if (this.match(types$1.ellipsis)) { + children.push(this.jsxParseSpreadChild(node)); + } else { + children.push(this.jsxParseExpressionContainer(node)); + } + + break; + } + + default: + throw this.unexpected(); + } + } + + if (isFragment(openingElement) && !isFragment(closingElement)) { + this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment); + } else if (!isFragment(openingElement) && isFragment(closingElement)) { + this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name)); + } else if (!isFragment(openingElement) && !isFragment(closingElement)) { + if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { + this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name)); + } + } + } + + if (isFragment(openingElement)) { + node.openingFragment = openingElement; + node.closingFragment = closingElement; + } else { + node.openingElement = openingElement; + node.closingElement = closingElement; + } + + node.children = children; + + if (this.isRelational("<")) { + throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements); + } + + return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement"); + } + + jsxParseElement() { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + this.next(); + return this.jsxParseElementAt(startPos, startLoc); + } + + parseExprAtom(refExpressionErrors) { + if (this.match(types$1.jsxText)) { + return this.parseLiteral(this.state.value, "JSXText"); + } else if (this.match(types$1.jsxTagStart)) { + return this.jsxParseElement(); + } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) { + this.finishToken(types$1.jsxTagStart); + return this.jsxParseElement(); + } else { + return super.parseExprAtom(refExpressionErrors); + } + } + + createLookaheadState(state) { + const lookaheadState = super.createLookaheadState(state); + lookaheadState.inPropertyName = state.inPropertyName; + return lookaheadState; + } + + getTokenFromCode(code) { + if (this.state.inPropertyName) return super.getTokenFromCode(code); + const context = this.curContext(); + + if (context === types.j_expr) { + return this.jsxReadToken(); + } + + if (context === types.j_oTag || context === types.j_cTag) { + if (isIdentifierStart(code)) { + return this.jsxReadWord(); + } + + if (code === 62) { + ++this.state.pos; + return this.finishToken(types$1.jsxTagEnd); + } + + if ((code === 34 || code === 39) && context === types.j_oTag) { + return this.jsxReadString(code); + } + } + + if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) { + ++this.state.pos; + return this.finishToken(types$1.jsxTagStart); + } + + return super.getTokenFromCode(code); + } + + updateContext(prevType) { + super.updateContext(prevType); + const { + context, + type + } = this.state; + + if (type === types$1.slash && prevType === types$1.jsxTagStart) { + context.splice(-2, 2, types.j_cTag); + this.state.exprAllowed = false; + } else if (type === types$1.jsxTagEnd) { + const out = context.pop(); + + if (out === types.j_oTag && prevType === types$1.slash || out === types.j_cTag) { + context.pop(); + this.state.exprAllowed = context[context.length - 1] === types.j_expr; + } else { + this.state.exprAllowed = true; + } + } else if (type.keyword && (prevType === types$1.dot || prevType === types$1.questionDot)) { + this.state.exprAllowed = false; + } else { + this.state.exprAllowed = type.beforeExpr; + } + } + +}); + +class TypeScriptScope extends Scope { + constructor(...args) { + super(...args); + this.types = new Set(); + this.enums = new Set(); + this.constEnums = new Set(); + this.classes = new Set(); + this.exportOnlyBindings = new Set(); + } + +} + +class TypeScriptScopeHandler extends ScopeHandler { + createScope(flags) { + return new TypeScriptScope(flags); + } + + declareName(name, bindingType, pos) { + const scope = this.currentScope(); + + if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) { + this.maybeExportDefined(scope, name); + scope.exportOnlyBindings.add(name); + return; + } + + super.declareName(...arguments); + + if (bindingType & BIND_KIND_TYPE) { + if (!(bindingType & BIND_KIND_VALUE)) { + this.checkRedeclarationInScope(scope, name, bindingType, pos); + this.maybeExportDefined(scope, name); + } + + scope.types.add(name); + } + + if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.add(name); + if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.add(name); + if (bindingType & BIND_FLAGS_CLASS) scope.classes.add(name); + } + + isRedeclaredInScope(scope, name, bindingType) { + if (scope.enums.has(name)) { + if (bindingType & BIND_FLAGS_TS_ENUM) { + const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM); + const wasConst = scope.constEnums.has(name); + return isConst !== wasConst; + } + + return true; + } + + if (bindingType & BIND_FLAGS_CLASS && scope.classes.has(name)) { + if (scope.lexical.has(name)) { + return !!(bindingType & BIND_KIND_VALUE); + } else { + return false; + } + } + + if (bindingType & BIND_KIND_TYPE && scope.types.has(name)) { + return true; + } + + return super.isRedeclaredInScope(...arguments); + } + + checkLocalExport(id) { + const topLevelScope = this.scopeStack[0]; + const { + name + } = id; + + if (!topLevelScope.types.has(name) && !topLevelScope.exportOnlyBindings.has(name)) { + super.checkLocalExport(id); + } + } + +} + +function nonNull(x) { + if (x == null) { + throw new Error(`Unexpected ${x} value.`); + } + + return x; +} + +function assert(x) { + if (!x) { + throw new Error("Assert fail"); + } +} + +const TSErrors = makeErrorTemplates({ + AbstractMethodHasImplementation: "Method '%0' cannot have an implementation because it is marked abstract.", + AbstractPropertyHasInitializer: "Property '%0' cannot have an initializer because it is marked abstract.", + AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.", + AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.", + ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.", + ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.", + ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.", + DeclareAccessor: "'declare' is not allowed in %0ters.", + DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.", + DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.", + DuplicateAccessibilityModifier: "Accessibility modifier already seen.", + DuplicateModifier: "Duplicate modifier: '%0'.", + EmptyHeritageClauseType: "'%0' list cannot be empty.", + EmptyTypeArguments: "Type argument list cannot be empty.", + EmptyTypeParameters: "Type parameter list cannot be empty.", + ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.", + ImportAliasHasImportType: "An import alias can not use 'import type'.", + IncompatibleModifiers: "'%0' modifier cannot be used with '%1' modifier.", + IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.", + IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0').", + IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.", + IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.", + IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.", + InvalidModifierOnTypeMember: "'%0' modifier cannot appear on a type member.", + InvalidModifiersOrder: "'%0' modifier must precede '%1' modifier.", + InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.", + MissingInterfaceName: "'interface' declarations must be followed by an identifier.", + MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.", + NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.", + NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.", + OptionalTypeBeforeRequired: "A required element cannot follow an optional element.", + OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.", + PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.", + PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.", + PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0').", + ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.", + SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.", + SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.", + SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.", + StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.", + TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.", + UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.", + UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.", + UnexpectedTypeAnnotation: "Did not expect a type annotation here.", + UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.", + UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.", + UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.", + UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0." +}, ErrorCodes.SyntaxError, "typescript"); + +function keywordTypeFromName(value) { + switch (value) { + case "any": + return "TSAnyKeyword"; + + case "boolean": + return "TSBooleanKeyword"; + + case "bigint": + return "TSBigIntKeyword"; + + case "never": + return "TSNeverKeyword"; + + case "number": + return "TSNumberKeyword"; + + case "object": + return "TSObjectKeyword"; + + case "string": + return "TSStringKeyword"; + + case "symbol": + return "TSSymbolKeyword"; + + case "undefined": + return "TSUndefinedKeyword"; + + case "unknown": + return "TSUnknownKeyword"; + + default: + return undefined; + } +} + +function tsIsAccessModifier(modifier) { + return modifier === "private" || modifier === "public" || modifier === "protected"; +} + +var typescript = (superClass => class extends superClass { + getScopeHandler() { + return TypeScriptScopeHandler; + } + + tsIsIdentifier() { + return this.match(types$1.name); + } + + tsTokenCanFollowModifier() { + return (this.match(types$1.bracketL) || this.match(types$1.braceL) || this.match(types$1.star) || this.match(types$1.ellipsis) || this.match(types$1.privateName) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak(); + } + + tsNextTokenCanFollowModifier() { + this.next(); + return this.tsTokenCanFollowModifier(); + } + + tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) { + if (!this.match(types$1.name)) { + return undefined; + } + + const modifier = this.state.value; + + if (allowedModifiers.indexOf(modifier) !== -1) { + if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) { + return undefined; + } + + if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { + return modifier; + } + } + + return undefined; + } + + tsParseModifiers(modified, allowedModifiers, disallowedModifiers, errorTemplate, stopOnStartOfClassStaticBlock) { + const enforceOrder = (pos, modifier, before, after) => { + if (modifier === before && modified[after]) { + this.raise(pos, TSErrors.InvalidModifiersOrder, before, after); + } + }; + + const incompatible = (pos, modifier, mod1, mod2) => { + if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) { + this.raise(pos, TSErrors.IncompatibleModifiers, mod1, mod2); + } + }; + + for (;;) { + const startPos = this.state.start; + const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock); + if (!modifier) break; + + if (tsIsAccessModifier(modifier)) { + if (modified.accessibility) { + this.raise(startPos, TSErrors.DuplicateAccessibilityModifier); + } else { + enforceOrder(startPos, modifier, modifier, "override"); + enforceOrder(startPos, modifier, modifier, "static"); + enforceOrder(startPos, modifier, modifier, "readonly"); + modified.accessibility = modifier; + } + } else { + if (Object.hasOwnProperty.call(modified, modifier)) { + this.raise(startPos, TSErrors.DuplicateModifier, modifier); + } else { + enforceOrder(startPos, modifier, "static", "readonly"); + enforceOrder(startPos, modifier, "static", "override"); + enforceOrder(startPos, modifier, "override", "readonly"); + enforceOrder(startPos, modifier, "abstract", "override"); + incompatible(startPos, modifier, "declare", "override"); + incompatible(startPos, modifier, "static", "abstract"); + } + + modified[modifier] = true; + } + + if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) { + this.raise(startPos, errorTemplate, modifier); + } + } + } + + tsIsListTerminator(kind) { + switch (kind) { + case "EnumMembers": + case "TypeMembers": + return this.match(types$1.braceR); + + case "HeritageClauseElement": + return this.match(types$1.braceL); + + case "TupleElementTypes": + return this.match(types$1.bracketR); + + case "TypeParametersOrArguments": + return this.isRelational(">"); + } + + throw new Error("Unreachable"); + } + + tsParseList(kind, parseElement) { + const result = []; + + while (!this.tsIsListTerminator(kind)) { + result.push(parseElement()); + } + + return result; + } + + tsParseDelimitedList(kind, parseElement) { + return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true)); + } + + tsParseDelimitedListWorker(kind, parseElement, expectSuccess) { + const result = []; + + for (;;) { + if (this.tsIsListTerminator(kind)) { + break; + } + + const element = parseElement(); + + if (element == null) { + return undefined; + } + + result.push(element); + + if (this.eat(types$1.comma)) { + continue; + } + + if (this.tsIsListTerminator(kind)) { + break; + } + + if (expectSuccess) { + this.expect(types$1.comma); + } + + return undefined; + } + + return result; + } + + tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) { + if (!skipFirstToken) { + if (bracket) { + this.expect(types$1.bracketL); + } else { + this.expectRelational("<"); + } + } + + const result = this.tsParseDelimitedList(kind, parseElement); + + if (bracket) { + this.expect(types$1.bracketR); + } else { + this.expectRelational(">"); + } + + return result; + } + + tsParseImportType() { + const node = this.startNode(); + this.expect(types$1._import); + this.expect(types$1.parenL); + + if (!this.match(types$1.string)) { + this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument); + } + + node.argument = this.parseExprAtom(); + this.expect(types$1.parenR); + + if (this.eat(types$1.dot)) { + node.qualifier = this.tsParseEntityName(true); + } + + if (this.isRelational("<")) { + node.typeParameters = this.tsParseTypeArguments(); + } + + return this.finishNode(node, "TSImportType"); + } + + tsParseEntityName(allowReservedWords) { + let entity = this.parseIdentifier(); + + while (this.eat(types$1.dot)) { + const node = this.startNodeAtNode(entity); + node.left = entity; + node.right = this.parseIdentifier(allowReservedWords); + entity = this.finishNode(node, "TSQualifiedName"); + } + + return entity; + } + + tsParseTypeReference() { + const node = this.startNode(); + node.typeName = this.tsParseEntityName(false); + + if (!this.hasPrecedingLineBreak() && this.isRelational("<")) { + node.typeParameters = this.tsParseTypeArguments(); + } + + return this.finishNode(node, "TSTypeReference"); + } + + tsParseThisTypePredicate(lhs) { + this.next(); + const node = this.startNodeAtNode(lhs); + node.parameterName = lhs; + node.typeAnnotation = this.tsParseTypeAnnotation(false); + node.asserts = false; + return this.finishNode(node, "TSTypePredicate"); + } + + tsParseThisTypeNode() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSThisType"); + } + + tsParseTypeQuery() { + const node = this.startNode(); + this.expect(types$1._typeof); + + if (this.match(types$1._import)) { + node.exprName = this.tsParseImportType(); + } else { + node.exprName = this.tsParseEntityName(true); + } + + return this.finishNode(node, "TSTypeQuery"); + } + + tsParseTypeParameter() { + const node = this.startNode(); + node.name = this.tsParseTypeParameterName(); + node.constraint = this.tsEatThenParseType(types$1._extends); + node.default = this.tsEatThenParseType(types$1.eq); + return this.finishNode(node, "TSTypeParameter"); + } + + tsTryParseTypeParameters() { + if (this.isRelational("<")) { + return this.tsParseTypeParameters(); + } + } + + tsParseTypeParameters() { + const node = this.startNode(); + + if (this.isRelational("<") || this.match(types$1.jsxTagStart)) { + this.next(); + } else { + this.unexpected(); + } + + node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true); + + if (node.params.length === 0) { + this.raise(node.start, TSErrors.EmptyTypeParameters); + } + + return this.finishNode(node, "TSTypeParameterDeclaration"); + } + + tsTryNextParseConstantContext() { + if (this.lookahead().type === types$1._const) { + this.next(); + return this.tsParseTypeReference(); + } + + return null; + } + + tsFillSignature(returnToken, signature) { + const returnTokenRequired = returnToken === types$1.arrow; + signature.typeParameters = this.tsTryParseTypeParameters(); + this.expect(types$1.parenL); + signature.parameters = this.tsParseBindingListForSignature(); + + if (returnTokenRequired) { + signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } else if (this.match(returnToken)) { + signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } + } + + tsParseBindingListForSignature() { + return this.parseBindingList(types$1.parenR, 41).map(pattern => { + if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") { + this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type); + } + + return pattern; + }); + } + + tsParseTypeMemberSemicolon() { + if (!this.eat(types$1.comma) && !this.isLineTerminator()) { + this.expect(types$1.semi); + } + } + + tsParseSignatureMember(kind, node) { + this.tsFillSignature(types$1.colon, node); + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, kind); + } + + tsIsUnambiguouslyIndexSignature() { + this.next(); + return this.eat(types$1.name) && this.match(types$1.colon); + } + + tsTryParseIndexSignature(node) { + if (!(this.match(types$1.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) { + return undefined; + } + + this.expect(types$1.bracketL); + const id = this.parseIdentifier(); + id.typeAnnotation = this.tsParseTypeAnnotation(); + this.resetEndLocation(id); + this.expect(types$1.bracketR); + node.parameters = [id]; + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, "TSIndexSignature"); + } + + tsParsePropertyOrMethodSignature(node, readonly) { + if (this.eat(types$1.question)) node.optional = true; + const nodeAny = node; + + if (this.match(types$1.parenL) || this.isRelational("<")) { + if (readonly) { + this.raise(node.start, TSErrors.ReadonlyForMethodSignature); + } + + const method = nodeAny; + + if (method.kind && this.isRelational("<")) { + this.raise(this.state.pos, TSErrors.AccesorCannotHaveTypeParameters); + } + + this.tsFillSignature(types$1.colon, method); + this.tsParseTypeMemberSemicolon(); + + if (method.kind === "get") { + if (method.parameters.length > 0) { + this.raise(this.state.pos, ErrorMessages.BadGetterArity); + + if (this.isThisParam(method.parameters[0])) { + this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter); + } + } + } else if (method.kind === "set") { + if (method.parameters.length !== 1) { + this.raise(this.state.pos, ErrorMessages.BadSetterArity); + } else { + const firstParameter = method.parameters[0]; + + if (this.isThisParam(firstParameter)) { + this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter); + } + + if (firstParameter.type === "Identifier" && firstParameter.optional) { + this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveOptionalParameter); + } + + if (firstParameter.type === "RestElement") { + this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveRestParameter); + } + } + + if (method.typeAnnotation) { + this.raise(method.typeAnnotation.start, TSErrors.SetAccesorCannotHaveReturnType); + } + } else { + method.kind = "method"; + } + + return this.finishNode(method, "TSMethodSignature"); + } else { + const property = nodeAny; + if (readonly) property.readonly = true; + const type = this.tsTryParseTypeAnnotation(); + if (type) property.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(property, "TSPropertySignature"); + } + } + + tsParseTypeMember() { + const node = this.startNode(); + + if (this.match(types$1.parenL) || this.isRelational("<")) { + return this.tsParseSignatureMember("TSCallSignatureDeclaration", node); + } + + if (this.match(types$1._new)) { + const id = this.startNode(); + this.next(); + + if (this.match(types$1.parenL) || this.isRelational("<")) { + return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node); + } else { + node.key = this.createIdentifier(id, "new"); + return this.tsParsePropertyOrMethodSignature(node, false); + } + } + + this.tsParseModifiers(node, ["readonly"], ["declare", "abstract", "private", "protected", "public", "static", "override"], TSErrors.InvalidModifierOnTypeMember); + const idx = this.tsTryParseIndexSignature(node); + + if (idx) { + return idx; + } + + this.parsePropertyName(node, false); + + if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) { + node.kind = node.key.name; + this.parsePropertyName(node, false); + } + + return this.tsParsePropertyOrMethodSignature(node, !!node.readonly); + } + + tsParseTypeLiteral() { + const node = this.startNode(); + node.members = this.tsParseObjectTypeMembers(); + return this.finishNode(node, "TSTypeLiteral"); + } + + tsParseObjectTypeMembers() { + this.expect(types$1.braceL); + const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); + this.expect(types$1.braceR); + return members; + } + + tsIsStartOfMappedType() { + this.next(); + + if (this.eat(types$1.plusMin)) { + return this.isContextual("readonly"); + } + + if (this.isContextual("readonly")) { + this.next(); + } + + if (!this.match(types$1.bracketL)) { + return false; + } + + this.next(); + + if (!this.tsIsIdentifier()) { + return false; + } + + this.next(); + return this.match(types$1._in); + } + + tsParseMappedTypeParameter() { + const node = this.startNode(); + node.name = this.tsParseTypeParameterName(); + node.constraint = this.tsExpectThenParseType(types$1._in); + return this.finishNode(node, "TSTypeParameter"); + } + + tsParseMappedType() { + const node = this.startNode(); + this.expect(types$1.braceL); + + if (this.match(types$1.plusMin)) { + node.readonly = this.state.value; + this.next(); + this.expectContextual("readonly"); + } else if (this.eatContextual("readonly")) { + node.readonly = true; + } + + this.expect(types$1.bracketL); + node.typeParameter = this.tsParseMappedTypeParameter(); + node.nameType = this.eatContextual("as") ? this.tsParseType() : null; + this.expect(types$1.bracketR); + + if (this.match(types$1.plusMin)) { + node.optional = this.state.value; + this.next(); + this.expect(types$1.question); + } else if (this.eat(types$1.question)) { + node.optional = true; + } + + node.typeAnnotation = this.tsTryParseType(); + this.semicolon(); + this.expect(types$1.braceR); + return this.finishNode(node, "TSMappedType"); + } + + tsParseTupleType() { + const node = this.startNode(); + node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false); + let seenOptionalElement = false; + let labeledElements = null; + node.elementTypes.forEach(elementNode => { + var _labeledElements; + + let { + type + } = elementNode; + + if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) { + this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired); + } + + seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType"; + + if (type === "TSRestType") { + elementNode = elementNode.typeAnnotation; + type = elementNode.type; + } + + const isLabeled = type === "TSNamedTupleMember"; + labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled; + + if (labeledElements !== isLabeled) { + this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements); + } + }); + return this.finishNode(node, "TSTupleType"); + } + + tsParseTupleElementType() { + const { + start: startPos, + startLoc + } = this.state; + const rest = this.eat(types$1.ellipsis); + let type = this.tsParseType(); + const optional = this.eat(types$1.question); + const labeled = this.eat(types$1.colon); + + if (labeled) { + const labeledNode = this.startNodeAtNode(type); + labeledNode.optional = optional; + + if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") { + labeledNode.label = type.typeName; + } else { + this.raise(type.start, TSErrors.InvalidTupleMemberLabel); + labeledNode.label = type; + } + + labeledNode.elementType = this.tsParseType(); + type = this.finishNode(labeledNode, "TSNamedTupleMember"); + } else if (optional) { + const optionalTypeNode = this.startNodeAtNode(type); + optionalTypeNode.typeAnnotation = type; + type = this.finishNode(optionalTypeNode, "TSOptionalType"); + } + + if (rest) { + const restNode = this.startNodeAt(startPos, startLoc); + restNode.typeAnnotation = type; + type = this.finishNode(restNode, "TSRestType"); + } + + return type; + } + + tsParseParenthesizedType() { + const node = this.startNode(); + this.expect(types$1.parenL); + node.typeAnnotation = this.tsParseType(); + this.expect(types$1.parenR); + return this.finishNode(node, "TSParenthesizedType"); + } + + tsParseFunctionOrConstructorType(type, abstract) { + const node = this.startNode(); + + if (type === "TSConstructorType") { + node.abstract = !!abstract; + if (abstract) this.next(); + this.next(); + } + + this.tsFillSignature(types$1.arrow, node); + return this.finishNode(node, type); + } + + tsParseLiteralTypeNode() { + const node = this.startNode(); + + node.literal = (() => { + switch (this.state.type) { + case types$1.num: + case types$1.bigint: + case types$1.string: + case types$1._true: + case types$1._false: + return this.parseExprAtom(); + + default: + throw this.unexpected(); + } + })(); + + return this.finishNode(node, "TSLiteralType"); + } + + tsParseTemplateLiteralType() { + const node = this.startNode(); + node.literal = this.parseTemplate(false); + return this.finishNode(node, "TSLiteralType"); + } + + parseTemplateSubstitution() { + if (this.state.inType) return this.tsParseType(); + return super.parseTemplateSubstitution(); + } + + tsParseThisTypeOrThisTypePredicate() { + const thisKeyword = this.tsParseThisTypeNode(); + + if (this.isContextual("is") && !this.hasPrecedingLineBreak()) { + return this.tsParseThisTypePredicate(thisKeyword); + } else { + return thisKeyword; + } + } + + tsParseNonArrayType() { + switch (this.state.type) { + case types$1.name: + case types$1._void: + case types$1._null: + { + const type = this.match(types$1._void) ? "TSVoidKeyword" : this.match(types$1._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value); + + if (type !== undefined && this.lookaheadCharCode() !== 46) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, type); + } + + return this.tsParseTypeReference(); + } + + case types$1.string: + case types$1.num: + case types$1.bigint: + case types$1._true: + case types$1._false: + return this.tsParseLiteralTypeNode(); + + case types$1.plusMin: + if (this.state.value === "-") { + const node = this.startNode(); + const nextToken = this.lookahead(); + + if (nextToken.type !== types$1.num && nextToken.type !== types$1.bigint) { + throw this.unexpected(); + } + + node.literal = this.parseMaybeUnary(); + return this.finishNode(node, "TSLiteralType"); + } + + break; + + case types$1._this: + return this.tsParseThisTypeOrThisTypePredicate(); + + case types$1._typeof: + return this.tsParseTypeQuery(); + + case types$1._import: + return this.tsParseImportType(); + + case types$1.braceL: + return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral(); + + case types$1.bracketL: + return this.tsParseTupleType(); + + case types$1.parenL: + return this.tsParseParenthesizedType(); + + case types$1.backQuote: + return this.tsParseTemplateLiteralType(); + } + + throw this.unexpected(); + } + + tsParseArrayTypeOrHigher() { + let type = this.tsParseNonArrayType(); + + while (!this.hasPrecedingLineBreak() && this.eat(types$1.bracketL)) { + if (this.match(types$1.bracketR)) { + const node = this.startNodeAtNode(type); + node.elementType = type; + this.expect(types$1.bracketR); + type = this.finishNode(node, "TSArrayType"); + } else { + const node = this.startNodeAtNode(type); + node.objectType = type; + node.indexType = this.tsParseType(); + this.expect(types$1.bracketR); + type = this.finishNode(node, "TSIndexedAccessType"); + } + } + + return type; + } + + tsParseTypeOperator(operator) { + const node = this.startNode(); + this.expectContextual(operator); + node.operator = operator; + node.typeAnnotation = this.tsParseTypeOperatorOrHigher(); + + if (operator === "readonly") { + this.tsCheckTypeAnnotationForReadOnly(node); + } + + return this.finishNode(node, "TSTypeOperator"); + } + + tsCheckTypeAnnotationForReadOnly(node) { + switch (node.typeAnnotation.type) { + case "TSTupleType": + case "TSArrayType": + return; + + default: + this.raise(node.start, TSErrors.UnexpectedReadonly); + } + } + + tsParseInferType() { + const node = this.startNode(); + this.expectContextual("infer"); + const typeParameter = this.startNode(); + typeParameter.name = this.tsParseTypeParameterName(); + node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); + return this.finishNode(node, "TSInferType"); + } + + tsParseTypeOperatorOrHigher() { + const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw)); + return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher(); + } + + tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) { + const node = this.startNode(); + const hasLeadingOperator = this.eat(operator); + const types = []; + + do { + types.push(parseConstituentType()); + } while (this.eat(operator)); + + if (types.length === 1 && !hasLeadingOperator) { + return types[0]; + } + + node.types = types; + return this.finishNode(node, kind); + } + + tsParseIntersectionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types$1.bitwiseAND); + } + + tsParseUnionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types$1.bitwiseOR); + } + + tsIsStartOfFunctionType() { + if (this.isRelational("<")) { + return true; + } + + return this.match(types$1.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this)); + } + + tsSkipParameterStart() { + if (this.match(types$1.name) || this.match(types$1._this)) { + this.next(); + return true; + } + + if (this.match(types$1.braceL)) { + let braceStackCounter = 1; + this.next(); + + while (braceStackCounter > 0) { + if (this.match(types$1.braceL)) { + ++braceStackCounter; + } else if (this.match(types$1.braceR)) { + --braceStackCounter; + } + + this.next(); + } + + return true; + } + + if (this.match(types$1.bracketL)) { + let braceStackCounter = 1; + this.next(); + + while (braceStackCounter > 0) { + if (this.match(types$1.bracketL)) { + ++braceStackCounter; + } else if (this.match(types$1.bracketR)) { + --braceStackCounter; + } + + this.next(); + } + + return true; + } + + return false; + } + + tsIsUnambiguouslyStartOfFunctionType() { + this.next(); + + if (this.match(types$1.parenR) || this.match(types$1.ellipsis)) { + return true; + } + + if (this.tsSkipParameterStart()) { + if (this.match(types$1.colon) || this.match(types$1.comma) || this.match(types$1.question) || this.match(types$1.eq)) { + return true; + } + + if (this.match(types$1.parenR)) { + this.next(); + + if (this.match(types$1.arrow)) { + return true; + } + } + } + + return false; + } + + tsParseTypeOrTypePredicateAnnotation(returnToken) { + return this.tsInType(() => { + const t = this.startNode(); + this.expect(returnToken); + const node = this.startNode(); + const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this)); + + if (asserts && this.match(types$1._this)) { + let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate(); + + if (thisTypePredicate.type === "TSThisType") { + node.parameterName = thisTypePredicate; + node.asserts = true; + node.typeAnnotation = null; + thisTypePredicate = this.finishNode(node, "TSTypePredicate"); + } else { + this.resetStartLocationFromNode(thisTypePredicate, node); + thisTypePredicate.asserts = true; + } + + t.typeAnnotation = thisTypePredicate; + return this.finishNode(t, "TSTypeAnnotation"); + } + + const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); + + if (!typePredicateVariable) { + if (!asserts) { + return this.tsParseTypeAnnotation(false, t); + } + + node.parameterName = this.parseIdentifier(); + node.asserts = asserts; + node.typeAnnotation = null; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + } + + const type = this.tsParseTypeAnnotation(false); + node.parameterName = typePredicateVariable; + node.typeAnnotation = type; + node.asserts = asserts; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + }); + } + + tsTryParseTypeOrTypePredicateAnnotation() { + return this.match(types$1.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types$1.colon) : undefined; + } + + tsTryParseTypeAnnotation() { + return this.match(types$1.colon) ? this.tsParseTypeAnnotation() : undefined; + } + + tsTryParseType() { + return this.tsEatThenParseType(types$1.colon); + } + + tsParseTypePredicatePrefix() { + const id = this.parseIdentifier(); + + if (this.isContextual("is") && !this.hasPrecedingLineBreak()) { + this.next(); + return id; + } + } + + tsParseTypePredicateAsserts() { + if (!this.match(types$1.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) { + return false; + } + + const containsEsc = this.state.containsEsc; + this.next(); + + if (!this.match(types$1.name) && !this.match(types$1._this)) { + return false; + } + + if (containsEsc) { + this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts"); + } + + return true; + } + + tsParseTypeAnnotation(eatColon = true, t = this.startNode()) { + this.tsInType(() => { + if (eatColon) this.expect(types$1.colon); + t.typeAnnotation = this.tsParseType(); + }); + return this.finishNode(t, "TSTypeAnnotation"); + } + + tsParseType() { + assert(this.state.inType); + const type = this.tsParseNonConditionalType(); + + if (this.hasPrecedingLineBreak() || !this.eat(types$1._extends)) { + return type; + } + + const node = this.startNodeAtNode(type); + node.checkType = type; + node.extendsType = this.tsParseNonConditionalType(); + this.expect(types$1.question); + node.trueType = this.tsParseType(); + this.expect(types$1.colon); + node.falseType = this.tsParseType(); + return this.finishNode(node, "TSConditionalType"); + } + + isAbstractConstructorSignature() { + return this.isContextual("abstract") && this.lookahead().type === types$1._new; + } + + tsParseNonConditionalType() { + if (this.tsIsStartOfFunctionType()) { + return this.tsParseFunctionOrConstructorType("TSFunctionType"); + } + + if (this.match(types$1._new)) { + return this.tsParseFunctionOrConstructorType("TSConstructorType"); + } else if (this.isAbstractConstructorSignature()) { + return this.tsParseFunctionOrConstructorType("TSConstructorType", true); + } + + return this.tsParseUnionTypeOrHigher(); + } + + tsParseTypeAssertion() { + const node = this.startNode(); + + const _const = this.tsTryNextParseConstantContext(); + + node.typeAnnotation = _const || this.tsNextThenParseType(); + this.expectRelational(">"); + node.expression = this.parseMaybeUnary(); + return this.finishNode(node, "TSTypeAssertion"); + } + + tsParseHeritageClause(descriptor) { + const originalStart = this.state.start; + const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this)); + + if (!delimitedList.length) { + this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor); + } + + return delimitedList; + } + + tsParseExpressionWithTypeArguments() { + const node = this.startNode(); + node.expression = this.tsParseEntityName(false); + + if (this.isRelational("<")) { + node.typeParameters = this.tsParseTypeArguments(); + } + + return this.finishNode(node, "TSExpressionWithTypeArguments"); + } + + tsParseInterfaceDeclaration(node) { + if (this.match(types$1.name)) { + node.id = this.parseIdentifier(); + this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE); + } else { + node.id = null; + this.raise(this.state.start, TSErrors.MissingInterfaceName); + } + + node.typeParameters = this.tsTryParseTypeParameters(); + + if (this.eat(types$1._extends)) { + node.extends = this.tsParseHeritageClause("extends"); + } + + const body = this.startNode(); + body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this)); + node.body = this.finishNode(body, "TSInterfaceBody"); + return this.finishNode(node, "TSInterfaceDeclaration"); + } + + tsParseTypeAliasDeclaration(node) { + node.id = this.parseIdentifier(); + this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE); + node.typeParameters = this.tsTryParseTypeParameters(); + node.typeAnnotation = this.tsInType(() => { + this.expect(types$1.eq); + + if (this.isContextual("intrinsic") && this.lookahead().type !== types$1.dot) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSIntrinsicKeyword"); + } + + return this.tsParseType(); + }); + this.semicolon(); + return this.finishNode(node, "TSTypeAliasDeclaration"); + } + + tsInNoContext(cb) { + const oldContext = this.state.context; + this.state.context = [oldContext[0]]; + + try { + return cb(); + } finally { + this.state.context = oldContext; + } + } + + tsInType(cb) { + const oldInType = this.state.inType; + this.state.inType = true; + + try { + return cb(); + } finally { + this.state.inType = oldInType; + } + } + + tsEatThenParseType(token) { + return !this.match(token) ? undefined : this.tsNextThenParseType(); + } + + tsExpectThenParseType(token) { + return this.tsDoThenParseType(() => this.expect(token)); + } + + tsNextThenParseType() { + return this.tsDoThenParseType(() => this.next()); + } + + tsDoThenParseType(cb) { + return this.tsInType(() => { + cb(); + return this.tsParseType(); + }); + } + + tsParseEnumMember() { + const node = this.startNode(); + node.id = this.match(types$1.string) ? this.parseExprAtom() : this.parseIdentifier(true); + + if (this.eat(types$1.eq)) { + node.initializer = this.parseMaybeAssignAllowIn(); + } + + return this.finishNode(node, "TSEnumMember"); + } + + tsParseEnumDeclaration(node, isConst) { + if (isConst) node.const = true; + node.id = this.parseIdentifier(); + this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM); + this.expect(types$1.braceL); + node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); + this.expect(types$1.braceR); + return this.finishNode(node, "TSEnumDeclaration"); + } + + tsParseModuleBlock() { + const node = this.startNode(); + this.scope.enter(SCOPE_OTHER); + this.expect(types$1.braceL); + this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types$1.braceR); + this.scope.exit(); + return this.finishNode(node, "TSModuleBlock"); + } + + tsParseModuleOrNamespaceDeclaration(node, nested = false) { + node.id = this.parseIdentifier(); + + if (!nested) { + this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE); + } + + if (this.eat(types$1.dot)) { + const inner = this.startNode(); + this.tsParseModuleOrNamespaceDeclaration(inner, true); + node.body = inner; + } else { + this.scope.enter(SCOPE_TS_MODULE); + this.prodParam.enter(PARAM); + node.body = this.tsParseModuleBlock(); + this.prodParam.exit(); + this.scope.exit(); + } + + return this.finishNode(node, "TSModuleDeclaration"); + } + + tsParseAmbientExternalModuleDeclaration(node) { + if (this.isContextual("global")) { + node.global = true; + node.id = this.parseIdentifier(); + } else if (this.match(types$1.string)) { + node.id = this.parseExprAtom(); + } else { + this.unexpected(); + } + + if (this.match(types$1.braceL)) { + this.scope.enter(SCOPE_TS_MODULE); + this.prodParam.enter(PARAM); + node.body = this.tsParseModuleBlock(); + this.prodParam.exit(); + this.scope.exit(); + } else { + this.semicolon(); + } + + return this.finishNode(node, "TSModuleDeclaration"); + } + + tsParseImportEqualsDeclaration(node, isExport) { + node.isExport = isExport || false; + node.id = this.parseIdentifier(); + this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL); + this.expect(types$1.eq); + const moduleReference = this.tsParseModuleReference(); + + if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") { + this.raise(moduleReference.start, TSErrors.ImportAliasHasImportType); + } + + node.moduleReference = moduleReference; + this.semicolon(); + return this.finishNode(node, "TSImportEqualsDeclaration"); + } + + tsIsExternalModuleReference() { + return this.isContextual("require") && this.lookaheadCharCode() === 40; + } + + tsParseModuleReference() { + return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false); + } + + tsParseExternalModuleReference() { + const node = this.startNode(); + this.expectContextual("require"); + this.expect(types$1.parenL); + + if (!this.match(types$1.string)) { + throw this.unexpected(); + } + + node.expression = this.parseExprAtom(); + this.expect(types$1.parenR); + return this.finishNode(node, "TSExternalModuleReference"); + } + + tsLookAhead(f) { + const state = this.state.clone(); + const res = f(); + this.state = state; + return res; + } + + tsTryParseAndCatch(f) { + const result = this.tryParse(abort => f() || abort()); + if (result.aborted || !result.node) return undefined; + if (result.error) this.state = result.failState; + return result.node; + } + + tsTryParse(f) { + const state = this.state.clone(); + const result = f(); + + if (result !== undefined && result !== false) { + return result; + } else { + this.state = state; + return undefined; + } + } + + tsTryParseDeclare(nany) { + if (this.isLineTerminator()) { + return; + } + + let starttype = this.state.type; + let kind; + + if (this.isContextual("let")) { + starttype = types$1._var; + kind = "let"; + } + + return this.tsInAmbientContext(() => { + switch (starttype) { + case types$1._function: + nany.declare = true; + return this.parseFunctionStatement(nany, false, true); + + case types$1._class: + nany.declare = true; + return this.parseClass(nany, true, false); + + case types$1._const: + if (this.match(types$1._const) && this.isLookaheadContextual("enum")) { + this.expect(types$1._const); + this.expectContextual("enum"); + return this.tsParseEnumDeclaration(nany, true); + } + + case types$1._var: + kind = kind || this.state.value; + return this.parseVarStatement(nany, kind); + + case types$1.name: + { + const value = this.state.value; + + if (value === "global") { + return this.tsParseAmbientExternalModuleDeclaration(nany); + } else { + return this.tsParseDeclaration(nany, value, true); + } + } + } + }); + } + + tsTryParseExportDeclaration() { + return this.tsParseDeclaration(this.startNode(), this.state.value, true); + } + + tsParseExpressionStatement(node, expr) { + switch (expr.name) { + case "declare": + { + const declaration = this.tsTryParseDeclare(node); + + if (declaration) { + declaration.declare = true; + return declaration; + } + + break; + } + + case "global": + if (this.match(types$1.braceL)) { + this.scope.enter(SCOPE_TS_MODULE); + this.prodParam.enter(PARAM); + const mod = node; + mod.global = true; + mod.id = expr; + mod.body = this.tsParseModuleBlock(); + this.scope.exit(); + this.prodParam.exit(); + return this.finishNode(mod, "TSModuleDeclaration"); + } + + break; + + default: + return this.tsParseDeclaration(node, expr.name, false); + } + } + + tsParseDeclaration(node, value, next) { + switch (value) { + case "abstract": + if (this.tsCheckLineTerminator(next) && (this.match(types$1._class) || this.match(types$1.name))) { + return this.tsParseAbstractDeclaration(node); + } + + break; + + case "enum": + if (next || this.match(types$1.name)) { + if (next) this.next(); + return this.tsParseEnumDeclaration(node, false); + } + + break; + + case "interface": + if (this.tsCheckLineTerminator(next) && this.match(types$1.name)) { + return this.tsParseInterfaceDeclaration(node); + } + + break; + + case "module": + if (this.tsCheckLineTerminator(next)) { + if (this.match(types$1.string)) { + return this.tsParseAmbientExternalModuleDeclaration(node); + } else if (this.match(types$1.name)) { + return this.tsParseModuleOrNamespaceDeclaration(node); + } + } + + break; + + case "namespace": + if (this.tsCheckLineTerminator(next) && this.match(types$1.name)) { + return this.tsParseModuleOrNamespaceDeclaration(node); + } + + break; + + case "type": + if (this.tsCheckLineTerminator(next) && this.match(types$1.name)) { + return this.tsParseTypeAliasDeclaration(node); + } + + break; + } + } + + tsCheckLineTerminator(next) { + if (next) { + if (this.hasFollowingLineBreak()) return false; + this.next(); + return true; + } + + return !this.isLineTerminator(); + } + + tsTryParseGenericAsyncArrowFunction(startPos, startLoc) { + if (!this.isRelational("<")) { + return undefined; + } + + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + this.state.maybeInArrowParameters = true; + const res = this.tsTryParseAndCatch(() => { + const node = this.startNodeAt(startPos, startLoc); + node.typeParameters = this.tsParseTypeParameters(); + super.parseFunctionParams(node); + node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation(); + this.expect(types$1.arrow); + return node; + }); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + + if (!res) { + return undefined; + } + + return this.parseArrowExpression(res, null, true); + } + + tsParseTypeArguments() { + const node = this.startNode(); + node.params = this.tsInType(() => this.tsInNoContext(() => { + this.expectRelational("<"); + return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this)); + })); + + if (node.params.length === 0) { + this.raise(node.start, TSErrors.EmptyTypeArguments); + } + + this.expectRelational(">"); + return this.finishNode(node, "TSTypeParameterInstantiation"); + } + + tsIsDeclarationStart() { + if (this.match(types$1.name)) { + switch (this.state.value) { + case "abstract": + case "declare": + case "enum": + case "interface": + case "module": + case "namespace": + case "type": + return true; + } + } + + return false; + } + + isExportDefaultSpecifier() { + if (this.tsIsDeclarationStart()) return false; + return super.isExportDefaultSpecifier(); + } + + parseAssignableListItem(allowModifiers, decorators) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + let accessibility; + let readonly = false; + let override = false; + + if (allowModifiers !== undefined) { + const modified = {}; + this.tsParseModifiers(modified, ["public", "private", "protected", "override", "readonly"]); + accessibility = modified.accessibility; + override = modified.override; + readonly = modified.readonly; + + if (allowModifiers === false && (accessibility || readonly || override)) { + this.raise(startPos, TSErrors.UnexpectedParameterModifier); + } + } + + const left = this.parseMaybeDefault(); + this.parseAssignableListItemTypes(left); + const elt = this.parseMaybeDefault(left.start, left.loc.start, left); + + if (accessibility || readonly || override) { + const pp = this.startNodeAt(startPos, startLoc); + + if (decorators.length) { + pp.decorators = decorators; + } + + if (accessibility) pp.accessibility = accessibility; + if (readonly) pp.readonly = readonly; + if (override) pp.override = override; + + if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { + this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind); + } + + pp.parameter = elt; + return this.finishNode(pp, "TSParameterProperty"); + } + + if (decorators.length) { + left.decorators = decorators; + } + + return elt; + } + + parseFunctionBodyAndFinish(node, type, isMethod = false) { + if (this.match(types$1.colon)) { + node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types$1.colon); + } + + const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined; + + if (bodilessType && !this.match(types$1.braceL) && this.isLineTerminator()) { + this.finishNode(node, bodilessType); + return; + } + + if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) { + this.raise(node.start, TSErrors.DeclareFunctionHasImplementation); + + if (node.declare) { + super.parseFunctionBodyAndFinish(node, bodilessType, isMethod); + return; + } + } + + super.parseFunctionBodyAndFinish(node, type, isMethod); + } + + registerFunctionStatementId(node) { + if (!node.body && node.id) { + this.checkLVal(node.id, "function name", BIND_TS_AMBIENT); + } else { + super.registerFunctionStatementId(...arguments); + } + } + + tsCheckForInvalidTypeCasts(items) { + items.forEach(node => { + if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") { + this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation); + } + }); + } + + toReferencedList(exprList, isInParens) { + this.tsCheckForInvalidTypeCasts(exprList); + return exprList; + } + + parseArrayLike(...args) { + const node = super.parseArrayLike(...args); + + if (node.type === "ArrayExpression") { + this.tsCheckForInvalidTypeCasts(node.elements); + } + + return node; + } + + parseSubscript(base, startPos, startLoc, noCalls, state) { + if (!this.hasPrecedingLineBreak() && this.match(types$1.bang)) { + this.state.exprAllowed = false; + this.next(); + const nonNullExpression = this.startNodeAt(startPos, startLoc); + nonNullExpression.expression = base; + return this.finishNode(nonNullExpression, "TSNonNullExpression"); + } + + let isOptionalCall = false; + + if (this.match(types$1.questionDot) && this.lookaheadCharCode() === 60) { + if (noCalls) { + state.stop = true; + return base; + } + + state.optionalChainMember = isOptionalCall = true; + this.next(); + } + + if (this.isRelational("<")) { + let missingParenErrorPos; + const result = this.tsTryParseAndCatch(() => { + if (!noCalls && this.atPossibleAsyncArrow(base)) { + const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc); + + if (asyncArrowFn) { + return asyncArrowFn; + } + } + + const node = this.startNodeAt(startPos, startLoc); + node.callee = base; + const typeArguments = this.tsParseTypeArguments(); + + if (typeArguments) { + if (isOptionalCall && !this.match(types$1.parenL)) { + missingParenErrorPos = this.state.pos; + this.unexpected(); + } + + if (!noCalls && this.eat(types$1.parenL)) { + node.arguments = this.parseCallExpressionArguments(types$1.parenR, false); + this.tsCheckForInvalidTypeCasts(node.arguments); + node.typeParameters = typeArguments; + + if (state.optionalChainMember) { + node.optional = isOptionalCall; + } + + return this.finishCallExpression(node, state.optionalChainMember); + } else if (this.match(types$1.backQuote)) { + const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state); + result.typeParameters = typeArguments; + return result; + } + } + + this.unexpected(); + }); + + if (missingParenErrorPos) { + this.unexpected(missingParenErrorPos, types$1.parenL); + } + + if (result) return result; + } + + return super.parseSubscript(base, startPos, startLoc, noCalls, state); + } + + parseNewArguments(node) { + if (this.isRelational("<")) { + const typeParameters = this.tsTryParseAndCatch(() => { + const args = this.tsParseTypeArguments(); + if (!this.match(types$1.parenL)) this.unexpected(); + return args; + }); + + if (typeParameters) { + node.typeParameters = typeParameters; + } + } + + super.parseNewArguments(node); + } + + parseExprOp(left, leftStartPos, leftStartLoc, minPrec) { + if (nonNull(types$1._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) { + const node = this.startNodeAt(leftStartPos, leftStartLoc); + node.expression = left; + + const _const = this.tsTryNextParseConstantContext(); + + if (_const) { + node.typeAnnotation = _const; + } else { + node.typeAnnotation = this.tsNextThenParseType(); + } + + this.finishNode(node, "TSAsExpression"); + this.reScan_lt_gt(); + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec); + } + + return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec); + } + + checkReservedWord(word, startLoc, checkKeywords, isBinding) {} + + checkDuplicateExports() {} + + parseImport(node) { + node.importKind = "value"; + + if (this.match(types$1.name) || this.match(types$1.star) || this.match(types$1.braceL)) { + let ahead = this.lookahead(); + + if (this.isContextual("type") && ahead.type !== types$1.comma && !(ahead.type === types$1.name && ahead.value === "from") && ahead.type !== types$1.eq) { + node.importKind = "type"; + this.next(); + ahead = this.lookahead(); + } + + if (this.match(types$1.name) && ahead.type === types$1.eq) { + return this.tsParseImportEqualsDeclaration(node); + } + } + + const importNode = super.parseImport(node); + + if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") { + this.raise(importNode.start, TSErrors.TypeImportCannotSpecifyDefaultAndNamed); + } + + return importNode; + } + + parseExport(node) { + if (this.match(types$1._import)) { + this.next(); + + if (this.isContextual("type") && this.lookaheadCharCode() !== 61) { + node.importKind = "type"; + this.next(); + } else { + node.importKind = "value"; + } + + return this.tsParseImportEqualsDeclaration(node, true); + } else if (this.eat(types$1.eq)) { + const assign = node; + assign.expression = this.parseExpression(); + this.semicolon(); + return this.finishNode(assign, "TSExportAssignment"); + } else if (this.eatContextual("as")) { + const decl = node; + this.expectContextual("namespace"); + decl.id = this.parseIdentifier(); + this.semicolon(); + return this.finishNode(decl, "TSNamespaceExportDeclaration"); + } else { + if (this.isContextual("type") && this.lookahead().type === types$1.braceL) { + this.next(); + node.exportKind = "type"; + } else { + node.exportKind = "value"; + } + + return super.parseExport(node); + } + } + + isAbstractClass() { + return this.isContextual("abstract") && this.lookahead().type === types$1._class; + } + + parseExportDefaultExpression() { + if (this.isAbstractClass()) { + const cls = this.startNode(); + this.next(); + cls.abstract = true; + this.parseClass(cls, true, true); + return cls; + } + + if (this.state.value === "interface") { + const interfaceNode = this.startNode(); + this.next(); + const result = this.tsParseInterfaceDeclaration(interfaceNode); + if (result) return result; + } + + return super.parseExportDefaultExpression(); + } + + parseStatementContent(context, topLevel) { + if (this.state.type === types$1._const) { + const ahead = this.lookahead(); + + if (ahead.type === types$1.name && ahead.value === "enum") { + const node = this.startNode(); + this.expect(types$1._const); + this.expectContextual("enum"); + return this.tsParseEnumDeclaration(node, true); + } + } + + return super.parseStatementContent(context, topLevel); + } + + parseAccessModifier() { + return this.tsParseModifier(["public", "protected", "private"]); + } + + tsHasSomeModifiers(member, modifiers) { + return modifiers.some(modifier => { + if (tsIsAccessModifier(modifier)) { + return member.accessibility === modifier; + } + + return !!member[modifier]; + }); + } + + tsIsStartOfStaticBlocks() { + return this.isContextual("static") && this.lookaheadCharCode() === 123; + } + + parseClassMember(classBody, member, state) { + const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"]; + this.tsParseModifiers(member, modifiers, undefined, undefined, true); + + const callParseClassMemberWithIsStatic = () => { + if (this.tsIsStartOfStaticBlocks()) { + this.next(); + this.next(); + + if (this.tsHasSomeModifiers(member, modifiers)) { + this.raise(this.state.pos, TSErrors.StaticBlockCannotHaveModifier); + } + + this.parseClassStaticBlock(classBody, member); + } else { + this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static); + } + }; + + if (member.declare) { + this.tsInAmbientContext(callParseClassMemberWithIsStatic); + } else { + callParseClassMemberWithIsStatic(); + } + } + + parseClassMemberWithIsStatic(classBody, member, state, isStatic) { + const idx = this.tsTryParseIndexSignature(member); + + if (idx) { + classBody.body.push(idx); + + if (member.abstract) { + this.raise(member.start, TSErrors.IndexSignatureHasAbstract); + } + + if (member.accessibility) { + this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility); + } + + if (member.declare) { + this.raise(member.start, TSErrors.IndexSignatureHasDeclare); + } + + if (member.override) { + this.raise(member.start, TSErrors.IndexSignatureHasOverride); + } + + return; + } + + if (!this.state.inAbstractClass && member.abstract) { + this.raise(member.start, TSErrors.NonAbstractClassHasAbstractMethod); + } + + if (member.override) { + if (!state.hadSuperClass) { + this.raise(member.start, TSErrors.OverrideNotInSubClass); + } + } + + super.parseClassMemberWithIsStatic(classBody, member, state, isStatic); + } + + parsePostMemberNameModifiers(methodOrProp) { + const optional = this.eat(types$1.question); + if (optional) methodOrProp.optional = true; + + if (methodOrProp.readonly && this.match(types$1.parenL)) { + this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly); + } + + if (methodOrProp.declare && this.match(types$1.parenL)) { + this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare); + } + } + + parseExpressionStatement(node, expr) { + const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined; + return decl || super.parseExpressionStatement(node, expr); + } + + shouldParseExportDeclaration() { + if (this.tsIsDeclarationStart()) return true; + return super.shouldParseExportDeclaration(); + } + + parseConditional(expr, startPos, startLoc, refExpressionErrors) { + if (!this.state.maybeInArrowParameters || !this.match(types$1.question)) { + return super.parseConditional(expr, startPos, startLoc, refExpressionErrors); + } + + const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc)); + + if (!result.node) { + if (result.error) { + super.setOptionalParametersError(refExpressionErrors, result.error); + } + + return expr; + } + + if (result.error) this.state = result.failState; + return result.node; + } + + parseParenItem(node, startPos, startLoc) { + node = super.parseParenItem(node, startPos, startLoc); + + if (this.eat(types$1.question)) { + node.optional = true; + this.resetEndLocation(node); + } + + if (this.match(types$1.colon)) { + const typeCastNode = this.startNodeAt(startPos, startLoc); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.tsParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TSTypeCastExpression"); + } + + return node; + } + + parseExportDeclaration(node) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + const isDeclare = this.eatContextual("declare"); + + if (isDeclare && (this.isContextual("declare") || !this.shouldParseExportDeclaration())) { + throw this.raise(this.state.start, TSErrors.ExpectedAmbientAfterExportDeclare); + } + + let declaration; + + if (this.match(types$1.name)) { + declaration = this.tsTryParseExportDeclaration(); + } + + if (!declaration) { + declaration = super.parseExportDeclaration(node); + } + + if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) { + node.exportKind = "type"; + } + + if (declaration && isDeclare) { + this.resetStartLocation(declaration, startPos, startLoc); + declaration.declare = true; + } + + return declaration; + } + + parseClassId(node, isStatement, optionalId) { + if ((!isStatement || optionalId) && this.isContextual("implements")) { + return; + } + + super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS); + const typeParameters = this.tsTryParseTypeParameters(); + if (typeParameters) node.typeParameters = typeParameters; + } + + parseClassPropertyAnnotation(node) { + if (!node.optional && this.eat(types$1.bang)) { + node.definite = true; + } + + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + } + + parseClassProperty(node) { + this.parseClassPropertyAnnotation(node); + + if (this.state.isAmbientContext && this.match(types$1.eq)) { + this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer); + } + + if (node.abstract && this.match(types$1.eq)) { + const { + key + } = node; + this.raise(this.state.start, TSErrors.AbstractPropertyHasInitializer, key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`); + } + + return super.parseClassProperty(node); + } + + parseClassPrivateProperty(node) { + if (node.abstract) { + this.raise(node.start, TSErrors.PrivateElementHasAbstract); + } + + if (node.accessibility) { + this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility); + } + + this.parseClassPropertyAnnotation(node); + return super.parseClassPrivateProperty(node); + } + + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + const typeParameters = this.tsTryParseTypeParameters(); + + if (typeParameters && isConstructor) { + this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters); + } + + if (method.declare && (method.kind === "get" || method.kind === "set")) { + this.raise(method.start, TSErrors.DeclareAccessor, method.kind); + } + + if (typeParameters) method.typeParameters = typeParameters; + super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + } + + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + const typeParameters = this.tsTryParseTypeParameters(); + if (typeParameters) method.typeParameters = typeParameters; + super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); + } + + parseClassSuper(node) { + super.parseClassSuper(node); + + if (node.superClass && this.isRelational("<")) { + node.superTypeParameters = this.tsParseTypeArguments(); + } + + if (this.eatContextual("implements")) { + node.implements = this.tsParseHeritageClause("implements"); + } + } + + parseObjPropValue(prop, ...args) { + const typeParameters = this.tsTryParseTypeParameters(); + if (typeParameters) prop.typeParameters = typeParameters; + super.parseObjPropValue(prop, ...args); + } + + parseFunctionParams(node, allowModifiers) { + const typeParameters = this.tsTryParseTypeParameters(); + if (typeParameters) node.typeParameters = typeParameters; + super.parseFunctionParams(node, allowModifiers); + } + + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + + if (decl.id.type === "Identifier" && this.eat(types$1.bang)) { + decl.definite = true; + } + + const type = this.tsTryParseTypeAnnotation(); + + if (type) { + decl.id.typeAnnotation = type; + this.resetEndLocation(decl.id); + } + } + + parseAsyncArrowFromCallExpression(node, call) { + if (this.match(types$1.colon)) { + node.returnType = this.tsParseTypeAnnotation(); + } + + return super.parseAsyncArrowFromCallExpression(node, call); + } + + parseMaybeAssign(...args) { + var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3; + + let state; + let jsx; + let typeCast; + + if (this.hasPlugin("jsx") && (this.match(types$1.jsxTagStart) || this.isRelational("<"))) { + state = this.state.clone(); + jsx = this.tryParse(() => super.parseMaybeAssign(...args), state); + if (!jsx.error) return jsx.node; + const { + context + } = this.state; + + if (context[context.length - 1] === types.j_oTag) { + context.length -= 2; + } else if (context[context.length - 1] === types.j_expr) { + context.length -= 1; + } + } + + if (!((_jsx = jsx) != null && _jsx.error) && !this.isRelational("<")) { + return super.parseMaybeAssign(...args); + } + + let typeParameters; + state = state || this.state.clone(); + const arrow = this.tryParse(abort => { + var _expr$extra, _typeParameters; + + typeParameters = this.tsParseTypeParameters(); + const expr = super.parseMaybeAssign(...args); + + if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { + abort(); + } + + if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) { + this.resetStartLocationFromNode(expr, typeParameters); + } + + expr.typeParameters = typeParameters; + return expr; + }, state); + if (!arrow.error && !arrow.aborted) return arrow.node; + + if (!jsx) { + assert(!this.hasPlugin("jsx")); + typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state); + if (!typeCast.error) return typeCast.node; + } + + if ((_jsx2 = jsx) != null && _jsx2.node) { + this.state = jsx.failState; + return jsx.node; + } + + if (arrow.node) { + this.state = arrow.failState; + return arrow.node; + } + + if ((_typeCast = typeCast) != null && _typeCast.node) { + this.state = typeCast.failState; + return typeCast.node; + } + + if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error; + if (arrow.thrown) throw arrow.error; + if ((_typeCast2 = typeCast) != null && _typeCast2.thrown) throw typeCast.error; + throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error); + } + + parseMaybeUnary(refExpressionErrors) { + if (!this.hasPlugin("jsx") && this.isRelational("<")) { + return this.tsParseTypeAssertion(); + } else { + return super.parseMaybeUnary(refExpressionErrors); + } + } + + parseArrow(node) { + if (this.match(types$1.colon)) { + const result = this.tryParse(abort => { + const returnType = this.tsParseTypeOrTypePredicateAnnotation(types$1.colon); + if (this.canInsertSemicolon() || !this.match(types$1.arrow)) abort(); + return returnType; + }); + if (result.aborted) return; + + if (!result.thrown) { + if (result.error) this.state = result.failState; + node.returnType = result.node; + } + } + + return super.parseArrow(node); + } + + parseAssignableListItemTypes(param) { + if (this.eat(types$1.question)) { + if (param.type !== "Identifier" && !this.state.isAmbientContext && !this.state.inType) { + this.raise(param.start, TSErrors.PatternIsOptional); + } + + param.optional = true; + } + + const type = this.tsTryParseTypeAnnotation(); + if (type) param.typeAnnotation = type; + this.resetEndLocation(param); + return param; + } + + isAssignable(node, isBinding) { + switch (node.type) { + case "TSTypeCastExpression": + return this.isAssignable(node.expression, isBinding); + + case "TSParameterProperty": + return true; + + default: + return super.isAssignable(node, isBinding); + } + } + + toAssignable(node, isLHS = false) { + switch (node.type) { + case "TSTypeCastExpression": + return super.toAssignable(this.typeCastToParameter(node), isLHS); + + case "TSParameterProperty": + return super.toAssignable(node, isLHS); + + case "ParenthesizedExpression": + return this.toAssignableParenthesizedExpression(node, isLHS); + + case "TSAsExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + node.expression = this.toAssignable(node.expression, isLHS); + return node; + + default: + return super.toAssignable(node, isLHS); + } + } + + toAssignableParenthesizedExpression(node, isLHS) { + switch (node.expression.type) { + case "TSAsExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + case "ParenthesizedExpression": + node.expression = this.toAssignable(node.expression, isLHS); + return node; + + default: + return super.toAssignable(node, isLHS); + } + } + + checkLVal(expr, contextDescription, ...args) { + var _expr$extra2; + + switch (expr.type) { + case "TSTypeCastExpression": + return; + + case "TSParameterProperty": + this.checkLVal(expr.parameter, "parameter property", ...args); + return; + + case "TSAsExpression": + case "TSTypeAssertion": + if (!args[0] && contextDescription !== "parenthesized expression" && !((_expr$extra2 = expr.extra) != null && _expr$extra2.parenthesized)) { + this.raise(expr.start, ErrorMessages.InvalidLhs, contextDescription); + break; + } + + this.checkLVal(expr.expression, "parenthesized expression", ...args); + return; + + case "TSNonNullExpression": + this.checkLVal(expr.expression, contextDescription, ...args); + return; + + default: + super.checkLVal(expr, contextDescription, ...args); + return; + } + } + + parseBindingAtom() { + switch (this.state.type) { + case types$1._this: + return this.parseIdentifier(true); + + default: + return super.parseBindingAtom(); + } + } + + parseMaybeDecoratorArguments(expr) { + if (this.isRelational("<")) { + const typeArguments = this.tsParseTypeArguments(); + + if (this.match(types$1.parenL)) { + const call = super.parseMaybeDecoratorArguments(expr); + call.typeParameters = typeArguments; + return call; + } + + this.unexpected(this.state.start, types$1.parenL); + } + + return super.parseMaybeDecoratorArguments(expr); + } + + checkCommaAfterRest(close) { + if (this.state.isAmbientContext && this.match(types$1.comma) && this.lookaheadCharCode() === close) { + this.next(); + } else { + super.checkCommaAfterRest(close); + } + } + + isClassMethod() { + return this.isRelational("<") || super.isClassMethod(); + } + + isClassProperty() { + return this.match(types$1.bang) || this.match(types$1.colon) || super.isClassProperty(); + } + + parseMaybeDefault(...args) { + const node = super.parseMaybeDefault(...args); + + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign); + } + + return node; + } + + getTokenFromCode(code) { + if (this.state.inType && (code === 62 || code === 60)) { + return this.finishOp(types$1.relational, 1); + } else { + return super.getTokenFromCode(code); + } + } + + reScan_lt_gt() { + if (this.match(types$1.relational)) { + const code = this.input.charCodeAt(this.state.start); + + if (code === 60 || code === 62) { + this.state.pos -= 1; + this.readToken_lt_gt(code); + } + } + } + + toAssignableList(exprList) { + for (let i = 0; i < exprList.length; i++) { + const expr = exprList[i]; + if (!expr) continue; + + switch (expr.type) { + case "TSTypeCastExpression": + exprList[i] = this.typeCastToParameter(expr); + break; + + case "TSAsExpression": + case "TSTypeAssertion": + if (!this.state.maybeInArrowParameters) { + exprList[i] = this.typeCastToParameter(expr); + } else { + this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter); + } + + break; + } + } + + return super.toAssignableList(...arguments); + } + + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end); + return node.expression; + } + + shouldParseArrow(params) { + if (this.match(types$1.colon)) { + return params.every(expr => this.isAssignable(expr, true)); + } + + return super.shouldParseArrow(params); + } + + shouldParseAsyncArrow() { + return this.match(types$1.colon) || super.shouldParseAsyncArrow(); + } + + canHaveLeadingDecorator() { + return super.canHaveLeadingDecorator() || this.isAbstractClass(); + } + + jsxParseOpeningElementAfterName(node) { + if (this.isRelational("<")) { + const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments()); + if (typeArguments) node.typeParameters = typeArguments; + } + + return super.jsxParseOpeningElementAfterName(node); + } + + getGetterSetterExpectedParamCount(method) { + const baseCount = super.getGetterSetterExpectedParamCount(method); + const params = this.getObjectOrClassMethodParams(method); + const firstParam = params[0]; + const hasContextParam = firstParam && this.isThisParam(firstParam); + return hasContextParam ? baseCount + 1 : baseCount; + } + + parseCatchClauseParam() { + const param = super.parseCatchClauseParam(); + const type = this.tsTryParseTypeAnnotation(); + + if (type) { + param.typeAnnotation = type; + this.resetEndLocation(param); + } + + return param; + } + + tsInAmbientContext(cb) { + const oldIsAmbientContext = this.state.isAmbientContext; + this.state.isAmbientContext = true; + + try { + return cb(); + } finally { + this.state.isAmbientContext = oldIsAmbientContext; + } + } + + parseClass(node, ...args) { + const oldInAbstractClass = this.state.inAbstractClass; + this.state.inAbstractClass = !!node.abstract; + + try { + return super.parseClass(node, ...args); + } finally { + this.state.inAbstractClass = oldInAbstractClass; + } + } + + tsParseAbstractDeclaration(node) { + if (this.match(types$1._class)) { + node.abstract = true; + return this.parseClass(node, true, false); + } else if (this.isContextual("interface")) { + if (!this.hasFollowingLineBreak()) { + node.abstract = true; + this.raise(node.start, TSErrors.NonClassMethodPropertyHasAbstractModifer); + this.next(); + return this.tsParseInterfaceDeclaration(node); + } + } else { + this.unexpected(null, types$1._class); + } + } + + parseMethod(...args) { + const method = super.parseMethod(...args); + + if (method.abstract) { + const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body; + + if (hasBody) { + const { + key + } = method; + this.raise(method.start, TSErrors.AbstractMethodHasImplementation, key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`); + } + } + + return method; + } + + tsParseTypeParameterName() { + const typeName = this.parseIdentifier(); + return typeName.name; + } + + shouldParseAsAmbientContext() { + return !!this.getPluginOption("typescript", "dts"); + } + + parse() { + if (this.shouldParseAsAmbientContext()) { + this.state.isAmbientContext = true; + } + + return super.parse(); + } + + getExpression() { + if (this.shouldParseAsAmbientContext()) { + this.state.isAmbientContext = true; + } + + return super.getExpression(); + } + +}); + +types$1.placeholder = new TokenType("%%", { + startsExpr: true +}); +const PlaceHolderErrors = makeErrorTemplates({ + ClassNameIsRequired: "A class name is required." +}, ErrorCodes.SyntaxError); +var placeholders = (superClass => class extends superClass { + parsePlaceholder(expectedNode) { + if (this.match(types$1.placeholder)) { + const node = this.startNode(); + this.next(); + this.assertNoSpace("Unexpected space in placeholder."); + node.name = super.parseIdentifier(true); + this.assertNoSpace("Unexpected space in placeholder."); + this.expect(types$1.placeholder); + return this.finishPlaceholder(node, expectedNode); + } + } + + finishPlaceholder(node, expectedNode) { + const isFinished = !!(node.expectedNode && node.type === "Placeholder"); + node.expectedNode = expectedNode; + return isFinished ? node : this.finishNode(node, "Placeholder"); + } + + getTokenFromCode(code) { + if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) { + return this.finishOp(types$1.placeholder, 2); + } + + return super.getTokenFromCode(...arguments); + } + + parseExprAtom() { + return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments); + } + + parseIdentifier() { + return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments); + } + + checkReservedWord(word) { + if (word !== undefined) super.checkReservedWord(...arguments); + } + + parseBindingAtom() { + return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments); + } + + checkLVal(expr) { + if (expr.type !== "Placeholder") super.checkLVal(...arguments); + } + + toAssignable(node) { + if (node && node.type === "Placeholder" && node.expectedNode === "Expression") { + node.expectedNode = "Pattern"; + return node; + } + + return super.toAssignable(...arguments); + } + + isLet(context) { + if (super.isLet(context)) { + return true; + } + + if (!this.isContextual("let")) { + return false; + } + + if (context) return false; + const nextToken = this.lookahead(); + + if (nextToken.type === types$1.placeholder) { + return true; + } + + return false; + } + + verifyBreakContinue(node) { + if (node.label && node.label.type === "Placeholder") return; + super.verifyBreakContinue(...arguments); + } + + parseExpressionStatement(node, expr) { + if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) { + return super.parseExpressionStatement(...arguments); + } + + if (this.match(types$1.colon)) { + const stmt = node; + stmt.label = this.finishPlaceholder(expr, "Identifier"); + this.next(); + stmt.body = this.parseStatement("label"); + return this.finishNode(stmt, "LabeledStatement"); + } + + this.semicolon(); + node.name = expr.name; + return this.finishPlaceholder(node, "Statement"); + } + + parseBlock() { + return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments); + } + + parseFunctionId() { + return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments); + } + + parseClass(node, isStatement, optionalId) { + const type = isStatement ? "ClassDeclaration" : "ClassExpression"; + this.next(); + this.takeDecorators(node); + const oldStrict = this.state.strict; + const placeholder = this.parsePlaceholder("Identifier"); + + if (placeholder) { + if (this.match(types$1._extends) || this.match(types$1.placeholder) || this.match(types$1.braceL)) { + node.id = placeholder; + } else if (optionalId || !isStatement) { + node.id = null; + node.body = this.finishPlaceholder(placeholder, "ClassBody"); + return this.finishNode(node, type); + } else { + this.unexpected(null, PlaceHolderErrors.ClassNameIsRequired); + } + } else { + this.parseClassId(node, isStatement, optionalId); + } + + this.parseClassSuper(node); + node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict); + return this.finishNode(node, type); + } + + parseExport(node) { + const placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return super.parseExport(...arguments); + + if (!this.isContextual("from") && !this.match(types$1.comma)) { + node.specifiers = []; + node.source = null; + node.declaration = this.finishPlaceholder(placeholder, "Declaration"); + return this.finishNode(node, "ExportNamedDeclaration"); + } + + this.expectPlugin("exportDefaultFrom"); + const specifier = this.startNode(); + specifier.exported = placeholder; + node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return super.parseExport(node); + } + + isExportDefaultSpecifier() { + if (this.match(types$1._default)) { + const next = this.nextTokenStart(); + + if (this.isUnparsedContextual(next, "from")) { + if (this.input.startsWith(types$1.placeholder.label, this.nextTokenStartSince(next + 4))) { + return true; + } + } + } + + return super.isExportDefaultSpecifier(); + } + + maybeParseExportDefaultSpecifier(node) { + if (node.specifiers && node.specifiers.length > 0) { + return true; + } + + return super.maybeParseExportDefaultSpecifier(...arguments); + } + + checkExport(node) { + const { + specifiers + } = node; + + if (specifiers != null && specifiers.length) { + node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder"); + } + + super.checkExport(node); + node.specifiers = specifiers; + } + + parseImport(node) { + const placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return super.parseImport(...arguments); + node.specifiers = []; + + if (!this.isContextual("from") && !this.match(types$1.comma)) { + node.source = this.finishPlaceholder(placeholder, "StringLiteral"); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + + const specifier = this.startNodeAtNode(placeholder); + specifier.local = placeholder; + this.finishNode(specifier, "ImportDefaultSpecifier"); + node.specifiers.push(specifier); + + if (this.eat(types$1.comma)) { + const hasStarImport = this.maybeParseStarImportSpecifier(node); + if (!hasStarImport) this.parseNamedImportSpecifiers(node); + } + + this.expectContextual("from"); + node.source = this.parseImportSource(); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + + parseImportSource() { + return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments); + } + +}); + +var v8intrinsic = (superClass => class extends superClass { + parseV8Intrinsic() { + if (this.match(types$1.modulo)) { + const v8IntrinsicStart = this.state.start; + const node = this.startNode(); + this.eat(types$1.modulo); + + if (this.match(types$1.name)) { + const name = this.parseIdentifierName(this.state.start); + const identifier = this.createIdentifier(node, name); + identifier.type = "V8IntrinsicIdentifier"; + + if (this.match(types$1.parenL)) { + return identifier; + } + } + + this.unexpected(v8IntrinsicStart); + } + } + + parseExprAtom() { + return this.parseV8Intrinsic() || super.parseExprAtom(...arguments); + } + +}); + +function hasPlugin(plugins, name) { + return plugins.some(plugin => { + if (Array.isArray(plugin)) { + return plugin[0] === name; + } else { + return plugin === name; + } + }); +} +function getPluginOption(plugins, name, option) { + const plugin = plugins.find(plugin => { + if (Array.isArray(plugin)) { + return plugin[0] === name; + } else { + return plugin === name; + } + }); + + if (plugin && Array.isArray(plugin)) { + return plugin[1][option]; + } + + return null; +} +const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"]; +const TOPIC_TOKENS = ["%", "#"]; +const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"]; +function validatePlugins(plugins) { + if (hasPlugin(plugins, "decorators")) { + if (hasPlugin(plugins, "decorators-legacy")) { + throw new Error("Cannot use the decorators and decorators-legacy plugin together"); + } + + const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport"); + + if (decoratorsBeforeExport == null) { + throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option," + " whose value must be a boolean. If you are migrating from" + " Babylon/Babel 6 or want to use the old decorators proposal, you" + " should use the 'decorators-legacy' plugin instead of 'decorators'."); + } else if (typeof decoratorsBeforeExport !== "boolean") { + throw new Error("'decoratorsBeforeExport' must be a boolean."); + } + } + + if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) { + throw new Error("Cannot combine flow and typescript plugins."); + } + + if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) { + throw new Error("Cannot combine placeholders and v8intrinsic plugins."); + } + + if (hasPlugin(plugins, "pipelineOperator")) { + const proposal = getPluginOption(plugins, "pipelineOperator", "proposal"); + + if (!PIPELINE_PROPOSALS.includes(proposal)) { + const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", "); + throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`); + } + + const tupleSyntaxIsHash = hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") === "hash"; + + if (proposal === "hack") { + if (hasPlugin(plugins, "placeholders")) { + throw new Error("Cannot combine placeholders plugin and Hack-style pipes."); + } + + if (hasPlugin(plugins, "v8intrinsic")) { + throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes."); + } + + const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken"); + + if (!TOPIC_TOKENS.includes(topicToken)) { + const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", "); + throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`); + } + + if (topicToken === "#" && tupleSyntaxIsHash) { + throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.'); + } + } else if (proposal === "smart" && tupleSyntaxIsHash) { + throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.'); + } + } + + if (hasPlugin(plugins, "moduleAttributes")) { + { + if (hasPlugin(plugins, "importAssertions")) { + throw new Error("Cannot combine importAssertions and moduleAttributes plugins."); + } + + const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version"); + + if (moduleAttributesVerionPluginOption !== "may-2020") { + throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'."); + } + } + } + + if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) { + throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", ")); + } + + if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) { + const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins."); + error.missingPlugins = "doExpressions"; + throw error; + } +} +const mixinPlugins = { + estree, + jsx, + flow, + typescript, + v8intrinsic, + placeholders +}; +const mixinPluginNames = Object.keys(mixinPlugins); + +const defaultOptions = { + sourceType: "script", + sourceFilename: undefined, + startLine: 1, + allowAwaitOutsideFunction: false, + allowReturnOutsideFunction: false, + allowImportExportEverywhere: false, + allowSuperOutsideMethod: false, + allowUndeclaredExports: false, + plugins: [], + strictMode: null, + ranges: false, + tokens: false, + createParenthesizedExpressions: false, + errorRecovery: false, + attachComment: true +}; +function getOptions(opts) { + const options = {}; + + for (const key of Object.keys(defaultOptions)) { + options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key]; + } + + return options; +} + +const unwrapParenthesizedExpression = node => { + return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node; +}; + +class LValParser extends NodeUtils { + toAssignable(node, isLHS = false) { + var _node$extra, _node$extra3; + + let parenthesized = undefined; + + if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) { + parenthesized = unwrapParenthesizedExpression(node); + + if (isLHS) { + if (parenthesized.type === "Identifier") { + this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment); + } else if (parenthesized.type !== "MemberExpression") { + this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment); + } + } else { + this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment); + } + } + + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break; + + case "ObjectExpression": + node.type = "ObjectPattern"; + + for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) { + var _node$extra2; + + const prop = node.properties[i]; + const isLast = i === last; + this.toAssignableObjectExpressionProp(prop, isLast, isLHS); + + if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingComma) { + this.raiseRestNotLast(node.extra.trailingComma); + } + } + + break; + + case "ObjectProperty": + this.toAssignable(node.value, isLHS); + break; + + case "SpreadElement": + { + this.checkToRestConversion(node); + node.type = "RestElement"; + const arg = node.argument; + this.toAssignable(arg, isLHS); + break; + } + + case "ArrayExpression": + node.type = "ArrayPattern"; + this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS); + break; + + case "AssignmentExpression": + if (node.operator !== "=") { + this.raise(node.left.end, ErrorMessages.MissingEqInAssignment); + } + + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isLHS); + break; + + case "ParenthesizedExpression": + this.toAssignable(parenthesized, isLHS); + break; + } + + return node; + } + + toAssignableObjectExpressionProp(prop, isLast, isLHS) { + if (prop.type === "ObjectMethod") { + const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod; + this.raise(prop.key.start, error); + } else if (prop.type === "SpreadElement" && !isLast) { + this.raiseRestNotLast(prop.start); + } else { + this.toAssignable(prop, isLHS); + } + } + + toAssignableList(exprList, trailingCommaPos, isLHS) { + let end = exprList.length; + + if (end) { + const last = exprList[end - 1]; + + if ((last == null ? void 0 : last.type) === "RestElement") { + --end; + } else if ((last == null ? void 0 : last.type) === "SpreadElement") { + last.type = "RestElement"; + let arg = last.argument; + this.toAssignable(arg, isLHS); + arg = unwrapParenthesizedExpression(arg); + + if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") { + this.unexpected(arg.start); + } + + if (trailingCommaPos) { + this.raiseTrailingCommaAfterRest(trailingCommaPos); + } + + --end; + } + } + + for (let i = 0; i < end; i++) { + const elt = exprList[i]; + + if (elt) { + this.toAssignable(elt, isLHS); + + if (elt.type === "RestElement") { + this.raiseRestNotLast(elt.start); + } + } + } + + return exprList; + } + + isAssignable(node, isBinding) { + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + return true; + + case "ObjectExpression": + { + const last = node.properties.length - 1; + return node.properties.every((prop, i) => { + return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop); + }); + } + + case "ObjectProperty": + return this.isAssignable(node.value); + + case "SpreadElement": + return this.isAssignable(node.argument); + + case "ArrayExpression": + return node.elements.every(element => element === null || this.isAssignable(element)); + + case "AssignmentExpression": + return node.operator === "="; + + case "ParenthesizedExpression": + return this.isAssignable(node.expression); + + case "MemberExpression": + case "OptionalMemberExpression": + return !isBinding; + + default: + return false; + } + } + + toReferencedList(exprList, isParenthesizedExpr) { + return exprList; + } + + toReferencedListDeep(exprList, isParenthesizedExpr) { + this.toReferencedList(exprList, isParenthesizedExpr); + + for (const expr of exprList) { + if ((expr == null ? void 0 : expr.type) === "ArrayExpression") { + this.toReferencedListDeep(expr.elements); + } + } + } + + parseSpread(refExpressionErrors, refNeedsArrowPos) { + const node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos); + return this.finishNode(node, "SpreadElement"); + } + + parseRestBinding() { + const node = this.startNode(); + this.next(); + node.argument = this.parseBindingAtom(); + return this.finishNode(node, "RestElement"); + } + + parseBindingAtom() { + switch (this.state.type) { + case types$1.bracketL: + { + const node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types$1.bracketR, 93, true); + return this.finishNode(node, "ArrayPattern"); + } + + case types$1.braceL: + return this.parseObjectLike(types$1.braceR, true); + } + + return this.parseIdentifier(); + } + + parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) { + const elts = []; + let first = true; + + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(types$1.comma); + } + + if (allowEmpty && this.match(types$1.comma)) { + elts.push(null); + } else if (this.eat(close)) { + break; + } else if (this.match(types$1.ellipsis)) { + elts.push(this.parseAssignableListItemTypes(this.parseRestBinding())); + this.checkCommaAfterRest(closeCharCode); + this.expect(close); + break; + } else { + const decorators = []; + + if (this.match(types$1.at) && this.hasPlugin("decorators")) { + this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator); + } + + while (this.match(types$1.at)) { + decorators.push(this.parseDecorator()); + } + + elts.push(this.parseAssignableListItem(allowModifiers, decorators)); + } + } + + return elts; + } + + parseAssignableListItem(allowModifiers, decorators) { + const left = this.parseMaybeDefault(); + this.parseAssignableListItemTypes(left); + const elt = this.parseMaybeDefault(left.start, left.loc.start, left); + + if (decorators.length) { + left.decorators = decorators; + } + + return elt; + } + + parseAssignableListItemTypes(param) { + return param; + } + + parseMaybeDefault(startPos, startLoc, left) { + var _startLoc, _startPos, _left; + + startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc; + startPos = (_startPos = startPos) != null ? _startPos : this.state.start; + left = (_left = left) != null ? _left : this.parseBindingAtom(); + if (!this.eat(types$1.eq)) return left; + const node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssignAllowIn(); + return this.finishNode(node, "AssignmentPattern"); + } + + checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) { + switch (expr.type) { + case "Identifier": + { + const { + name + } = expr; + + if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) { + this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name); + } + + if (checkClashes) { + if (checkClashes.has(name)) { + this.raise(expr.start, ErrorMessages.ParamDupe); + } else { + checkClashes.add(name); + } + } + + if (disallowLetBinding && name === "let") { + this.raise(expr.start, ErrorMessages.LetInLexicalBinding); + } + + if (!(bindingType & BIND_NONE)) { + this.scope.declareName(name, bindingType, expr.start); + } + + break; + } + + case "MemberExpression": + if (bindingType !== BIND_NONE) { + this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern); + } + + break; + + case "ObjectPattern": + for (let prop of expr.properties) { + if (this.isObjectProperty(prop)) prop = prop.value;else if (this.isObjectMethod(prop)) continue; + this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding); + } + + break; + + case "ArrayPattern": + for (const elem of expr.elements) { + if (elem) { + this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding); + } + } + + break; + + case "AssignmentPattern": + this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes); + break; + + case "RestElement": + this.checkLVal(expr.argument, "rest element", bindingType, checkClashes); + break; + + case "ParenthesizedExpression": + this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes); + break; + + default: + { + this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription); + } + } + } + + checkToRestConversion(node) { + if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") { + this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern); + } + } + + checkCommaAfterRest(close) { + if (this.match(types$1.comma)) { + if (this.lookaheadCharCode() === close) { + this.raiseTrailingCommaAfterRest(this.state.start); + } else { + this.raiseRestNotLast(this.state.start); + } + } + } + + raiseRestNotLast(pos) { + throw this.raise(pos, ErrorMessages.ElementAfterRest); + } + + raiseTrailingCommaAfterRest(pos) { + this.raise(pos, ErrorMessages.RestTrailingComma); + } + +} + +class ExpressionParser extends LValParser { + checkProto(prop, isRecord, protoRef, refExpressionErrors) { + if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) { + return; + } + + const key = prop.key; + const name = key.type === "Identifier" ? key.name : key.value; + + if (name === "__proto__") { + if (isRecord) { + this.raise(key.start, ErrorMessages.RecordNoProto); + return; + } + + if (protoRef.used) { + if (refExpressionErrors) { + if (refExpressionErrors.doubleProto === -1) { + refExpressionErrors.doubleProto = key.start; + } + } else { + this.raise(key.start, ErrorMessages.DuplicateProto); + } + } + + protoRef.used = true; + } + } + + shouldExitDescending(expr, potentialArrowAt) { + return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt; + } + + getExpression() { + this.enterInitialScopes(); + this.nextToken(); + const expr = this.parseExpression(); + + if (!this.match(types$1.eof)) { + this.unexpected(); + } + + this.finalizeRemainingComments(); + expr.comments = this.state.comments; + expr.errors = this.state.errors; + + if (this.options.tokens) { + expr.tokens = this.tokens; + } + + return expr; + } + + parseExpression(disallowIn, refExpressionErrors) { + if (disallowIn) { + return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors)); + } + + return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors)); + } + + parseExpressionBase(refExpressionErrors) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + const expr = this.parseMaybeAssign(refExpressionErrors); + + if (this.match(types$1.comma)) { + const node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + + while (this.eat(types$1.comma)) { + node.expressions.push(this.parseMaybeAssign(refExpressionErrors)); + } + + this.toReferencedList(node.expressions); + return this.finishNode(node, "SequenceExpression"); + } + + return expr; + } + + parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) { + return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); + } + + parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) { + return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); + } + + setOptionalParametersError(refExpressionErrors, resultError) { + var _resultError$pos; + + refExpressionErrors.optionalParameters = (_resultError$pos = resultError == null ? void 0 : resultError.pos) != null ? _resultError$pos : this.state.start; + } + + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + + if (this.isContextual("yield")) { + if (this.prodParam.hasYield) { + let left = this.parseYield(); + + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startPos, startLoc); + } + + return left; + } + } + + let ownExpressionErrors; + + if (refExpressionErrors) { + ownExpressionErrors = false; + } else { + refExpressionErrors = new ExpressionErrors(); + ownExpressionErrors = true; + } + + if (this.match(types$1.parenL) || this.match(types$1.name)) { + this.state.potentialArrowAt = this.state.start; + } + + let left = this.parseMaybeConditional(refExpressionErrors); + + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startPos, startLoc); + } + + if (this.state.type.isAssign) { + const node = this.startNodeAt(startPos, startLoc); + const operator = this.state.value; + node.operator = operator; + const leftIsHackPipeExpression = left.type === "BinaryExpression" && left.operator === "|>" && this.getPluginOption("pipelineOperator", "proposal") === "hack"; + + if (leftIsHackPipeExpression) { + throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, operator); + } + + if (this.match(types$1.eq)) { + node.left = this.toAssignable(left, true); + refExpressionErrors.doubleProto = -1; + } else { + node.left = left; + } + + if (refExpressionErrors.shorthandAssign >= node.left.start) { + refExpressionErrors.shorthandAssign = -1; + } + + this.checkLVal(left, "assignment expression"); + this.next(); + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentExpression"); + } else if (ownExpressionErrors) { + this.checkExpressionErrors(refExpressionErrors, true); + } + + return left; + } + + parseMaybeConditional(refExpressionErrors) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseExprOps(refExpressionErrors); + + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + + return this.parseConditional(expr, startPos, startLoc, refExpressionErrors); + } + + parseConditional(expr, startPos, startLoc, refExpressionErrors) { + if (this.eat(types$1.question)) { + const node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssignAllowIn(); + this.expect(types$1.colon); + node.alternate = this.parseMaybeAssign(); + return this.finishNode(node, "ConditionalExpression"); + } + + return expr; + } + + parseExprOps(refExpressionErrors) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseMaybeUnary(refExpressionErrors); + + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + + return this.parseExprOp(expr, startPos, startLoc, -1); + } + + parseExprOp(left, leftStartPos, leftStartLoc, minPrec) { + let prec = this.state.type.binop; + + if (prec != null && (this.prodParam.hasIn || !this.match(types$1._in))) { + if (prec > minPrec) { + const op = this.state.type; + + if (op === types$1.pipeline) { + this.expectPlugin("pipelineOperator"); + + if (this.state.inFSharpPipelineDirectBody) { + return left; + } + + this.checkPipelineAtInfixOperator(left, leftStartPos); + } + + const node = this.startNodeAt(leftStartPos, leftStartLoc); + node.left = left; + node.operator = this.state.value; + const logical = op === types$1.logicalOR || op === types$1.logicalAND; + const coalesce = op === types$1.nullishCoalescing; + + if (coalesce) { + prec = types$1.logicalAND.binop; + } + + this.next(); + + if (op === types$1.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") { + if (this.match(types$1.name) && this.state.value === "await" && this.prodParam.hasAwait) { + throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody); + } + } + + node.right = this.parseExprOpRightExpr(op, prec); + this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression"); + const nextOp = this.state.type; + + if (coalesce && (nextOp === types$1.logicalOR || nextOp === types$1.logicalAND) || logical && nextOp === types$1.nullishCoalescing) { + throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical); + } + + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec); + } + } + + return left; + } + + parseExprOpRightExpr(op, prec) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + + switch (op) { + case types$1.pipeline: + switch (this.getPluginOption("pipelineOperator", "proposal")) { + case "hack": + return this.withTopicBindingContext(() => { + const bodyExpr = this.parseHackPipeBody(op, prec); + this.checkHackPipeBodyEarlyErrors(startPos); + return bodyExpr; + }); + + case "smart": + return this.withTopicBindingContext(() => { + const childExpr = this.parseHackPipeBody(op, prec); + return this.parseSmartPipelineBodyInStyle(childExpr, startPos, startLoc); + }); + + case "fsharp": + return this.withSoloAwaitPermittingContext(() => { + return this.parseFSharpPipelineBody(prec); + }); + } + + default: + return this.parseExprOpBaseRightExpr(op, prec); + } + } + + parseExprOpBaseRightExpr(op, prec) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec); + } + + parseHackPipeBody(op, prec) { + const bodyIsInGeneratorContext = this.prodParam.hasYield; + const bodyIsYieldExpression = bodyIsInGeneratorContext && this.isContextual("yield"); + + if (bodyIsYieldExpression) { + throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, this.state.value); + } else { + return this.parseExprOpBaseRightExpr(op, prec); + } + } + + checkExponentialAfterUnary(node) { + if (this.match(types$1.exponent)) { + this.raise(node.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation); + } + } + + parseMaybeUnary(refExpressionErrors, sawUnary) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + const isAwait = this.isContextual("await"); + + if (isAwait && this.isAwaitAllowed()) { + this.next(); + const expr = this.parseAwait(startPos, startLoc); + if (!sawUnary) this.checkExponentialAfterUnary(expr); + return expr; + } + + const update = this.match(types$1.incDec); + const node = this.startNode(); + + if (this.state.type.prefix) { + node.operator = this.state.value; + node.prefix = true; + + if (this.match(types$1._throw)) { + this.expectPlugin("throwExpressions"); + } + + const isDelete = this.match(types$1._delete); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + this.checkExpressionErrors(refExpressionErrors, true); + + if (this.state.strict && isDelete) { + const arg = node.argument; + + if (arg.type === "Identifier") { + this.raise(node.start, ErrorMessages.StrictDelete); + } else if (this.hasPropertyAsPrivateName(arg)) { + this.raise(node.start, ErrorMessages.DeletePrivateField); + } + } + + if (!update) { + if (!sawUnary) this.checkExponentialAfterUnary(node); + return this.finishNode(node, "UnaryExpression"); + } + } + + const expr = this.parseUpdate(node, update, refExpressionErrors); + + if (isAwait) { + const startsExpr = this.hasPlugin("v8intrinsic") ? this.state.type.startsExpr : this.state.type.startsExpr && !this.match(types$1.modulo); + + if (startsExpr && !this.isAmbiguousAwait()) { + this.raiseOverwrite(startPos, ErrorMessages.AwaitNotInAsyncContext); + return this.parseAwait(startPos, startLoc); + } + } + + return expr; + } + + parseUpdate(node, update, refExpressionErrors) { + if (update) { + this.checkLVal(node.argument, "prefix operation"); + return this.finishNode(node, "UpdateExpression"); + } + + const startPos = this.state.start; + const startLoc = this.state.startLoc; + let expr = this.parseExprSubscripts(refExpressionErrors); + if (this.checkExpressionErrors(refExpressionErrors, false)) return expr; + + while (this.state.type.postfix && !this.canInsertSemicolon()) { + const node = this.startNodeAt(startPos, startLoc); + node.operator = this.state.value; + node.prefix = false; + node.argument = expr; + this.checkLVal(expr, "postfix operation"); + this.next(); + expr = this.finishNode(node, "UpdateExpression"); + } + + return expr; + } + + parseExprSubscripts(refExpressionErrors) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseExprAtom(refExpressionErrors); + + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + + return this.parseSubscripts(expr, startPos, startLoc); + } + + parseSubscripts(base, startPos, startLoc, noCalls) { + const state = { + optionalChainMember: false, + maybeAsyncArrow: this.atPossibleAsyncArrow(base), + stop: false + }; + + do { + base = this.parseSubscript(base, startPos, startLoc, noCalls, state); + state.maybeAsyncArrow = false; + } while (!state.stop); + + return base; + } + + parseSubscript(base, startPos, startLoc, noCalls, state) { + if (!noCalls && this.eat(types$1.doubleColon)) { + return this.parseBind(base, startPos, startLoc, noCalls, state); + } else if (this.match(types$1.backQuote)) { + return this.parseTaggedTemplateExpression(base, startPos, startLoc, state); + } + + let optional = false; + + if (this.match(types$1.questionDot)) { + if (noCalls && this.lookaheadCharCode() === 40) { + state.stop = true; + return base; + } + + state.optionalChainMember = optional = true; + this.next(); + } + + if (!noCalls && this.match(types$1.parenL)) { + return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional); + } else { + const computed = this.eat(types$1.bracketL); + + if (computed || optional || this.eat(types$1.dot)) { + return this.parseMember(base, startPos, startLoc, state, computed, optional); + } else { + state.stop = true; + return base; + } + } + } + + parseMember(base, startPos, startLoc, state, computed, optional) { + const node = this.startNodeAt(startPos, startLoc); + node.object = base; + node.computed = computed; + const privateName = !computed && this.match(types$1.privateName) && this.state.value; + const property = computed ? this.parseExpression() : privateName ? this.parsePrivateName() : this.parseIdentifier(true); + + if (privateName !== false) { + if (node.object.type === "Super") { + this.raise(startPos, ErrorMessages.SuperPrivateField); + } + + this.classScope.usePrivateName(privateName, property.start); + } + + node.property = property; + + if (computed) { + this.expect(types$1.bracketR); + } + + if (state.optionalChainMember) { + node.optional = optional; + return this.finishNode(node, "OptionalMemberExpression"); + } else { + return this.finishNode(node, "MemberExpression"); + } + } + + parseBind(base, startPos, startLoc, noCalls, state) { + const node = this.startNodeAt(startPos, startLoc); + node.object = base; + node.callee = this.parseNoCallExpr(); + state.stop = true; + return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls); + } + + parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) { + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + let refExpressionErrors = null; + this.state.maybeInArrowParameters = true; + this.next(); + let node = this.startNodeAt(startPos, startLoc); + node.callee = base; + + if (state.maybeAsyncArrow) { + this.expressionScope.enter(newAsyncArrowScope()); + refExpressionErrors = new ExpressionErrors(); + } + + if (state.optionalChainMember) { + node.optional = optional; + } + + if (optional) { + node.arguments = this.parseCallExpressionArguments(types$1.parenR); + } else { + node.arguments = this.parseCallExpressionArguments(types$1.parenR, base.type === "Import", base.type !== "Super", node, refExpressionErrors); + } + + this.finishCallExpression(node, state.optionalChainMember); + + if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) { + state.stop = true; + this.expressionScope.validateAsPattern(); + this.expressionScope.exit(); + node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node); + } else { + if (state.maybeAsyncArrow) { + this.checkExpressionErrors(refExpressionErrors, true); + this.expressionScope.exit(); + } + + this.toReferencedArguments(node); + } + + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return node; + } + + toReferencedArguments(node, isParenthesizedExpr) { + this.toReferencedListDeep(node.arguments, isParenthesizedExpr); + } + + parseTaggedTemplateExpression(base, startPos, startLoc, state) { + const node = this.startNodeAt(startPos, startLoc); + node.tag = base; + node.quasi = this.parseTemplate(true); + + if (state.optionalChainMember) { + this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate); + } + + return this.finishNode(node, "TaggedTemplateExpression"); + } + + atPossibleAsyncArrow(base) { + return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt; + } + + finishCallExpression(node, optional) { + if (node.callee.type === "Import") { + if (node.arguments.length === 2) { + { + if (!this.hasPlugin("moduleAttributes")) { + this.expectPlugin("importAssertions"); + } + } + } + + if (node.arguments.length === 0 || node.arguments.length > 2) { + this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument"); + } else { + for (const arg of node.arguments) { + if (arg.type === "SpreadElement") { + this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument); + } + } + } + } + + return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression"); + } + + parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) { + const elts = []; + let first = true; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(types$1.comma); + + if (this.match(close)) { + if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) { + this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma); + } + + if (nodeForExtra) { + this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart); + } + + this.next(); + break; + } + } + + elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder)); + } + + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return elts; + } + + shouldParseAsyncArrow() { + return this.match(types$1.arrow) && !this.canInsertSemicolon(); + } + + parseAsyncArrowFromCallExpression(node, call) { + var _call$extra; + + this.resetPreviousNodeTrailingComments(call); + this.expect(types$1.arrow); + this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma); + setInnerComments(node, call.innerComments); + setInnerComments(node, call.callee.trailingComments); + return node; + } + + parseNoCallExpr() { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); + } + + parseExprAtom(refExpressionErrors) { + let node; + + switch (this.state.type) { + case types$1._super: + return this.parseSuper(); + + case types$1._import: + node = this.startNode(); + this.next(); + + if (this.match(types$1.dot)) { + return this.parseImportMetaProperty(node); + } + + if (!this.match(types$1.parenL)) { + this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport); + } + + return this.finishNode(node, "Import"); + + case types$1._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression"); + + case types$1.name: + { + if (this.isContextual("module") && this.lookaheadCharCode() === 123 && !this.hasFollowingLineBreak()) { + return this.parseModuleExpression(); + } + + const canBeArrow = this.state.potentialArrowAt === this.state.start; + const containsEsc = this.state.containsEsc; + const id = this.parseIdentifier(); + + if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) { + if (this.match(types$1._function)) { + this.resetPreviousNodeTrailingComments(id); + this.next(); + return this.parseFunction(this.startNodeAtNode(id), undefined, true); + } else if (this.match(types$1.name)) { + if (this.lookaheadCharCode() === 61) { + return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id)); + } else { + return id; + } + } else if (this.match(types$1._do)) { + this.resetPreviousNodeTrailingComments(id); + return this.parseDo(this.startNodeAtNode(id), true); + } + } + + if (canBeArrow && this.match(types$1.arrow) && !this.canInsertSemicolon()) { + this.next(); + return this.parseArrowExpression(this.startNodeAtNode(id), [id], false); + } + + return id; + } + + case types$1._do: + { + return this.parseDo(this.startNode(), false); + } + + case types$1.slash: + case types$1.slashAssign: + { + this.readRegexp(); + return this.parseRegExpLiteral(this.state.value); + } + + case types$1.num: + return this.parseNumericLiteral(this.state.value); + + case types$1.bigint: + return this.parseBigIntLiteral(this.state.value); + + case types$1.decimal: + return this.parseDecimalLiteral(this.state.value); + + case types$1.string: + return this.parseStringLiteral(this.state.value); + + case types$1._null: + return this.parseNullLiteral(); + + case types$1._true: + return this.parseBooleanLiteral(true); + + case types$1._false: + return this.parseBooleanLiteral(false); + + case types$1.parenL: + { + const canBeArrow = this.state.potentialArrowAt === this.state.start; + return this.parseParenAndDistinguishExpression(canBeArrow); + } + + case types$1.bracketBarL: + case types$1.bracketHashL: + { + return this.parseArrayLike(this.state.type === types$1.bracketBarL ? types$1.bracketBarR : types$1.bracketR, false, true, refExpressionErrors); + } + + case types$1.bracketL: + { + return this.parseArrayLike(types$1.bracketR, true, false, refExpressionErrors); + } + + case types$1.braceBarL: + case types$1.braceHashL: + { + return this.parseObjectLike(this.state.type === types$1.braceBarL ? types$1.braceBarR : types$1.braceR, false, true, refExpressionErrors); + } + + case types$1.braceL: + { + return this.parseObjectLike(types$1.braceR, false, false, refExpressionErrors); + } + + case types$1._function: + return this.parseFunctionOrFunctionSent(); + + case types$1.at: + this.parseDecorators(); + + case types$1._class: + node = this.startNode(); + this.takeDecorators(node); + return this.parseClass(node, false); + + case types$1._new: + return this.parseNewOrNewTarget(); + + case types$1.backQuote: + return this.parseTemplate(false); + + case types$1.doubleColon: + { + node = this.startNode(); + this.next(); + node.object = null; + const callee = node.callee = this.parseNoCallExpr(); + + if (callee.type === "MemberExpression") { + return this.finishNode(node, "BindExpression"); + } else { + throw this.raise(callee.start, ErrorMessages.UnsupportedBind); + } + } + + case types$1.privateName: + { + const { + value, + start + } = this.state; + node = this.parsePrivateName(); + + if (this.match(types$1._in)) { + this.classScope.usePrivateName(value, start); + } else { + this.raise(start, ErrorMessages.PrivateInExpectedIn, value); + } + + return node; + } + + case types$1.moduloAssign: + if (this.getPluginOption("pipelineOperator", "proposal") === "hack" && this.getPluginOption("pipelineOperator", "topicToken") === "%") { + this.state.value = "%"; + this.state.type = types$1.modulo; + this.state.pos--; + this.state.end--; + this.state.endLoc.column--; + } else { + throw this.unexpected(); + } + + case types$1.modulo: + case types$1.hash: + { + const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); + + if (pipeProposal) { + node = this.startNode(); + const start = this.state.start; + const tokenType = this.state.type; + this.next(); + return this.finishTopicReference(node, start, pipeProposal, tokenType); + } + } + + case types$1.relational: + { + if (this.state.value === "<") { + const lookaheadCh = this.input.codePointAt(this.nextTokenStart()); + + if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) { + this.expectOnePlugin(["jsx", "flow", "typescript"]); + } + } + } + + default: + throw this.unexpected(); + } + } + + finishTopicReference(node, start, pipeProposal, tokenType) { + if (this.testTopicReferenceConfiguration(pipeProposal, start, tokenType)) { + let nodeType; + + if (pipeProposal === "smart") { + nodeType = "PipelinePrimaryTopicReference"; + } else { + nodeType = "TopicReference"; + } + + if (!this.topicReferenceIsAllowedInCurrentContext()) { + if (pipeProposal === "smart") { + this.raise(start, ErrorMessages.PrimaryTopicNotAllowed); + } else { + this.raise(start, ErrorMessages.PipeTopicUnbound); + } + } + + this.registerTopicReference(); + return this.finishNode(node, nodeType); + } else { + throw this.raise(start, ErrorMessages.PipeTopicUnconfiguredToken, tokenType.label); + } + } + + testTopicReferenceConfiguration(pipeProposal, start, tokenType) { + switch (pipeProposal) { + case "hack": + { + const pluginTopicToken = this.getPluginOption("pipelineOperator", "topicToken"); + return tokenType.label === pluginTopicToken; + } + + case "smart": + return tokenType === types$1.hash; + + default: + throw this.raise(start, ErrorMessages.PipeTopicRequiresHackPipes); + } + } + + parseAsyncArrowUnaryFunction(node) { + this.prodParam.enter(functionFlags(true, this.prodParam.hasYield)); + const params = [this.parseIdentifier()]; + this.prodParam.exit(); + + if (this.hasPrecedingLineBreak()) { + this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow); + } + + this.expect(types$1.arrow); + this.parseArrowExpression(node, params, true); + return node; + } + + parseDo(node, isAsync) { + this.expectPlugin("doExpressions"); + + if (isAsync) { + this.expectPlugin("asyncDoExpressions"); + } + + node.async = isAsync; + this.next(); + const oldLabels = this.state.labels; + this.state.labels = []; + + if (isAsync) { + this.prodParam.enter(PARAM_AWAIT); + node.body = this.parseBlock(); + this.prodParam.exit(); + } else { + node.body = this.parseBlock(); + } + + this.state.labels = oldLabels; + return this.finishNode(node, "DoExpression"); + } + + parseSuper() { + const node = this.startNode(); + this.next(); + + if (this.match(types$1.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) { + this.raise(node.start, ErrorMessages.SuperNotAllowed); + } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) { + this.raise(node.start, ErrorMessages.UnexpectedSuper); + } + + if (!this.match(types$1.parenL) && !this.match(types$1.bracketL) && !this.match(types$1.dot)) { + this.raise(node.start, ErrorMessages.UnsupportedSuper); + } + + return this.finishNode(node, "Super"); + } + + parseMaybePrivateName(isPrivateNameAllowed) { + const isPrivate = this.match(types$1.privateName); + + if (isPrivate) { + if (!isPrivateNameAllowed) { + this.raise(this.state.start + 1, ErrorMessages.UnexpectedPrivateField); + } + + return this.parsePrivateName(); + } else { + return this.parseIdentifier(true); + } + } + + parsePrivateName() { + const node = this.startNode(); + const id = this.startNodeAt(this.state.start + 1, new Position(this.state.curLine, this.state.start + 1 - this.state.lineStart)); + const name = this.state.value; + this.next(); + node.id = this.createIdentifier(id, name); + return this.finishNode(node, "PrivateName"); + } + + parseFunctionOrFunctionSent() { + const node = this.startNode(); + this.next(); + + if (this.prodParam.hasYield && this.match(types$1.dot)) { + const meta = this.createIdentifier(this.startNodeAtNode(node), "function"); + this.next(); + return this.parseMetaProperty(node, meta, "sent"); + } + + return this.parseFunction(node); + } + + parseMetaProperty(node, meta, propertyName) { + node.meta = meta; + + if (meta.name === "function" && propertyName === "sent") { + if (this.isContextual(propertyName)) { + this.expectPlugin("functionSent"); + } else if (!this.hasPlugin("functionSent")) { + this.unexpected(); + } + } + + const containsEsc = this.state.containsEsc; + node.property = this.parseIdentifier(true); + + if (node.property.name !== propertyName || containsEsc) { + this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName); + } + + return this.finishNode(node, "MetaProperty"); + } + + parseImportMetaProperty(node) { + const id = this.createIdentifier(this.startNodeAtNode(node), "import"); + this.next(); + + if (this.isContextual("meta")) { + if (!this.inModule) { + this.raise(id.start, SourceTypeModuleErrorMessages.ImportMetaOutsideModule); + } + + this.sawUnambiguousESM = true; + } + + return this.parseMetaProperty(node, id, "meta"); + } + + parseLiteralAtNode(value, type, node) { + this.addExtra(node, "rawValue", value); + this.addExtra(node, "raw", this.input.slice(node.start, this.state.end)); + node.value = value; + this.next(); + return this.finishNode(node, type); + } + + parseLiteral(value, type) { + const node = this.startNode(); + return this.parseLiteralAtNode(value, type, node); + } + + parseStringLiteral(value) { + return this.parseLiteral(value, "StringLiteral"); + } + + parseNumericLiteral(value) { + return this.parseLiteral(value, "NumericLiteral"); + } + + parseBigIntLiteral(value) { + return this.parseLiteral(value, "BigIntLiteral"); + } + + parseDecimalLiteral(value) { + return this.parseLiteral(value, "DecimalLiteral"); + } + + parseRegExpLiteral(value) { + const node = this.parseLiteral(value.value, "RegExpLiteral"); + node.pattern = value.pattern; + node.flags = value.flags; + return node; + } + + parseBooleanLiteral(value) { + const node = this.startNode(); + node.value = value; + this.next(); + return this.finishNode(node, "BooleanLiteral"); + } + + parseNullLiteral() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "NullLiteral"); + } + + parseParenAndDistinguishExpression(canBeArrow) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + let val; + this.next(); + this.expressionScope.enter(newArrowHeadScope()); + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.maybeInArrowParameters = true; + this.state.inFSharpPipelineDirectBody = false; + const innerStartPos = this.state.start; + const innerStartLoc = this.state.startLoc; + const exprList = []; + const refExpressionErrors = new ExpressionErrors(); + let first = true; + let spreadStart; + let optionalCommaStart; + + while (!this.match(types$1.parenR)) { + if (first) { + first = false; + } else { + this.expect(types$1.comma, refExpressionErrors.optionalParameters === -1 ? null : refExpressionErrors.optionalParameters); + + if (this.match(types$1.parenR)) { + optionalCommaStart = this.state.start; + break; + } + } + + if (this.match(types$1.ellipsis)) { + const spreadNodeStartPos = this.state.start; + const spreadNodeStartLoc = this.state.startLoc; + spreadStart = this.state.start; + exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc)); + this.checkCommaAfterRest(41); + break; + } else { + exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem)); + } + } + + const innerEndPos = this.state.lastTokEnd; + const innerEndLoc = this.state.lastTokEndLoc; + this.expect(types$1.parenR); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + let arrowNode = this.startNodeAt(startPos, startLoc); + + if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) { + this.expressionScope.validateAsPattern(); + this.expressionScope.exit(); + this.parseArrowExpression(arrowNode, exprList, false); + return arrowNode; + } + + this.expressionScope.exit(); + + if (!exprList.length) { + this.unexpected(this.state.lastTokStart); + } + + if (optionalCommaStart) this.unexpected(optionalCommaStart); + if (spreadStart) this.unexpected(spreadStart); + this.checkExpressionErrors(refExpressionErrors, true); + this.toReferencedListDeep(exprList, true); + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNode(val, "SequenceExpression"); + val.end = innerEndPos; + val.loc.end = innerEndLoc; + } else { + val = exprList[0]; + } + + if (!this.options.createParenthesizedExpressions) { + this.addExtra(val, "parenthesized", true); + this.addExtra(val, "parenStart", startPos); + return val; + } + + const parenExpression = this.startNodeAt(startPos, startLoc); + parenExpression.expression = val; + this.finishNode(parenExpression, "ParenthesizedExpression"); + return parenExpression; + } + + shouldParseArrow(params) { + return !this.canInsertSemicolon(); + } + + parseArrow(node) { + if (this.eat(types$1.arrow)) { + return node; + } + } + + parseParenItem(node, startPos, startLoc) { + return node; + } + + parseNewOrNewTarget() { + const node = this.startNode(); + this.next(); + + if (this.match(types$1.dot)) { + const meta = this.createIdentifier(this.startNodeAtNode(node), "new"); + this.next(); + const metaProp = this.parseMetaProperty(node, meta, "target"); + + if (!this.scope.inNonArrowFunction && !this.scope.inClass) { + this.raise(metaProp.start, ErrorMessages.UnexpectedNewTarget); + } + + return metaProp; + } + + return this.parseNew(node); + } + + parseNew(node) { + node.callee = this.parseNoCallExpr(); + + if (node.callee.type === "Import") { + this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression); + } else if (this.isOptionalChain(node.callee)) { + this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew); + } else if (this.eat(types$1.questionDot)) { + this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew); + } + + this.parseNewArguments(node); + return this.finishNode(node, "NewExpression"); + } + + parseNewArguments(node) { + if (this.eat(types$1.parenL)) { + const args = this.parseExprList(types$1.parenR); + this.toReferencedList(args); + node.arguments = args; + } else { + node.arguments = []; + } + } + + parseTemplateElement(isTagged) { + const elem = this.startNode(); + + if (this.state.value === null) { + if (!isTagged) { + this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate); + } + } + + elem.value = { + raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"), + cooked: this.state.value + }; + this.next(); + elem.tail = this.match(types$1.backQuote); + return this.finishNode(elem, "TemplateElement"); + } + + parseTemplate(isTagged) { + const node = this.startNode(); + this.next(); + node.expressions = []; + let curElt = this.parseTemplateElement(isTagged); + node.quasis = [curElt]; + + while (!curElt.tail) { + this.expect(types$1.dollarBraceL); + node.expressions.push(this.parseTemplateSubstitution()); + this.expect(types$1.braceR); + node.quasis.push(curElt = this.parseTemplateElement(isTagged)); + } + + this.next(); + return this.finishNode(node, "TemplateLiteral"); + } + + parseTemplateSubstitution() { + return this.parseExpression(); + } + + parseObjectLike(close, isPattern, isRecord, refExpressionErrors) { + if (isRecord) { + this.expectPlugin("recordAndTuple"); + } + + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + const propHash = Object.create(null); + let first = true; + const node = this.startNode(); + node.properties = []; + this.next(); + + while (!this.match(close)) { + if (first) { + first = false; + } else { + this.expect(types$1.comma); + + if (this.match(close)) { + this.addExtra(node, "trailingComma", this.state.lastTokStart); + break; + } + } + + const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors); + + if (!isPattern) { + this.checkProto(prop, isRecord, propHash, refExpressionErrors); + } + + if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") { + this.raise(prop.start, ErrorMessages.InvalidRecordProperty); + } + + if (prop.shorthand) { + this.addExtra(prop, "shorthand", true); + } + + node.properties.push(prop); + } + + this.next(); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + let type = "ObjectExpression"; + + if (isPattern) { + type = "ObjectPattern"; + } else if (isRecord) { + type = "RecordExpression"; + } + + return this.finishNode(node, type); + } + + maybeAsyncOrAccessorProp(prop) { + return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(types$1.bracketL) || this.match(types$1.star)); + } + + parsePropertyDefinition(isPattern, refExpressionErrors) { + let decorators = []; + + if (this.match(types$1.at)) { + if (this.hasPlugin("decorators")) { + this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator); + } + + while (this.match(types$1.at)) { + decorators.push(this.parseDecorator()); + } + } + + const prop = this.startNode(); + let isGenerator = false; + let isAsync = false; + let isAccessor = false; + let startPos; + let startLoc; + + if (this.match(types$1.ellipsis)) { + if (decorators.length) this.unexpected(); + + if (isPattern) { + this.next(); + prop.argument = this.parseIdentifier(); + this.checkCommaAfterRest(125); + return this.finishNode(prop, "RestElement"); + } + + return this.parseSpread(); + } + + if (decorators.length) { + prop.decorators = decorators; + decorators = []; + } + + prop.method = false; + + if (isPattern || refExpressionErrors) { + startPos = this.state.start; + startLoc = this.state.startLoc; + } + + if (!isPattern) { + isGenerator = this.eat(types$1.star); + } + + const containsEsc = this.state.containsEsc; + const key = this.parsePropertyName(prop, false); + + if (!isPattern && !isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) { + const keyName = key.name; + + if (keyName === "async" && !this.hasPrecedingLineBreak()) { + isAsync = true; + this.resetPreviousNodeTrailingComments(key); + isGenerator = this.eat(types$1.star); + this.parsePropertyName(prop, false); + } + + if (keyName === "get" || keyName === "set") { + isAccessor = true; + this.resetPreviousNodeTrailingComments(key); + prop.kind = keyName; + + if (this.match(types$1.star)) { + isGenerator = true; + this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName); + this.next(); + } + + this.parsePropertyName(prop, false); + } + } + + this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); + return prop; + } + + getGetterSetterExpectedParamCount(method) { + return method.kind === "get" ? 0 : 1; + } + + getObjectOrClassMethodParams(method) { + return method.params; + } + + checkGetterSetterParams(method) { + var _params; + + const paramCount = this.getGetterSetterExpectedParamCount(method); + const params = this.getObjectOrClassMethodParams(method); + const start = method.start; + + if (params.length !== paramCount) { + if (method.kind === "get") { + this.raise(start, ErrorMessages.BadGetterArity); + } else { + this.raise(start, ErrorMessages.BadSetterArity); + } + } + + if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") { + this.raise(start, ErrorMessages.BadSetterRestParameter); + } + } + + parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { + if (isAccessor) { + this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod"); + this.checkGetterSetterParams(prop); + return prop; + } + + if (isAsync || isGenerator || this.match(types$1.parenL)) { + if (isPattern) this.unexpected(); + prop.kind = "method"; + prop.method = true; + return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod"); + } + } + + parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) { + prop.shorthand = false; + + if (this.eat(types$1.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors); + return this.finishNode(prop, "ObjectProperty"); + } + + if (!prop.computed && prop.key.type === "Identifier") { + this.checkReservedWord(prop.key.name, prop.key.start, true, false); + + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key)); + } else if (this.match(types$1.eq) && refExpressionErrors) { + if (refExpressionErrors.shorthandAssign === -1) { + refExpressionErrors.shorthandAssign = this.state.start; + } + + prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key)); + } else { + prop.value = cloneIdentifier(prop.key); + } + + prop.shorthand = true; + return this.finishNode(prop, "ObjectProperty"); + } + } + + parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors); + if (!node) this.unexpected(); + return node; + } + + parsePropertyName(prop, isPrivateNameAllowed) { + if (this.eat(types$1.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssignAllowIn(); + this.expect(types$1.bracketR); + } else { + const oldInPropertyName = this.state.inPropertyName; + this.state.inPropertyName = true; + const type = this.state.type; + prop.key = type === types$1.num || type === types$1.string || type === types$1.bigint || type === types$1.decimal ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed); + + if (type !== types$1.privateName) { + prop.computed = false; + } + + this.state.inPropertyName = oldInPropertyName; + } + + return prop.key; + } + + initFunction(node, isAsync) { + node.id = null; + node.generator = false; + node.async = !!isAsync; + } + + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { + this.initFunction(node, isAsync); + node.generator = !!isGenerator; + const allowModifiers = isConstructor; + this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + this.prodParam.enter(functionFlags(isAsync, node.generator)); + this.parseFunctionParams(node, allowModifiers); + this.parseFunctionBodyAndFinish(node, type, true); + this.prodParam.exit(); + this.scope.exit(); + return node; + } + + parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { + if (isTuple) { + this.expectPlugin("recordAndTuple"); + } + + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + const node = this.startNode(); + this.next(); + node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression"); + } + + parseArrowExpression(node, params, isAsync, trailingCommaPos) { + this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW); + let flags = functionFlags(isAsync, false); + + if (!this.match(types$1.bracketL) && this.prodParam.hasIn) { + flags |= PARAM_IN; + } + + this.prodParam.enter(flags); + this.initFunction(node, isAsync); + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + + if (params) { + this.state.maybeInArrowParameters = true; + this.setArrowFunctionParameters(node, params, trailingCommaPos); + } + + this.state.maybeInArrowParameters = false; + this.parseFunctionBody(node, true); + this.prodParam.exit(); + this.scope.exit(); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return this.finishNode(node, "ArrowFunctionExpression"); + } + + setArrowFunctionParameters(node, params, trailingCommaPos) { + node.params = this.toAssignableList(params, trailingCommaPos, false); + } + + parseFunctionBodyAndFinish(node, type, isMethod = false) { + this.parseFunctionBody(node, false, isMethod); + this.finishNode(node, type); + } + + parseFunctionBody(node, allowExpression, isMethod = false) { + const isExpression = allowExpression && !this.match(types$1.braceL); + this.expressionScope.enter(newExpressionScope()); + + if (isExpression) { + node.body = this.parseMaybeAssign(); + this.checkParams(node, false, allowExpression, false); + } else { + const oldStrict = this.state.strict; + const oldLabels = this.state.labels; + this.state.labels = []; + this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN); + node.body = this.parseBlock(true, false, hasStrictModeDirective => { + const nonSimple = !this.isSimpleParamList(node.params); + + if (hasStrictModeDirective && nonSimple) { + const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start; + this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective); + } + + const strictModeChanged = !oldStrict && this.state.strict; + this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged); + + if (this.state.strict && node.id) { + this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged); + } + }); + this.prodParam.exit(); + this.expressionScope.exit(); + this.state.labels = oldLabels; + } + } + + isSimpleParamList(params) { + for (let i = 0, len = params.length; i < len; i++) { + if (params[i].type !== "Identifier") return false; + } + + return true; + } + + checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { + const checkClashes = new Set(); + + for (const param of node.params) { + this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged); + } + } + + parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) { + const elts = []; + let first = true; + + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(types$1.comma); + + if (this.match(close)) { + if (nodeForExtra) { + this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart); + } + + this.next(); + break; + } + } + + elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors)); + } + + return elts; + } + + parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) { + let elt; + + if (this.match(types$1.comma)) { + if (!allowEmpty) { + this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ","); + } + + elt = null; + } else if (this.match(types$1.ellipsis)) { + const spreadNodeStartPos = this.state.start; + const spreadNodeStartLoc = this.state.startLoc; + elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartPos, spreadNodeStartLoc); + } else if (this.match(types$1.question)) { + this.expectPlugin("partialApplication"); + + if (!allowPlaceholder) { + this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder); + } + + const node = this.startNode(); + this.next(); + elt = this.finishNode(node, "ArgumentPlaceholder"); + } else { + elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem); + } + + return elt; + } + + parseIdentifier(liberal) { + const node = this.startNode(); + const name = this.parseIdentifierName(node.start, liberal); + return this.createIdentifier(node, name); + } + + createIdentifier(node, name) { + node.name = name; + node.loc.identifierName = name; + return this.finishNode(node, "Identifier"); + } + + parseIdentifierName(pos, liberal) { + let name; + const { + start, + type + } = this.state; + + if (type === types$1.name) { + name = this.state.value; + } else if (type.keyword) { + name = type.keyword; + } else { + throw this.unexpected(); + } + + if (liberal) { + this.state.type = types$1.name; + } else { + this.checkReservedWord(name, start, !!type.keyword, false); + } + + this.next(); + return name; + } + + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (word.length > 10) { + return; + } + + if (!canBeReservedWord(word)) { + return; + } + + if (word === "yield") { + if (this.prodParam.hasYield) { + this.raise(startLoc, ErrorMessages.YieldBindingIdentifier); + return; + } + } else if (word === "await") { + if (this.prodParam.hasAwait) { + this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier); + return; + } else if (this.scope.inStaticBlock) { + this.raise(startLoc, ErrorMessages.AwaitBindingIdentifierInStaticBlock); + return; + } else { + this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier); + } + } else if (word === "arguments") { + if (this.scope.inClassAndNotInNonArrowFunction) { + this.raise(startLoc, ErrorMessages.ArgumentsInClass); + return; + } + } + + if (checkKeywords && isKeyword(word)) { + this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word); + return; + } + + const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; + + if (reservedTest(word, this.inModule)) { + this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word); + } + } + + isAwaitAllowed() { + if (this.prodParam.hasAwait) return true; + + if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) { + return true; + } + + return false; + } + + parseAwait(startPos, startLoc) { + const node = this.startNodeAt(startPos, startLoc); + this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter); + + if (this.eat(types$1.star)) { + this.raise(node.start, ErrorMessages.ObsoleteAwaitStar); + } + + if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) { + if (this.isAmbiguousAwait()) { + this.ambiguousScriptDifferentAst = true; + } else { + this.sawUnambiguousESM = true; + } + } + + if (!this.state.soloAwait) { + node.argument = this.parseMaybeUnary(null, true); + } + + return this.finishNode(node, "AwaitExpression"); + } + + isAmbiguousAwait() { + return this.hasPrecedingLineBreak() || this.match(types$1.plusMin) || this.match(types$1.parenL) || this.match(types$1.bracketL) || this.match(types$1.backQuote) || this.match(types$1.regexp) || this.match(types$1.slash) || this.hasPlugin("v8intrinsic") && this.match(types$1.modulo); + } + + parseYield() { + const node = this.startNode(); + this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter); + this.next(); + let delegating = false; + let argument = null; + + if (!this.hasPrecedingLineBreak()) { + delegating = this.eat(types$1.star); + + switch (this.state.type) { + case types$1.semi: + case types$1.eof: + case types$1.braceR: + case types$1.parenR: + case types$1.bracketR: + case types$1.braceBarR: + case types$1.colon: + case types$1.comma: + if (!delegating) break; + + default: + argument = this.parseMaybeAssign(); + } + } + + node.delegate = delegating; + node.argument = argument; + return this.finishNode(node, "YieldExpression"); + } + + checkPipelineAtInfixOperator(left, leftStartPos) { + if (this.getPluginOption("pipelineOperator", "proposal") === "smart") { + if (left.type === "SequenceExpression") { + this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression); + } + } + } + + checkHackPipeBodyEarlyErrors(startPos) { + if (this.match(types$1.arrow)) { + throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, types$1.arrow.label); + } else if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(startPos, ErrorMessages.PipeTopicUnused); + } + } + + parseSmartPipelineBodyInStyle(childExpr, startPos, startLoc) { + const bodyNode = this.startNodeAt(startPos, startLoc); + + if (this.isSimpleReference(childExpr)) { + bodyNode.callee = childExpr; + return this.finishNode(bodyNode, "PipelineBareFunction"); + } else { + this.checkSmartPipeTopicBodyEarlyErrors(startPos); + bodyNode.expression = childExpr; + return this.finishNode(bodyNode, "PipelineTopicExpression"); + } + } + + isSimpleReference(expression) { + switch (expression.type) { + case "MemberExpression": + return !expression.computed && this.isSimpleReference(expression.object); + + case "Identifier": + return true; + + default: + return false; + } + } + + checkSmartPipeTopicBodyEarlyErrors(startPos) { + if (this.match(types$1.arrow)) { + throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow); + } else if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(startPos, ErrorMessages.PipelineTopicUnused); + } + } + + withTopicBindingContext(callback) { + const outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 1, + maxTopicIndex: null + }; + + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } + + withSmartMixTopicForbiddingContext(callback) { + const proposal = this.getPluginOption("pipelineOperator", "proposal"); + + if (proposal === "smart") { + const outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } else { + return callback(); + } + } + + withSoloAwaitPermittingContext(callback) { + const outerContextSoloAwaitState = this.state.soloAwait; + this.state.soloAwait = true; + + try { + return callback(); + } finally { + this.state.soloAwait = outerContextSoloAwaitState; + } + } + + allowInAnd(callback) { + const flags = this.prodParam.currentFlags(); + const prodParamToSet = PARAM_IN & ~flags; + + if (prodParamToSet) { + this.prodParam.enter(flags | PARAM_IN); + + try { + return callback(); + } finally { + this.prodParam.exit(); + } + } + + return callback(); + } + + disallowInAnd(callback) { + const flags = this.prodParam.currentFlags(); + const prodParamToClear = PARAM_IN & flags; + + if (prodParamToClear) { + this.prodParam.enter(flags & ~PARAM_IN); + + try { + return callback(); + } finally { + this.prodParam.exit(); + } + } + + return callback(); + } + + registerTopicReference() { + this.state.topicContext.maxTopicIndex = 0; + } + + topicReferenceIsAllowedInCurrentContext() { + return this.state.topicContext.maxNumOfResolvableTopics >= 1; + } + + topicReferenceWasUsedInCurrentContext() { + return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0; + } + + parseFSharpPipelineBody(prec) { + const startPos = this.state.start; + const startLoc = this.state.startLoc; + this.state.potentialArrowAt = this.state.start; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = true; + const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return ret; + } + + parseModuleExpression() { + this.expectPlugin("moduleBlocks"); + const node = this.startNode(); + this.next(); + this.eat(types$1.braceL); + const revertScopes = this.initializeScopes(true); + this.enterInitialScopes(); + const program = this.startNode(); + + try { + node.body = this.parseProgram(program, types$1.braceR, "module"); + } finally { + revertScopes(); + } + + this.eat(types$1.braceR); + return this.finishNode(node, "ModuleExpression"); + } + +} + +const loopLabel = { + kind: "loop" +}, + switchLabel = { + kind: "switch" +}; +const FUNC_NO_FLAGS = 0b000, + FUNC_STATEMENT = 0b001, + FUNC_HANGING_STATEMENT = 0b010, + FUNC_NULLABLE_ID = 0b100; +const loneSurrogate = /[\uD800-\uDFFF]/u; +const keywordRelationalOperator = /in(?:stanceof)?/y; + +function babel7CompatTokens(tokens) { + { + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + + if (token.type === types$1.privateName) { + const { + loc, + start, + value, + end + } = token; + const hashEndPos = start + 1; + const hashEndLoc = new Position(loc.start.line, loc.start.column + 1); + tokens.splice(i, 1, new Token({ + type: types$1.hash, + value: "#", + start: start, + end: hashEndPos, + startLoc: loc.start, + endLoc: hashEndLoc + }), new Token({ + type: types$1.name, + value: value, + start: hashEndPos, + end: end, + startLoc: hashEndLoc, + endLoc: loc.end + })); + } + } + } + return tokens; +} + +class StatementParser extends ExpressionParser { + parseTopLevel(file, program) { + file.program = this.parseProgram(program); + file.comments = this.state.comments; + if (this.options.tokens) file.tokens = babel7CompatTokens(this.tokens); + return this.finishNode(file, "File"); + } + + parseProgram(program, end = types$1.eof, sourceType = this.options.sourceType) { + program.sourceType = sourceType; + program.interpreter = this.parseInterpreterDirective(); + this.parseBlockBody(program, true, true, end); + + if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) { + for (const [name] of Array.from(this.scope.undefinedExports)) { + const pos = this.scope.undefinedExports.get(name); + this.raise(pos, ErrorMessages.ModuleExportUndefined, name); + } + } + + return this.finishNode(program, "Program"); + } + + stmtToDirective(stmt) { + const directive = stmt; + directive.type = "Directive"; + directive.value = directive.expression; + delete directive.expression; + const directiveLiteral = directive.value; + const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end); + const val = directiveLiteral.value = raw.slice(1, -1); + this.addExtra(directiveLiteral, "raw", raw); + this.addExtra(directiveLiteral, "rawValue", val); + directiveLiteral.type = "DirectiveLiteral"; + return directive; + } + + parseInterpreterDirective() { + if (!this.match(types$1.interpreterDirective)) { + return null; + } + + const node = this.startNode(); + node.value = this.state.value; + this.next(); + return this.finishNode(node, "InterpreterDirective"); + } + + isLet(context) { + if (!this.isContextual("let")) { + return false; + } + + return this.isLetKeyword(context); + } + + isLetKeyword(context) { + const next = this.nextTokenStart(); + const nextCh = this.codePointAtPos(next); + + if (nextCh === 92 || nextCh === 91) { + return true; + } + + if (context) return false; + if (nextCh === 123) return true; + + if (isIdentifierStart(nextCh)) { + keywordRelationalOperator.lastIndex = next; + + if (keywordRelationalOperator.test(this.input)) { + const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex); + + if (!isIdentifierChar(endCh) && endCh !== 92) { + return false; + } + } + + return true; + } + + return false; + } + + parseStatement(context, topLevel) { + if (this.match(types$1.at)) { + this.parseDecorators(true); + } + + return this.parseStatementContent(context, topLevel); + } + + parseStatementContent(context, topLevel) { + let starttype = this.state.type; + const node = this.startNode(); + let kind; + + if (this.isLet(context)) { + starttype = types$1._var; + kind = "let"; + } + + switch (starttype) { + case types$1._break: + case types$1._continue: + return this.parseBreakContinueStatement(node, starttype.keyword); + + case types$1._debugger: + return this.parseDebuggerStatement(node); + + case types$1._do: + return this.parseDoStatement(node); + + case types$1._for: + return this.parseForStatement(node); + + case types$1._function: + if (this.lookaheadCharCode() === 46) break; + + if (context) { + if (this.state.strict) { + this.raise(this.state.start, ErrorMessages.StrictFunction); + } else if (context !== "if" && context !== "label") { + this.raise(this.state.start, ErrorMessages.SloppyFunction); + } + } + + return this.parseFunctionStatement(node, false, !context); + + case types$1._class: + if (context) this.unexpected(); + return this.parseClass(node, true); + + case types$1._if: + return this.parseIfStatement(node); + + case types$1._return: + return this.parseReturnStatement(node); + + case types$1._switch: + return this.parseSwitchStatement(node); + + case types$1._throw: + return this.parseThrowStatement(node); + + case types$1._try: + return this.parseTryStatement(node); + + case types$1._const: + case types$1._var: + kind = kind || this.state.value; + + if (context && kind !== "var") { + this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration); + } + + return this.parseVarStatement(node, kind); + + case types$1._while: + return this.parseWhileStatement(node); + + case types$1._with: + return this.parseWithStatement(node); + + case types$1.braceL: + return this.parseBlock(); + + case types$1.semi: + return this.parseEmptyStatement(node); + + case types$1._import: + { + const nextTokenCharCode = this.lookaheadCharCode(); + + if (nextTokenCharCode === 40 || nextTokenCharCode === 46) { + break; + } + } + + case types$1._export: + { + if (!this.options.allowImportExportEverywhere && !topLevel) { + this.raise(this.state.start, ErrorMessages.UnexpectedImportExport); + } + + this.next(); + let result; + + if (starttype === types$1._import) { + result = this.parseImport(node); + + if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) { + this.sawUnambiguousESM = true; + } + } else { + result = this.parseExport(node); + + if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") { + this.sawUnambiguousESM = true; + } + } + + this.assertModuleNodeAllowed(node); + return result; + } + + default: + { + if (this.isAsyncFunction()) { + if (context) { + this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext); + } + + this.next(); + return this.parseFunctionStatement(node, true, !context); + } + } + } + + const maybeName = this.state.value; + const expr = this.parseExpression(); + + if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) { + return this.parseLabeledStatement(node, maybeName, expr, context); + } else { + return this.parseExpressionStatement(node, expr); + } + } + + assertModuleNodeAllowed(node) { + if (!this.options.allowImportExportEverywhere && !this.inModule) { + this.raise(node.start, SourceTypeModuleErrorMessages.ImportOutsideModule); + } + } + + takeDecorators(node) { + const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; + + if (decorators.length) { + node.decorators = decorators; + this.resetStartLocationFromNode(node, decorators[0]); + this.state.decoratorStack[this.state.decoratorStack.length - 1] = []; + } + } + + canHaveLeadingDecorator() { + return this.match(types$1._class); + } + + parseDecorators(allowExport) { + const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; + + while (this.match(types$1.at)) { + const decorator = this.parseDecorator(); + currentContextDecorators.push(decorator); + } + + if (this.match(types$1._export)) { + if (!allowExport) { + this.unexpected(); + } + + if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) { + this.raise(this.state.start, ErrorMessages.DecoratorExportClass); + } + } else if (!this.canHaveLeadingDecorator()) { + throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator); + } + } + + parseDecorator() { + this.expectOnePlugin(["decorators-legacy", "decorators"]); + const node = this.startNode(); + this.next(); + + if (this.hasPlugin("decorators")) { + this.state.decoratorStack.push([]); + const startPos = this.state.start; + const startLoc = this.state.startLoc; + let expr; + + if (this.eat(types$1.parenL)) { + expr = this.parseExpression(); + this.expect(types$1.parenR); + } else { + expr = this.parseIdentifier(false); + + while (this.eat(types$1.dot)) { + const node = this.startNodeAt(startPos, startLoc); + node.object = expr; + node.property = this.parseIdentifier(true); + node.computed = false; + expr = this.finishNode(node, "MemberExpression"); + } + } + + node.expression = this.parseMaybeDecoratorArguments(expr); + this.state.decoratorStack.pop(); + } else { + node.expression = this.parseExprSubscripts(); + } + + return this.finishNode(node, "Decorator"); + } + + parseMaybeDecoratorArguments(expr) { + if (this.eat(types$1.parenL)) { + const node = this.startNodeAtNode(expr); + node.callee = expr; + node.arguments = this.parseCallExpressionArguments(types$1.parenR, false); + this.toReferencedList(node.arguments); + return this.finishNode(node, "CallExpression"); + } + + return expr; + } + + parseBreakContinueStatement(node, keyword) { + const isBreak = keyword === "break"; + this.next(); + + if (this.isLineTerminator()) { + node.label = null; + } else { + node.label = this.parseIdentifier(); + this.semicolon(); + } + + this.verifyBreakContinue(node, keyword); + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); + } + + verifyBreakContinue(node, keyword) { + const isBreak = keyword === "break"; + let i; + + for (i = 0; i < this.state.labels.length; ++i) { + const lab = this.state.labels[i]; + + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) break; + if (node.label && isBreak) break; + } + } + + if (i === this.state.labels.length) { + this.raise(node.start, ErrorMessages.IllegalBreakContinue, keyword); + } + } + + parseDebuggerStatement(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement"); + } + + parseHeaderExpression() { + this.expect(types$1.parenL); + const val = this.parseExpression(); + this.expect(types$1.parenR); + return val; + } + + parseDoStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("do")); + this.state.labels.pop(); + this.expect(types$1._while); + node.test = this.parseHeaderExpression(); + this.eat(types$1.semi); + return this.finishNode(node, "DoWhileStatement"); + } + + parseForStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + let awaitAt = -1; + + if (this.isAwaitAllowed() && this.eatContextual("await")) { + awaitAt = this.state.lastTokStart; + } + + this.scope.enter(SCOPE_OTHER); + this.expect(types$1.parenL); + + if (this.match(types$1.semi)) { + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + + return this.parseFor(node, null); + } + + const startsWithLet = this.isContextual("let"); + const isLet = startsWithLet && this.isLetKeyword(); + + if (this.match(types$1._var) || this.match(types$1._const) || isLet) { + const init = this.startNode(); + const kind = isLet ? "let" : this.state.value; + this.next(); + this.parseVar(init, true, kind); + this.finishNode(init, "VariableDeclaration"); + + if ((this.match(types$1._in) || this.isContextual("of")) && init.declarations.length === 1) { + return this.parseForIn(node, init, awaitAt); + } + + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + + return this.parseFor(node, init); + } + + const startsWithUnescapedName = this.match(types$1.name) && !this.state.containsEsc; + const refExpressionErrors = new ExpressionErrors(); + const init = this.parseExpression(true, refExpressionErrors); + const isForOf = this.isContextual("of"); + + if (isForOf) { + if (startsWithLet) { + this.raise(init.start, ErrorMessages.ForOfLet); + } else if (awaitAt === -1 && startsWithUnescapedName && init.type === "Identifier" && init.name === "async") { + this.raise(init.start, ErrorMessages.ForOfAsync); + } + } + + if (isForOf || this.match(types$1._in)) { + this.toAssignable(init, true); + const description = isForOf ? "for-of statement" : "for-in statement"; + this.checkLVal(init, description); + return this.parseForIn(node, init, awaitAt); + } else { + this.checkExpressionErrors(refExpressionErrors, true); + } + + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + + return this.parseFor(node, init); + } + + parseFunctionStatement(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync); + } + + parseIfStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement"); + } + + parseReturnStatement(node) { + if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) { + this.raise(this.state.start, ErrorMessages.IllegalReturn); + } + + this.next(); + + if (this.isLineTerminator()) { + node.argument = null; + } else { + node.argument = this.parseExpression(); + this.semicolon(); + } + + return this.finishNode(node, "ReturnStatement"); + } + + parseSwitchStatement(node) { + this.next(); + node.discriminant = this.parseHeaderExpression(); + const cases = node.cases = []; + this.expect(types$1.braceL); + this.state.labels.push(switchLabel); + this.scope.enter(SCOPE_OTHER); + let cur; + + for (let sawDefault; !this.match(types$1.braceR);) { + if (this.match(types$1._case) || this.match(types$1._default)) { + const isCase = this.match(types$1._case); + if (cur) this.finishNode(cur, "SwitchCase"); + cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { + this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch); + } + + sawDefault = true; + cur.test = null; + } + + this.expect(types$1.colon); + } else { + if (cur) { + cur.consequent.push(this.parseStatement(null)); + } else { + this.unexpected(); + } + } + } + + this.scope.exit(); + if (cur) this.finishNode(cur, "SwitchCase"); + this.next(); + this.state.labels.pop(); + return this.finishNode(node, "SwitchStatement"); + } + + parseThrowStatement(node) { + this.next(); + + if (this.hasPrecedingLineBreak()) { + this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow); + } + + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement"); + } + + parseCatchClauseParam() { + const param = this.parseBindingAtom(); + const simple = param.type === "Identifier"; + this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLVal(param, "catch clause", BIND_LEXICAL); + return param; + } + + parseTryStatement(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + + if (this.match(types$1._catch)) { + const clause = this.startNode(); + this.next(); + + if (this.match(types$1.parenL)) { + this.expect(types$1.parenL); + clause.param = this.parseCatchClauseParam(); + this.expect(types$1.parenR); + } else { + clause.param = null; + this.scope.enter(SCOPE_OTHER); + } + + clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false)); + this.scope.exit(); + node.handler = this.finishNode(clause, "CatchClause"); + } + + node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; + + if (!node.handler && !node.finalizer) { + this.raise(node.start, ErrorMessages.NoCatchOrFinally); + } + + return this.finishNode(node, "TryStatement"); + } + + parseVarStatement(node, kind) { + this.next(); + this.parseVar(node, false, kind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration"); + } + + parseWhileStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + this.state.labels.push(loopLabel); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("while")); + this.state.labels.pop(); + return this.finishNode(node, "WhileStatement"); + } + + parseWithStatement(node) { + if (this.state.strict) { + this.raise(this.state.start, ErrorMessages.StrictWith); + } + + this.next(); + node.object = this.parseHeaderExpression(); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("with")); + return this.finishNode(node, "WithStatement"); + } + + parseEmptyStatement(node) { + this.next(); + return this.finishNode(node, "EmptyStatement"); + } + + parseLabeledStatement(node, maybeName, expr, context) { + for (const label of this.state.labels) { + if (label.name === maybeName) { + this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName); + } + } + + const kind = this.state.type.isLoop ? "loop" : this.match(types$1._switch) ? "switch" : null; + + for (let i = this.state.labels.length - 1; i >= 0; i--) { + const label = this.state.labels[i]; + + if (label.statementStart === node.start) { + label.statementStart = this.state.start; + label.kind = kind; + } else { + break; + } + } + + this.state.labels.push({ + name: maybeName, + kind: kind, + statementStart: this.state.start + }); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.state.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement"); + } + + parseExpressionStatement(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement"); + } + + parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) { + const node = this.startNode(); + + if (allowDirectives) { + this.state.strictErrors.clear(); + } + + this.expect(types$1.braceL); + + if (createNewLexicalScope) { + this.scope.enter(SCOPE_OTHER); + } + + this.parseBlockBody(node, allowDirectives, false, types$1.braceR, afterBlockParse); + + if (createNewLexicalScope) { + this.scope.exit(); + } + + return this.finishNode(node, "BlockStatement"); + } + + isValidDirective(stmt) { + return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized; + } + + parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { + const body = node.body = []; + const directives = node.directives = []; + this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse); + } + + parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) { + const oldStrict = this.state.strict; + let hasStrictModeDirective = false; + let parsedNonDirective = false; + + while (!this.match(end)) { + const stmt = this.parseStatement(null, topLevel); + + if (directives && !parsedNonDirective) { + if (this.isValidDirective(stmt)) { + const directive = this.stmtToDirective(stmt); + directives.push(directive); + + if (!hasStrictModeDirective && directive.value.value === "use strict") { + hasStrictModeDirective = true; + this.setStrict(true); + } + + continue; + } + + parsedNonDirective = true; + this.state.strictErrors.clear(); + } + + body.push(stmt); + } + + if (afterBlockParse) { + afterBlockParse.call(this, hasStrictModeDirective); + } + + if (!oldStrict) { + this.setStrict(false); + } + + this.next(); + } + + parseFor(node, init) { + node.init = init; + this.semicolon(false); + node.test = this.match(types$1.semi) ? null : this.parseExpression(); + this.semicolon(false); + node.update = this.match(types$1.parenR) ? null : this.parseExpression(); + this.expect(types$1.parenR); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for")); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, "ForStatement"); + } + + parseForIn(node, init, awaitAt) { + const isForIn = this.match(types$1._in); + this.next(); + + if (isForIn) { + if (awaitAt > -1) this.unexpected(awaitAt); + } else { + node.await = awaitAt > -1; + } + + if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { + this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of"); + } else if (init.type === "AssignmentPattern") { + this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop"); + } + + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn(); + this.expect(types$1.parenR); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for")); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); + } + + parseVar(node, isFor, kind) { + const declarations = node.declarations = []; + const isTypescript = this.hasPlugin("typescript"); + node.kind = kind; + + for (;;) { + const decl = this.startNode(); + this.parseVarId(decl, kind); + + if (this.eat(types$1.eq)) { + decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn(); + } else { + if (kind === "const" && !(this.match(types$1._in) || this.isContextual("of"))) { + if (!isTypescript) { + this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations"); + } + } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types$1._in) || this.isContextual("of")))) { + this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns"); + } + + decl.init = null; + } + + declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types$1.comma)) break; + } + + return node; + } + + parseVarId(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var"); + } + + parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) { + const isStatement = statement & FUNC_STATEMENT; + const isHangingStatement = statement & FUNC_HANGING_STATEMENT; + const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID); + this.initFunction(node, isAsync); + + if (this.match(types$1.star) && isHangingStatement) { + this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext); + } + + node.generator = this.eat(types$1.star); + + if (isStatement) { + node.id = this.parseFunctionId(requireId); + } + + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + this.state.maybeInArrowParameters = false; + this.scope.enter(SCOPE_FUNCTION); + this.prodParam.enter(functionFlags(isAsync, node.generator)); + + if (!isStatement) { + node.id = this.parseFunctionId(); + } + + this.parseFunctionParams(node, false); + this.withSmartMixTopicForbiddingContext(() => { + this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); + }); + this.prodParam.exit(); + this.scope.exit(); + + if (isStatement && !isHangingStatement) { + this.registerFunctionStatementId(node); + } + + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return node; + } + + parseFunctionId(requireId) { + return requireId || this.match(types$1.name) ? this.parseIdentifier() : null; + } + + parseFunctionParams(node, allowModifiers) { + this.expect(types$1.parenL); + this.expressionScope.enter(newParameterDeclarationScope()); + node.params = this.parseBindingList(types$1.parenR, 41, false, allowModifiers); + this.expressionScope.exit(); + } + + registerFunctionStatementId(node) { + if (!node.id) return; + this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start); + } + + parseClass(node, isStatement, optionalId) { + this.next(); + this.takeDecorators(node); + const oldStrict = this.state.strict; + this.state.strict = true; + this.parseClassId(node, isStatement, optionalId); + this.parseClassSuper(node); + node.body = this.parseClassBody(!!node.superClass, oldStrict); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); + } + + isClassProperty() { + return this.match(types$1.eq) || this.match(types$1.semi) || this.match(types$1.braceR); + } + + isClassMethod() { + return this.match(types$1.parenL); + } + + isNonstaticConstructor(method) { + return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor"); + } + + parseClassBody(hadSuperClass, oldStrict) { + this.classScope.enter(); + const state = { + hadConstructor: false, + hadSuperClass + }; + let decorators = []; + const classBody = this.startNode(); + classBody.body = []; + this.expect(types$1.braceL); + this.withSmartMixTopicForbiddingContext(() => { + while (!this.match(types$1.braceR)) { + if (this.eat(types$1.semi)) { + if (decorators.length > 0) { + throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon); + } + + continue; + } + + if (this.match(types$1.at)) { + decorators.push(this.parseDecorator()); + continue; + } + + const member = this.startNode(); + + if (decorators.length) { + member.decorators = decorators; + this.resetStartLocationFromNode(member, decorators[0]); + decorators = []; + } + + this.parseClassMember(classBody, member, state); + + if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { + this.raise(member.start, ErrorMessages.DecoratorConstructor); + } + } + }); + this.state.strict = oldStrict; + this.next(); + + if (decorators.length) { + throw this.raise(this.state.start, ErrorMessages.TrailingDecorator); + } + + this.classScope.exit(); + return this.finishNode(classBody, "ClassBody"); + } + + parseClassMemberFromModifier(classBody, member) { + const key = this.parseIdentifier(true); + + if (this.isClassMethod()) { + const method = member; + method.kind = "method"; + method.computed = false; + method.key = key; + method.static = false; + this.pushClassMethod(classBody, method, false, false, false, false); + return true; + } else if (this.isClassProperty()) { + const prop = member; + prop.computed = false; + prop.key = key; + prop.static = false; + classBody.body.push(this.parseClassProperty(prop)); + return true; + } + + this.resetPreviousNodeTrailingComments(key); + return false; + } + + parseClassMember(classBody, member, state) { + const isStatic = this.isContextual("static"); + + if (isStatic) { + if (this.parseClassMemberFromModifier(classBody, member)) { + return; + } + + if (this.eat(types$1.braceL)) { + this.parseClassStaticBlock(classBody, member); + return; + } + } + + this.parseClassMemberWithIsStatic(classBody, member, state, isStatic); + } + + parseClassMemberWithIsStatic(classBody, member, state, isStatic) { + const publicMethod = member; + const privateMethod = member; + const publicProp = member; + const privateProp = member; + const method = publicMethod; + const publicMember = publicMethod; + member.static = isStatic; + + if (this.eat(types$1.star)) { + method.kind = "method"; + const isPrivateName = this.match(types$1.privateName); + this.parseClassElementName(method); + + if (isPrivateName) { + this.pushClassPrivateMethod(classBody, privateMethod, true, false); + return; + } + + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator); + } + + this.pushClassMethod(classBody, publicMethod, true, false, false, false); + return; + } + + const isContextual = this.match(types$1.name) && !this.state.containsEsc; + const isPrivate = this.match(types$1.privateName); + const key = this.parseClassElementName(member); + const maybeQuestionTokenStart = this.state.start; + this.parsePostMemberNameModifiers(publicMember); + + if (this.isClassMethod()) { + method.kind = "method"; + + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + return; + } + + const isConstructor = this.isNonstaticConstructor(publicMethod); + let allowsDirectSuper = false; + + if (isConstructor) { + publicMethod.kind = "constructor"; + + if (state.hadConstructor && !this.hasPlugin("typescript")) { + this.raise(key.start, ErrorMessages.DuplicateConstructor); + } + + if (isConstructor && this.hasPlugin("typescript") && member.override) { + this.raise(key.start, ErrorMessages.OverrideOnConstructor); + } + + state.hadConstructor = true; + allowsDirectSuper = state.hadSuperClass; + } + + this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper); + } else if (this.isClassProperty()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else if (isContextual && key.name === "async" && !this.isLineTerminator()) { + this.resetPreviousNodeTrailingComments(key); + const isGenerator = this.eat(types$1.star); + + if (publicMember.optional) { + this.unexpected(maybeQuestionTokenStart); + } + + method.kind = "method"; + const isPrivate = this.match(types$1.privateName); + this.parseClassElementName(method); + this.parsePostMemberNameModifiers(publicMember); + + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync); + } + + this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false); + } + } else if (isContextual && (key.name === "get" || key.name === "set") && !(this.match(types$1.star) && this.isLineTerminator())) { + this.resetPreviousNodeTrailingComments(key); + method.kind = key.name; + const isPrivate = this.match(types$1.privateName); + this.parseClassElementName(publicMethod); + + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor); + } + + this.pushClassMethod(classBody, publicMethod, false, false, false, false); + } + + this.checkGetterSetterParams(publicMethod); + } else if (this.isLineTerminator()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else { + this.unexpected(); + } + } + + parseClassElementName(member) { + const { + type, + value, + start + } = this.state; + + if ((type === types$1.name || type === types$1.string) && member.static && value === "prototype") { + this.raise(start, ErrorMessages.StaticPrototype); + } + + if (type === types$1.privateName && value === "constructor") { + this.raise(start, ErrorMessages.ConstructorClassPrivateField); + } + + return this.parsePropertyName(member, true); + } + + parseClassStaticBlock(classBody, member) { + var _member$decorators; + + this.expectPlugin("classStaticBlock", member.start); + this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER); + const oldLabels = this.state.labels; + this.state.labels = []; + this.prodParam.enter(PARAM); + const body = member.body = []; + this.parseBlockOrModuleBlockBody(body, undefined, false, types$1.braceR); + this.prodParam.exit(); + this.scope.exit(); + this.state.labels = oldLabels; + classBody.body.push(this.finishNode(member, "StaticBlock")); + + if ((_member$decorators = member.decorators) != null && _member$decorators.length) { + this.raise(member.start, ErrorMessages.DecoratorStaticBlock); + } + } + + pushClassProperty(classBody, prop) { + if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) { + this.raise(prop.key.start, ErrorMessages.ConstructorClassField); + } + + classBody.body.push(this.parseClassProperty(prop)); + } + + pushClassPrivateProperty(classBody, prop) { + const node = this.parseClassPrivateProperty(prop); + classBody.body.push(node); + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.start); + } + + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true)); + } + + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true); + classBody.body.push(node); + const kind = node.kind === "get" ? node.static ? CLASS_ELEMENT_STATIC_GETTER : CLASS_ELEMENT_INSTANCE_GETTER : node.kind === "set" ? node.static ? CLASS_ELEMENT_STATIC_SETTER : CLASS_ELEMENT_INSTANCE_SETTER : CLASS_ELEMENT_OTHER; + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.start); + } + + parsePostMemberNameModifiers(methodOrProp) {} + + parseClassPrivateProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassPrivateProperty"); + } + + parseClassProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassProperty"); + } + + parseInitializer(node) { + this.scope.enter(SCOPE_CLASS | SCOPE_SUPER); + this.expressionScope.enter(newExpressionScope()); + this.prodParam.enter(PARAM); + node.value = this.eat(types$1.eq) ? this.parseMaybeAssignAllowIn() : null; + this.expressionScope.exit(); + this.prodParam.exit(); + this.scope.exit(); + } + + parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) { + if (this.match(types$1.name)) { + node.id = this.parseIdentifier(); + + if (isStatement) { + this.checkLVal(node.id, "class name", bindingType); + } + } else { + if (optionalId || !isStatement) { + node.id = null; + } else { + this.unexpected(null, ErrorMessages.MissingClassName); + } + } + } + + parseClassSuper(node) { + node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts() : null; + } + + parseExport(node) { + const hasDefault = this.maybeParseExportDefaultSpecifier(node); + const parseAfterDefault = !hasDefault || this.eat(types$1.comma); + const hasStar = parseAfterDefault && this.eatExportStar(node); + const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node); + const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types$1.comma)); + const isFromRequired = hasDefault || hasStar; + + if (hasStar && !hasNamespace) { + if (hasDefault) this.unexpected(); + this.parseExportFrom(node, true); + return this.finishNode(node, "ExportAllDeclaration"); + } + + const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node); + + if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) { + throw this.unexpected(null, types$1.braceL); + } + + let hasDeclaration; + + if (isFromRequired || hasSpecifiers) { + hasDeclaration = false; + this.parseExportFrom(node, isFromRequired); + } else { + hasDeclaration = this.maybeParseExportDeclaration(node); + } + + if (isFromRequired || hasSpecifiers || hasDeclaration) { + this.checkExport(node, true, false, !!node.source); + return this.finishNode(node, "ExportNamedDeclaration"); + } + + if (this.eat(types$1._default)) { + node.declaration = this.parseExportDefaultExpression(); + this.checkExport(node, true, true); + return this.finishNode(node, "ExportDefaultDeclaration"); + } + + throw this.unexpected(null, types$1.braceL); + } + + eatExportStar(node) { + return this.eat(types$1.star); + } + + maybeParseExportDefaultSpecifier(node) { + if (this.isExportDefaultSpecifier()) { + this.expectPlugin("exportDefaultFrom"); + const specifier = this.startNode(); + specifier.exported = this.parseIdentifier(true); + node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return true; + } + + return false; + } + + maybeParseExportNamespaceSpecifier(node) { + if (this.isContextual("as")) { + if (!node.specifiers) node.specifiers = []; + const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc); + this.next(); + specifier.exported = this.parseModuleExportName(); + node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier")); + return true; + } + + return false; + } + + maybeParseExportNamedSpecifiers(node) { + if (this.match(types$1.braceL)) { + if (!node.specifiers) node.specifiers = []; + node.specifiers.push(...this.parseExportSpecifiers()); + node.source = null; + node.declaration = null; + return true; + } + + return false; + } + + maybeParseExportDeclaration(node) { + if (this.shouldParseExportDeclaration()) { + node.specifiers = []; + node.source = null; + node.declaration = this.parseExportDeclaration(node); + return true; + } + + return false; + } + + isAsyncFunction() { + if (!this.isContextual("async")) return false; + const next = this.nextTokenStart(); + return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function"); + } + + parseExportDefaultExpression() { + const expr = this.startNode(); + const isAsync = this.isAsyncFunction(); + + if (this.match(types$1._function) || isAsync) { + this.next(); + + if (isAsync) { + this.next(); + } + + return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync); + } else if (this.match(types$1._class)) { + return this.parseClass(expr, true, true); + } else if (this.match(types$1.at)) { + if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) { + this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport); + } + + this.parseDecorators(false); + return this.parseClass(expr, true, true); + } else if (this.match(types$1._const) || this.match(types$1._var) || this.isLet()) { + throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport); + } else { + const res = this.parseMaybeAssignAllowIn(); + this.semicolon(); + return res; + } + } + + parseExportDeclaration(node) { + return this.parseStatement(null); + } + + isExportDefaultSpecifier() { + if (this.match(types$1.name)) { + const value = this.state.value; + + if (value === "async" && !this.state.containsEsc || value === "let") { + return false; + } + + if ((value === "type" || value === "interface") && !this.state.containsEsc) { + const l = this.lookahead(); + + if (l.type === types$1.name && l.value !== "from" || l.type === types$1.braceL) { + this.expectOnePlugin(["flow", "typescript"]); + return false; + } + } + } else if (!this.match(types$1._default)) { + return false; + } + + const next = this.nextTokenStart(); + const hasFrom = this.isUnparsedContextual(next, "from"); + + if (this.input.charCodeAt(next) === 44 || this.match(types$1.name) && hasFrom) { + return true; + } + + if (this.match(types$1._default) && hasFrom) { + const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4)); + return nextAfterFrom === 34 || nextAfterFrom === 39; + } + + return false; + } + + parseExportFrom(node, expect) { + if (this.eatContextual("from")) { + node.source = this.parseImportSource(); + this.checkExport(node); + const assertions = this.maybeParseImportAssertions(); + + if (assertions) { + node.assertions = assertions; + } + } else { + if (expect) { + this.unexpected(); + } else { + node.source = null; + } + } + + this.semicolon(); + } + + shouldParseExportDeclaration() { + if (this.match(types$1.at)) { + this.expectOnePlugin(["decorators", "decorators-legacy"]); + + if (this.hasPlugin("decorators")) { + if (this.getPluginOption("decorators", "decoratorsBeforeExport")) { + this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport); + } else { + return true; + } + } + } + + return this.state.type.keyword === "var" || this.state.type.keyword === "const" || this.state.type.keyword === "function" || this.state.type.keyword === "class" || this.isLet() || this.isAsyncFunction(); + } + + checkExport(node, checkNames, isDefault, isFrom) { + if (checkNames) { + if (isDefault) { + this.checkDuplicateExports(node, "default"); + + if (this.hasPlugin("exportDefaultFrom")) { + var _declaration$extra; + + const declaration = node.declaration; + + if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) { + this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier); + } + } + } else if (node.specifiers && node.specifiers.length) { + for (const specifier of node.specifiers) { + const { + exported + } = specifier; + const exportedName = exported.type === "Identifier" ? exported.name : exported.value; + this.checkDuplicateExports(specifier, exportedName); + + if (!isFrom && specifier.local) { + const { + local + } = specifier; + + if (local.type !== "Identifier") { + this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.value, exportedName); + } else { + this.checkReservedWord(local.name, local.start, true, false); + this.scope.checkLocalExport(local); + } + } + } + } else if (node.declaration) { + if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") { + const id = node.declaration.id; + if (!id) throw new Error("Assertion failure"); + this.checkDuplicateExports(node, id.name); + } else if (node.declaration.type === "VariableDeclaration") { + for (const declaration of node.declaration.declarations) { + this.checkDeclaration(declaration.id); + } + } + } + } + + const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; + + if (currentContextDecorators.length) { + throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport); + } + } + + checkDeclaration(node) { + if (node.type === "Identifier") { + this.checkDuplicateExports(node, node.name); + } else if (node.type === "ObjectPattern") { + for (const prop of node.properties) { + this.checkDeclaration(prop); + } + } else if (node.type === "ArrayPattern") { + for (const elem of node.elements) { + if (elem) { + this.checkDeclaration(elem); + } + } + } else if (node.type === "ObjectProperty") { + this.checkDeclaration(node.value); + } else if (node.type === "RestElement") { + this.checkDeclaration(node.argument); + } else if (node.type === "AssignmentPattern") { + this.checkDeclaration(node.left); + } + } + + checkDuplicateExports(node, name) { + if (this.exportedIdentifiers.has(name)) { + this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name); + } + + this.exportedIdentifiers.add(name); + } + + parseExportSpecifiers() { + const nodes = []; + let first = true; + this.expect(types$1.braceL); + + while (!this.eat(types$1.braceR)) { + if (first) { + first = false; + } else { + this.expect(types$1.comma); + if (this.eat(types$1.braceR)) break; + } + + const node = this.startNode(); + const isString = this.match(types$1.string); + const local = this.parseModuleExportName(); + node.local = local; + + if (this.eatContextual("as")) { + node.exported = this.parseModuleExportName(); + } else if (isString) { + node.exported = cloneStringLiteral(local); + } else { + node.exported = cloneIdentifier(local); + } + + nodes.push(this.finishNode(node, "ExportSpecifier")); + } + + return nodes; + } + + parseModuleExportName() { + if (this.match(types$1.string)) { + const result = this.parseStringLiteral(this.state.value); + const surrogate = result.value.match(loneSurrogate); + + if (surrogate) { + this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16)); + } + + return result; + } + + return this.parseIdentifier(true); + } + + parseImport(node) { + node.specifiers = []; + + if (!this.match(types$1.string)) { + const hasDefault = this.maybeParseDefaultImportSpecifier(node); + const parseNext = !hasDefault || this.eat(types$1.comma); + const hasStar = parseNext && this.maybeParseStarImportSpecifier(node); + if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node); + this.expectContextual("from"); + } + + node.source = this.parseImportSource(); + const assertions = this.maybeParseImportAssertions(); + + if (assertions) { + node.assertions = assertions; + } else { + const attributes = this.maybeParseModuleAttributes(); + + if (attributes) { + node.attributes = attributes; + } + } + + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + + parseImportSource() { + if (!this.match(types$1.string)) this.unexpected(); + return this.parseExprAtom(); + } + + shouldParseDefaultImport(node) { + return this.match(types$1.name); + } + + parseImportSpecifierLocal(node, specifier, type, contextDescription) { + specifier.local = this.parseIdentifier(); + this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL); + node.specifiers.push(this.finishNode(specifier, type)); + } + + parseAssertEntries() { + const attrs = []; + const attrNames = new Set(); + + do { + if (this.match(types$1.braceR)) { + break; + } + + const node = this.startNode(); + const keyName = this.state.value; + + if (attrNames.has(keyName)) { + this.raise(this.state.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName); + } + + attrNames.add(keyName); + + if (this.match(types$1.string)) { + node.key = this.parseStringLiteral(keyName); + } else { + node.key = this.parseIdentifier(true); + } + + this.expect(types$1.colon); + + if (!this.match(types$1.string)) { + throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue); + } + + node.value = this.parseStringLiteral(this.state.value); + this.finishNode(node, "ImportAttribute"); + attrs.push(node); + } while (this.eat(types$1.comma)); + + return attrs; + } + + maybeParseModuleAttributes() { + if (this.match(types$1._with) && !this.hasPrecedingLineBreak()) { + this.expectPlugin("moduleAttributes"); + this.next(); + } else { + if (this.hasPlugin("moduleAttributes")) return []; + return null; + } + + const attrs = []; + const attributes = new Set(); + + do { + const node = this.startNode(); + node.key = this.parseIdentifier(true); + + if (node.key.name !== "type") { + this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name); + } + + if (attributes.has(node.key.name)) { + this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name); + } + + attributes.add(node.key.name); + this.expect(types$1.colon); + + if (!this.match(types$1.string)) { + throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue); + } + + node.value = this.parseStringLiteral(this.state.value); + this.finishNode(node, "ImportAttribute"); + attrs.push(node); + } while (this.eat(types$1.comma)); + + return attrs; + } + + maybeParseImportAssertions() { + if (this.isContextual("assert") && !this.hasPrecedingLineBreak()) { + this.expectPlugin("importAssertions"); + this.next(); + } else { + if (this.hasPlugin("importAssertions")) return []; + return null; + } + + this.eat(types$1.braceL); + const attrs = this.parseAssertEntries(); + this.eat(types$1.braceR); + return attrs; + } + + maybeParseDefaultImportSpecifier(node) { + if (this.shouldParseDefaultImport(node)) { + this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier"); + return true; + } + + return false; + } + + maybeParseStarImportSpecifier(node) { + if (this.match(types$1.star)) { + const specifier = this.startNode(); + this.next(); + this.expectContextual("as"); + this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier"); + return true; + } + + return false; + } + + parseNamedImportSpecifiers(node) { + let first = true; + this.expect(types$1.braceL); + + while (!this.eat(types$1.braceR)) { + if (first) { + first = false; + } else { + if (this.eat(types$1.colon)) { + throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport); + } + + this.expect(types$1.comma); + if (this.eat(types$1.braceR)) break; + } + + this.parseImportSpecifier(node); + } + } + + parseImportSpecifier(node) { + const specifier = this.startNode(); + const importedIsString = this.match(types$1.string); + specifier.imported = this.parseModuleExportName(); + + if (this.eatContextual("as")) { + specifier.local = this.parseIdentifier(); + } else { + const { + imported + } = specifier; + + if (importedIsString) { + throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value); + } + + this.checkReservedWord(imported.name, specifier.start, true, true); + specifier.local = cloneIdentifier(imported); + } + + this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL); + node.specifiers.push(this.finishNode(specifier, "ImportSpecifier")); + } + + isThisParam(param) { + return param.type === "Identifier" && param.name === "this"; + } + +} + +class Parser extends StatementParser { + constructor(options, input) { + options = getOptions(options); + super(options, input); + this.options = options; + this.initializeScopes(); + this.plugins = pluginsMap(this.options.plugins); + this.filename = options.sourceFilename; + } + + getScopeHandler() { + return ScopeHandler; + } + + parse() { + this.enterInitialScopes(); + const file = this.startNode(); + const program = this.startNode(); + this.nextToken(); + file.errors = null; + this.parseTopLevel(file, program); + file.errors = this.state.errors; + return file; + } + +} + +function pluginsMap(plugins) { + const pluginMap = new Map(); + + for (const plugin of plugins) { + const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}]; + if (!pluginMap.has(name)) pluginMap.set(name, options || {}); + } + + return pluginMap; +} + +function parse(input, options) { + var _options; + + if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") { + options = Object.assign({}, options); + + try { + options.sourceType = "module"; + const parser = getParser(options, input); + const ast = parser.parse(); + + if (parser.sawUnambiguousESM) { + return ast; + } + + if (parser.ambiguousScriptDifferentAst) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused) {} + } else { + ast.program.sourceType = "script"; + } + + return ast; + } catch (moduleError) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused2) {} + + throw moduleError; + } + } else { + return getParser(options, input).parse(); + } +} +function parseExpression(input, options) { + const parser = getParser(options, input); + + if (parser.options.strictMode) { + parser.state.strict = true; + } + + return parser.getExpression(); +} + +function getParser(options, input) { + let cls = Parser; + + if (options != null && options.plugins) { + validatePlugins(options.plugins); + cls = getParserClass(options.plugins); + } + + return new cls(options, input); +} + +const parserClassCache = {}; + +function getParserClass(pluginsFromOptions) { + const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name)); + const key = pluginList.join("/"); + let cls = parserClassCache[key]; + + if (!cls) { + cls = Parser; + + for (const plugin of pluginList) { + cls = mixinPlugins[plugin](cls); + } + + parserClassCache[key] = cls; + } + + return cls; +} + +exports.parse = parse; +exports.parseExpression = parseExpression; +exports.tokTypes = types$1; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/parser/lib/index.js.map b/node_modules/@babel/parser/lib/index.js.map new file mode 100644 index 0000000..25a98ce --- /dev/null +++ b/node_modules/@babel/parser/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/tokenizer/types.js","../src/util/whitespace.js","../src/util/location.js","../src/parser/base.js","../src/parser/comments.js","../src/parser/error-codes.js","../src/parser/error-message.js","../src/parser/error.js","../src/plugins/estree.js","../src/tokenizer/context.js","../../babel-helper-validator-identifier/src/identifier.ts","../../babel-helper-validator-identifier/src/keyword.ts","../src/util/identifier.js","../src/util/scopeflags.js","../src/util/scope.js","../src/plugins/flow/scope.js","../src/tokenizer/state.js","../src/tokenizer/index.js","../src/util/class-scope.js","../src/util/expression-scope.js","../src/util/production-parameter.js","../src/parser/util.js","../src/parser/node.js","../src/plugins/flow/index.js","../src/plugins/jsx/xhtml.js","../src/plugins/jsx/index.js","../src/plugins/typescript/scope.js","../src/plugins/typescript/index.js","../src/plugins/placeholders.js","../src/plugins/v8intrinsic.js","../src/plugin-utils.js","../src/options.js","../src/parser/lval.js","../src/parser/expression.js","../src/parser/statement.js","../src/parser/index.js","../src/index.js"],"sourcesContent":["// @flow\nimport type { TokContext } from \"./context\";\n// ## Token types\n\n// The assignment of fine-grained, information-carrying type objects\n// allows the tokenizer to store the information it has about a\n// token in a way that is very cheap for the parser to look up.\n\n// All token type variables start with an underscore, to make them\n// easy to recognize.\n\n// The `beforeExpr` property is used to disambiguate between 1) binary\n// expression (<) and JSX Tag start (); 2) object literal and JSX\n// texts. It is set on the `updateContext` function in the JSX plugin.\n\n// The `startsExpr` property is used to determine whether an expression\n// may be the “argument” subexpression of a `yield` expression or\n// `yield` statement. It is set on all token types that may be at the\n// start of a subexpression.\n\n// `isLoop` marks a keyword as starting a loop, which is important\n// to know when parsing a label, in order to allow or disallow\n// continue jumps to that label.\n\nconst beforeExpr = true;\nconst startsExpr = true;\nconst isLoop = true;\nconst isAssign = true;\nconst prefix = true;\nconst postfix = true;\n\ntype TokenOptions = {\n keyword?: string,\n beforeExpr?: boolean,\n startsExpr?: boolean,\n rightAssociative?: boolean,\n isLoop?: boolean,\n isAssign?: boolean,\n prefix?: boolean,\n postfix?: boolean,\n binop?: ?number,\n};\n\nexport class TokenType {\n label: string;\n keyword: ?string;\n beforeExpr: boolean;\n startsExpr: boolean;\n rightAssociative: boolean;\n isLoop: boolean;\n isAssign: boolean;\n prefix: boolean;\n postfix: boolean;\n binop: ?number;\n updateContext: ?(context: Array) => void;\n\n constructor(label: string, conf: TokenOptions = {}) {\n this.label = label;\n this.keyword = conf.keyword;\n this.beforeExpr = !!conf.beforeExpr;\n this.startsExpr = !!conf.startsExpr;\n this.rightAssociative = !!conf.rightAssociative;\n this.isLoop = !!conf.isLoop;\n this.isAssign = !!conf.isAssign;\n this.prefix = !!conf.prefix;\n this.postfix = !!conf.postfix;\n this.binop = conf.binop != null ? conf.binop : null;\n this.updateContext = null;\n }\n}\n\nexport const keywords = new Map();\n\nfunction createKeyword(name: string, options: TokenOptions = {}): TokenType {\n options.keyword = name;\n const token = new TokenType(name, options);\n keywords.set(name, token);\n return token;\n}\n\nfunction createBinop(name: string, binop: number) {\n return new TokenType(name, { beforeExpr, binop });\n}\n\nexport const types: { [name: string]: TokenType } = {\n num: new TokenType(\"num\", { startsExpr }),\n bigint: new TokenType(\"bigint\", { startsExpr }),\n decimal: new TokenType(\"decimal\", { startsExpr }),\n regexp: new TokenType(\"regexp\", { startsExpr }),\n string: new TokenType(\"string\", { startsExpr }),\n name: new TokenType(\"name\", { startsExpr }),\n privateName: new TokenType(\"#name\", { startsExpr }),\n eof: new TokenType(\"eof\"),\n\n // Punctuation token types.\n bracketL: new TokenType(\"[\", { beforeExpr, startsExpr }),\n bracketHashL: new TokenType(\"#[\", { beforeExpr, startsExpr }),\n bracketBarL: new TokenType(\"[|\", { beforeExpr, startsExpr }),\n bracketR: new TokenType(\"]\"),\n bracketBarR: new TokenType(\"|]\"),\n braceL: new TokenType(\"{\", { beforeExpr, startsExpr }),\n braceBarL: new TokenType(\"{|\", { beforeExpr, startsExpr }),\n braceHashL: new TokenType(\"#{\", { beforeExpr, startsExpr }),\n braceR: new TokenType(\"}\", { beforeExpr }),\n braceBarR: new TokenType(\"|}\"),\n parenL: new TokenType(\"(\", { beforeExpr, startsExpr }),\n parenR: new TokenType(\")\"),\n comma: new TokenType(\",\", { beforeExpr }),\n semi: new TokenType(\";\", { beforeExpr }),\n colon: new TokenType(\":\", { beforeExpr }),\n doubleColon: new TokenType(\"::\", { beforeExpr }),\n dot: new TokenType(\".\"),\n question: new TokenType(\"?\", { beforeExpr }),\n questionDot: new TokenType(\"?.\"),\n arrow: new TokenType(\"=>\", { beforeExpr }),\n template: new TokenType(\"template\"),\n ellipsis: new TokenType(\"...\", { beforeExpr }),\n backQuote: new TokenType(\"`\", { startsExpr }),\n dollarBraceL: new TokenType(\"${\", { beforeExpr, startsExpr }),\n at: new TokenType(\"@\"),\n hash: new TokenType(\"#\", { startsExpr }),\n\n // Special hashbang token.\n interpreterDirective: new TokenType(\"#!...\"),\n\n // Operators. These carry several kinds of properties to help the\n // parser use them properly (the presence of these properties is\n // what categorizes them as operators).\n //\n // `binop`, when present, specifies that this operator is a binary\n // operator, and will refer to its precedence.\n //\n // `prefix` and `postfix` mark the operator as a prefix or postfix\n // unary operator.\n //\n // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as\n // binary operators with a very low precedence, that should result\n // in AssignmentExpression nodes.\n\n eq: new TokenType(\"=\", { beforeExpr, isAssign }),\n assign: new TokenType(\"_=\", { beforeExpr, isAssign }),\n slashAssign: new TokenType(\"_=\", { beforeExpr, isAssign }),\n // This is only needed to support % as a Hack-pipe topic token. If the proposal\n // ends up choosing a different token, it can be merged with tt.assign.\n moduloAssign: new TokenType(\"_=\", { beforeExpr, isAssign }),\n incDec: new TokenType(\"++/--\", { prefix, postfix, startsExpr }),\n bang: new TokenType(\"!\", { beforeExpr, prefix, startsExpr }),\n tilde: new TokenType(\"~\", { beforeExpr, prefix, startsExpr }),\n pipeline: createBinop(\"|>\", 0),\n nullishCoalescing: createBinop(\"??\", 1),\n logicalOR: createBinop(\"||\", 1),\n logicalAND: createBinop(\"&&\", 2),\n bitwiseOR: createBinop(\"|\", 3),\n bitwiseXOR: createBinop(\"^\", 4),\n bitwiseAND: createBinop(\"&\", 5),\n equality: createBinop(\"==/!=/===/!==\", 6),\n relational: createBinop(\"/<=/>=\", 7),\n bitShift: createBinop(\"<>/>>>\", 8),\n plusMin: new TokenType(\"+/-\", { beforeExpr, binop: 9, prefix, startsExpr }),\n // startsExpr: required by v8intrinsic plugin\n modulo: new TokenType(\"%\", { binop: 10, startsExpr }),\n // unset `beforeExpr` as it can be `function *`\n star: new TokenType(\"*\", { binop: 10 }),\n slash: createBinop(\"/\", 10),\n exponent: new TokenType(\"**\", {\n beforeExpr,\n binop: 11,\n rightAssociative: true,\n }),\n\n // Keywords\n // Don't forget to update packages/babel-helper-validator-identifier/src/keyword.js\n // when new keywords are added\n _break: createKeyword(\"break\"),\n _case: createKeyword(\"case\", { beforeExpr }),\n _catch: createKeyword(\"catch\"),\n _continue: createKeyword(\"continue\"),\n _debugger: createKeyword(\"debugger\"),\n _default: createKeyword(\"default\", { beforeExpr }),\n _do: createKeyword(\"do\", { isLoop, beforeExpr }),\n _else: createKeyword(\"else\", { beforeExpr }),\n _finally: createKeyword(\"finally\"),\n _for: createKeyword(\"for\", { isLoop }),\n _function: createKeyword(\"function\", { startsExpr }),\n _if: createKeyword(\"if\"),\n _return: createKeyword(\"return\", { beforeExpr }),\n _switch: createKeyword(\"switch\"),\n _throw: createKeyword(\"throw\", { beforeExpr, prefix, startsExpr }),\n _try: createKeyword(\"try\"),\n _var: createKeyword(\"var\"),\n _const: createKeyword(\"const\"),\n _while: createKeyword(\"while\", { isLoop }),\n _with: createKeyword(\"with\"),\n _new: createKeyword(\"new\", { beforeExpr, startsExpr }),\n _this: createKeyword(\"this\", { startsExpr }),\n _super: createKeyword(\"super\", { startsExpr }),\n _class: createKeyword(\"class\", { startsExpr }),\n _extends: createKeyword(\"extends\", { beforeExpr }),\n _export: createKeyword(\"export\"),\n _import: createKeyword(\"import\", { startsExpr }),\n _null: createKeyword(\"null\", { startsExpr }),\n _true: createKeyword(\"true\", { startsExpr }),\n _false: createKeyword(\"false\", { startsExpr }),\n _in: createKeyword(\"in\", { beforeExpr, binop: 7 }),\n _instanceof: createKeyword(\"instanceof\", { beforeExpr, binop: 7 }),\n _typeof: createKeyword(\"typeof\", { beforeExpr, prefix, startsExpr }),\n _void: createKeyword(\"void\", { beforeExpr, prefix, startsExpr }),\n _delete: createKeyword(\"delete\", { beforeExpr, prefix, startsExpr }),\n};\n","// @flow\n\nimport * as charCodes from \"charcodes\";\n\n// Matches a whole line break (where CRLF is considered a single\n// line break). Used to count lines.\nexport const lineBreak = /\\r\\n?|[\\n\\u2028\\u2029]/;\nexport const lineBreakG = new RegExp(lineBreak.source, \"g\");\n\n// https://tc39.github.io/ecma262/#sec-line-terminators\nexport function isNewLine(code: number): boolean {\n switch (code) {\n case charCodes.lineFeed:\n case charCodes.carriageReturn:\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return true;\n\n default:\n return false;\n }\n}\n\nexport const skipWhiteSpace = /(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g;\n\nexport const skipWhiteSpaceInLine =\n /(?:[^\\S\\n\\r\\u2028\\u2029]|\\/\\/.*|\\/\\*.*?\\*\\/)*/y;\n\n// Skip whitespace and single-line comments, including /* no newline here */.\n// After this RegExp matches, its lastIndex points to a line terminator, or\n// the start of multi-line comment (which is effectively a line terminator),\n// or the end of string.\nexport const skipWhiteSpaceToLineBreak = new RegExp(\n // Unfortunately JS doesn't support Perl's atomic /(?>pattern)/ or\n // possessive quantifiers, so we use a trick to prevent backtracking\n // when the look-ahead for line terminator fails.\n \"(?=(\" +\n // Capture the whitespace and comments that should be skipped inside\n // a look-ahead assertion, and then re-match the group as a unit.\n skipWhiteSpaceInLine.source +\n \"))\\\\1\" +\n // Look-ahead for either line terminator, start of multi-line comment,\n // or end of string.\n /(?=[\\n\\r\\u2028\\u2029]|\\/\\*(?!.*?\\*\\/)|$)/.source,\n \"y\", // sticky\n);\n\n// https://tc39.github.io/ecma262/#sec-white-space\nexport function isWhitespace(code: number): boolean {\n switch (code) {\n case 0x0009: // CHARACTER TABULATION\n case 0x000b: // LINE TABULATION\n case 0x000c: // FORM FEED\n case charCodes.space:\n case charCodes.nonBreakingSpace:\n case charCodes.oghamSpaceMark:\n case 0x2000: // EN QUAD\n case 0x2001: // EM QUAD\n case 0x2002: // EN SPACE\n case 0x2003: // EM SPACE\n case 0x2004: // THREE-PER-EM SPACE\n case 0x2005: // FOUR-PER-EM SPACE\n case 0x2006: // SIX-PER-EM SPACE\n case 0x2007: // FIGURE SPACE\n case 0x2008: // PUNCTUATION SPACE\n case 0x2009: // THIN SPACE\n case 0x200a: // HAIR SPACE\n case 0x202f: // NARROW NO-BREAK SPACE\n case 0x205f: // MEDIUM MATHEMATICAL SPACE\n case 0x3000: // IDEOGRAPHIC SPACE\n case 0xfeff: // ZERO WIDTH NO-BREAK SPACE\n return true;\n\n default:\n return false;\n }\n}\n","// @flow\n\nimport { lineBreakG } from \"./whitespace\";\n\nexport type Pos = {\n start: number,\n};\n\n// These are used when `options.locations` is on, for the\n// `startLoc` and `endLoc` properties.\n\nexport class Position {\n line: number;\n column: number;\n\n constructor(line: number, col: number) {\n this.line = line;\n this.column = col;\n }\n}\n\nexport class SourceLocation {\n start: Position;\n end: Position;\n filename: string;\n identifierName: ?string;\n\n constructor(start: Position, end?: Position) {\n this.start = start;\n // $FlowIgnore (may start as null, but initialized later)\n this.end = end;\n }\n}\n\n// The `getLineInfo` function is mostly useful when the\n// `locations` option is off (for performance reasons) and you\n// want to find the line/column position for a given character\n// offset. `input` should be the code string that the offset refers\n// into.\n\nexport function getLineInfo(input: string, offset: number): Position {\n let line = 1;\n let lineStart = 0;\n let match;\n lineBreakG.lastIndex = 0;\n while ((match = lineBreakG.exec(input)) && match.index < offset) {\n line++;\n lineStart = lineBreakG.lastIndex;\n }\n\n return new Position(line, offset - lineStart);\n}\n","// @flow\n\nimport type { Options } from \"../options\";\nimport type State from \"../tokenizer/state\";\nimport type { PluginsMap } from \"./index\";\nimport type ScopeHandler from \"../util/scope\";\nimport type ExpressionScopeHandler from \"../util/expression-scope\";\nimport type ClassScopeHandler from \"../util/class-scope\";\nimport type ProductionParameterHandler from \"../util/production-parameter\";\n\nexport default class BaseParser {\n // Properties set by constructor in index.js\n declare options: Options;\n declare inModule: boolean;\n declare scope: ScopeHandler<*>;\n declare classScope: ClassScopeHandler;\n declare prodParam: ProductionParameterHandler;\n declare expressionScope: ExpressionScopeHandler;\n declare plugins: PluginsMap;\n declare filename: ?string;\n // Names of exports store. `default` is stored as a name for both\n // `export default foo;` and `export { foo as default };`.\n declare exportedIdentifiers: Set;\n sawUnambiguousESM: boolean = false;\n ambiguousScriptDifferentAst: boolean = false;\n\n // Initialized by Tokenizer\n declare state: State;\n // input and length are not in state as they are constant and we do\n // not want to ever copy them, which happens if state gets cloned\n declare input: string;\n declare length: number;\n\n hasPlugin(name: string): boolean {\n return this.plugins.has(name);\n }\n\n getPluginOption(plugin: string, name: string) {\n // $FlowIssue\n if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];\n }\n}\n","// @flow\n\n/*:: declare var invariant; */\n\nimport BaseParser from \"./base\";\nimport type { Comment, Node } from \"../types\";\nimport * as charCodes from \"charcodes\";\n\n/**\n * A whitespace token containing comments\n * @typedef CommentWhitespace\n * @type {object}\n * @property {number} start - the start of the whitespace token.\n * @property {number} end - the end of the whitespace token.\n * @property {Array} comments - the containing comments\n * @property {Node | null} leadingNode - the immediately preceding AST node of the whitespace token\n * @property {Node | null} trailingNode - the immediately following AST node of the whitespace token\n * @property {Node | null} containingNode - the innermost AST node containing the whitespace\n * with minimal size (|end - start|)\n */\nexport type CommentWhitespace = {\n start: number,\n end: number,\n comments: Array,\n leadingNode: Node | null,\n trailingNode: Node | null,\n containingNode: Node | null,\n};\n/**\n * Merge comments with node's trailingComments or assign comments to be\n * trailingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n *\n * @param {Node} node\n * @param {Array} comments\n */\nfunction setTrailingComments(node: Node, comments: Array) {\n if (node.trailingComments === undefined) {\n node.trailingComments = comments;\n } else {\n node.trailingComments.unshift(...comments);\n }\n}\n\n/**\n * Merge comments with node's innerComments or assign comments to be\n * innerComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n *\n * @param {Node} node\n * @param {Array} comments\n */\nexport function setInnerComments(node: Node, comments: Array | void) {\n if (node.innerComments === undefined) {\n node.innerComments = comments;\n } else if (comments !== undefined) {\n node.innerComments.unshift(...comments);\n }\n}\n\n/**\n * Given node and elements array, if elements has non-null element,\n * merge comments to its trailingComments, otherwise merge comments\n * to node's innerComments\n *\n * @param {Node} node\n * @param {Array} elements\n * @param {Array} comments\n */\nfunction adjustInnerComments(\n node: Node,\n elements: Array,\n commentWS: CommentWhitespace,\n) {\n let lastElement = null;\n let i = elements.length;\n while (lastElement === null && i > 0) {\n lastElement = elements[--i];\n }\n if (lastElement === null || lastElement.start > commentWS.start) {\n setInnerComments(node, commentWS.comments);\n } else {\n setTrailingComments(lastElement, commentWS.comments);\n }\n}\n\n/** @class CommentsParser */\nexport default class CommentsParser extends BaseParser {\n addComment(comment: Comment): void {\n if (this.filename) comment.loc.filename = this.filename;\n this.state.comments.push(comment);\n }\n\n /**\n * Given a newly created AST node _n_, attach _n_ to a comment whitespace _w_ if applicable\n * {@see {@link CommentWhitespace}}\n *\n * @param {Node} node\n * @returns {void}\n * @memberof CommentsParser\n */\n processComment(node: Node): void {\n const { commentStack } = this.state;\n const commentStackLength = commentStack.length;\n if (commentStackLength === 0) return;\n let i = commentStackLength - 1;\n const lastCommentWS = commentStack[i];\n\n if (lastCommentWS.start === node.end) {\n lastCommentWS.leadingNode = node;\n i--;\n }\n\n const { start: nodeStart } = node;\n // invariant: for all 0 <= j <= i, let c = commentStack[j], c must satisfy c.end < node.end\n for (; i >= 0; i--) {\n const commentWS = commentStack[i];\n const commentEnd = commentWS.end;\n if (commentEnd > nodeStart) {\n // by definition of commentWhiteSpace, this implies commentWS.start > nodeStart\n // so node can be a containingNode candidate. At this time we can finalize the comment\n // whitespace, because\n // 1) its leadingNode or trailingNode, if exists, will not change\n // 2) its containingNode have been assigned and will not change because it is the\n // innermost minimal-sized AST node\n commentWS.containingNode = node;\n this.finalizeComment(commentWS);\n commentStack.splice(i, 1);\n } else {\n if (commentEnd === nodeStart) {\n commentWS.trailingNode = node;\n }\n // stop the loop when commentEnd <= nodeStart\n break;\n }\n }\n }\n\n /**\n * Assign the comments of comment whitespaces to related AST nodes.\n * Also adjust innerComments following trailing comma.\n *\n * @memberof CommentsParser\n */\n finalizeComment(commentWS: CommentWhitespace) {\n const { comments } = commentWS;\n if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {\n if (commentWS.leadingNode !== null) {\n setTrailingComments(commentWS.leadingNode, comments);\n }\n if (commentWS.trailingNode !== null) {\n commentWS.trailingNode.leadingComments = comments;\n }\n } else {\n /*:: invariant(commentWS.containingNode !== null) */\n const { containingNode: node, start: commentStart } = commentWS;\n if (this.input.charCodeAt(commentStart - 1) === charCodes.comma) {\n // If a commentWhitespace follows a comma and the containingNode allows\n // list structures with trailing comma, merge it to the trailingComment\n // of the last non-null list element\n switch (node.type) {\n case \"ObjectExpression\":\n case \"ObjectPattern\":\n case \"RecordExpression\":\n adjustInnerComments(node, node.properties, commentWS);\n break;\n case \"CallExpression\":\n case \"OptionalCallExpression\":\n adjustInnerComments(node, node.arguments, commentWS);\n break;\n case \"FunctionDeclaration\":\n case \"FunctionExpression\":\n case \"ArrowFunctionExpression\":\n case \"ObjectMethod\":\n case \"ClassMethod\":\n case \"ClassPrivateMethod\":\n adjustInnerComments(node, node.params, commentWS);\n break;\n case \"ArrayExpression\":\n case \"ArrayPattern\":\n case \"TupleExpression\":\n adjustInnerComments(node, node.elements, commentWS);\n break;\n case \"ExportNamedDeclaration\":\n case \"ImportDeclaration\":\n adjustInnerComments(node, node.specifiers, commentWS);\n break;\n default: {\n setInnerComments(node, comments);\n }\n }\n } else {\n setInnerComments(node, comments);\n }\n }\n }\n\n /**\n * Drains remaning commentStack and applies finalizeComment\n * to each comment whitespace. Used only in parseExpression\n * where the top level AST node is _not_ Program\n * {@see {@link CommentsParser#finalizeComment}}\n *\n * @memberof CommentsParser\n */\n finalizeRemainingComments() {\n const { commentStack } = this.state;\n for (let i = commentStack.length - 1; i >= 0; i--) {\n this.finalizeComment(commentStack[i]);\n }\n this.state.commentStack = [];\n }\n\n /**\n * Reset previous node trailing comments. Used in object / class\n * property parsing. We parse `async`, `static`, `set` and `get`\n * as an identifier but may reinterepret it into an async/static/accessor\n * method later. In this case the identifier is not part of the AST and we\n * should sync the knowledge to commentStacks\n *\n * For example, when parsing */\n // async /* 1 */ function f() {}\n /*\n * the comment whitespace \"* 1 *\" has leading node Identifier(async). When\n * we see the function token, we create a Function node and mark \"* 1 *\" as\n * inner comments. So \"* 1 *\" should be detached from the Identifier node.\n *\n * @param {N.Node} node the last finished AST node _before_ current token\n * @returns\n * @memberof CommentsParser\n */\n resetPreviousNodeTrailingComments(node: Node) {\n const { commentStack } = this.state;\n const { length } = commentStack;\n if (length === 0) return;\n const commentWS = commentStack[length - 1];\n if (commentWS.leadingNode === node) {\n commentWS.leadingNode = null;\n }\n }\n}\n","// @flow\n\nexport const ErrorCodes = Object.freeze({\n SyntaxError: \"BABEL_PARSER_SYNTAX_ERROR\",\n SourceTypeModuleError: \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\",\n});\n\nexport type ErrorCode = $Values;\n","// @flow\n\nimport { makeErrorTemplates, ErrorCodes } from \"./error\";\n\n/* eslint sort-keys: \"error\" */\n\n/**\n * @module parser/error-message\n */\n\n// The Errors key follows https://cs.chromium.org/chromium/src/v8/src/common/message-template.h unless it does not exist\nexport const ErrorMessages = makeErrorTemplates(\n {\n AccessorIsGenerator: \"A %0ter cannot be a generator.\",\n ArgumentsInClass:\n \"'arguments' is only allowed in functions and class methods.\",\n AsyncFunctionInSingleStatementContext:\n \"Async functions can only be declared at the top level or inside a block.\",\n AwaitBindingIdentifier:\n \"Can not use 'await' as identifier inside an async function.\",\n AwaitBindingIdentifierInStaticBlock:\n \"Can not use 'await' as identifier inside a static block.\",\n AwaitExpressionFormalParameter:\n \"'await' is not allowed in async function parameters.\",\n AwaitNotInAsyncContext:\n \"'await' is only allowed within async functions and at the top levels of modules.\",\n AwaitNotInAsyncFunction: \"'await' is only allowed within async functions.\",\n BadGetterArity: \"A 'get' accesor must not have any formal parameters.\",\n BadSetterArity: \"A 'set' accesor must have exactly one formal parameter.\",\n BadSetterRestParameter:\n \"A 'set' accesor function argument must not be a rest parameter.\",\n ConstructorClassField: \"Classes may not have a field named 'constructor'.\",\n ConstructorClassPrivateField:\n \"Classes may not have a private field named '#constructor'.\",\n ConstructorIsAccessor: \"Class constructor may not be an accessor.\",\n ConstructorIsAsync: \"Constructor can't be an async function.\",\n ConstructorIsGenerator: \"Constructor can't be a generator.\",\n DeclarationMissingInitializer: \"'%0' require an initialization value.\",\n DecoratorBeforeExport:\n \"Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax.\",\n DecoratorConstructor:\n \"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?\",\n DecoratorExportClass:\n \"Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.\",\n DecoratorSemicolon: \"Decorators must not be followed by a semicolon.\",\n DecoratorStaticBlock: \"Decorators can't be used with a static block.\",\n DeletePrivateField: \"Deleting a private field is not allowed.\",\n DestructureNamedImport:\n \"ES2015 named imports do not destructure. Use another statement for destructuring after the import.\",\n DuplicateConstructor: \"Duplicate constructor in the same class.\",\n DuplicateDefaultExport: \"Only one default export allowed per module.\",\n DuplicateExport:\n \"`%0` has already been exported. Exported identifiers must be unique.\",\n DuplicateProto: \"Redefinition of __proto__ property.\",\n DuplicateRegExpFlags: \"Duplicate regular expression flag.\",\n ElementAfterRest: \"Rest element must be last element.\",\n EscapedCharNotAnIdentifier: \"Invalid Unicode escape.\",\n ExportBindingIsString:\n \"A string literal cannot be used as an exported binding without `from`.\\n- Did you mean `export { '%0' as '%1' } from 'some-module'`?\",\n ExportDefaultFromAsIdentifier:\n \"'from' is not allowed as an identifier after 'export default'.\",\n ForInOfLoopInitializer:\n \"'%0' loop variable declaration may not have an initializer.\",\n ForOfAsync: \"The left-hand side of a for-of loop may not be 'async'.\",\n ForOfLet: \"The left-hand side of a for-of loop may not start with 'let'.\",\n GeneratorInSingleStatementContext:\n \"Generators can only be declared at the top level or inside a block.\",\n IllegalBreakContinue: \"Unsyntactic %0.\",\n IllegalLanguageModeDirective:\n \"Illegal 'use strict' directive in function with non-simple parameter list.\",\n IllegalReturn: \"'return' outside of function.\",\n ImportBindingIsString:\n 'A string literal cannot be used as an imported binding.\\n- Did you mean `import { \"%0\" as foo }`?',\n ImportCallArgumentTrailingComma:\n \"Trailing comma is disallowed inside import(...) arguments.\",\n ImportCallArity: \"`import()` requires exactly %0.\",\n ImportCallNotNewExpression: \"Cannot use new with import(...).\",\n ImportCallSpreadArgument: \"`...` is not allowed in `import()`.\",\n InvalidBigIntLiteral: \"Invalid BigIntLiteral.\",\n InvalidCodePoint: \"Code point out of bounds.\",\n InvalidDecimal: \"Invalid decimal.\",\n InvalidDigit: \"Expected number in radix %0.\",\n InvalidEscapeSequence: \"Bad character escape sequence.\",\n InvalidEscapeSequenceTemplate: \"Invalid escape sequence in template.\",\n InvalidEscapedReservedWord: \"Escape sequence in keyword %0.\",\n InvalidIdentifier: \"Invalid identifier %0.\",\n InvalidLhs: \"Invalid left-hand side in %0.\",\n InvalidLhsBinding: \"Binding invalid left-hand side in %0.\",\n InvalidNumber: \"Invalid number.\",\n InvalidOrMissingExponent:\n \"Floating-point numbers require a valid exponent after the 'e'.\",\n InvalidOrUnexpectedToken: \"Unexpected character '%0'.\",\n InvalidParenthesizedAssignment: \"Invalid parenthesized assignment pattern.\",\n InvalidPrivateFieldResolution: \"Private name #%0 is not defined.\",\n InvalidPropertyBindingPattern: \"Binding member expression.\",\n InvalidRecordProperty:\n \"Only properties and spread elements are allowed in record definitions.\",\n InvalidRestAssignmentPattern: \"Invalid rest operator's argument.\",\n LabelRedeclaration: \"Label '%0' is already declared.\",\n LetInLexicalBinding:\n \"'let' is not allowed to be used as a name in 'let' or 'const' declarations.\",\n LineTerminatorBeforeArrow: \"No line break is allowed before '=>'.\",\n MalformedRegExpFlags: \"Invalid regular expression flag.\",\n MissingClassName: \"A class name is required.\",\n MissingEqInAssignment:\n \"Only '=' operator can be used for specifying default value.\",\n MissingSemicolon: \"Missing semicolon.\",\n MissingUnicodeEscape: \"Expecting Unicode escape sequence \\\\uXXXX.\",\n MixingCoalesceWithLogical:\n \"Nullish coalescing operator(??) requires parens when mixing with logical operators.\",\n ModuleAttributeDifferentFromType:\n \"The only accepted module attribute is `type`.\",\n ModuleAttributeInvalidValue:\n \"Only string literals are allowed as module attribute values.\",\n ModuleAttributesWithDuplicateKeys:\n 'Duplicate key \"%0\" is not allowed in module attributes.',\n ModuleExportNameHasLoneSurrogate:\n \"An export name cannot include a lone surrogate, found '\\\\u%0'.\",\n ModuleExportUndefined: \"Export '%0' is not defined.\",\n MultipleDefaultsInSwitch: \"Multiple default clauses.\",\n NewlineAfterThrow: \"Illegal newline after throw.\",\n NoCatchOrFinally: \"Missing catch or finally clause.\",\n NumberIdentifier: \"Identifier directly after number.\",\n NumericSeparatorInEscapeSequence:\n \"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.\",\n ObsoleteAwaitStar:\n \"'await*' has been removed from the async functions proposal. Use Promise.all() instead.\",\n OptionalChainingNoNew:\n \"Constructors in/after an Optional Chain are not allowed.\",\n OptionalChainingNoTemplate:\n \"Tagged Template Literals are not allowed in optionalChain.\",\n OverrideOnConstructor:\n \"'override' modifier cannot appear on a constructor declaration.\",\n ParamDupe: \"Argument name clash.\",\n PatternHasAccessor: \"Object pattern can't contain getter or setter.\",\n PatternHasMethod: \"Object pattern can't contain methods.\",\n PipeBodyIsTighter:\n \"Unexpected %0 after pipeline body; any %0 expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.\",\n PipeTopicRequiresHackPipes:\n 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n PipeTopicUnbound:\n \"Topic reference is unbound; it must be inside a pipe body.\",\n PipeTopicUnconfiguredToken:\n 'Invalid topic token %0. In order to use %0 as a topic reference, the pipelineOperator plugin must be configured with { \"proposal\": \"hack\", \"topicToken\": \"%0\" }.',\n PipeTopicUnused:\n \"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.\",\n\n // Messages whose codes start with “Pipeline” or “PrimaryTopic”\n // are retained for backwards compatibility\n // with the deprecated smart-mix pipe operator proposal plugin.\n // They are subject to removal in a future major version.\n PipelineBodyNoArrow:\n 'Unexpected arrow \"=>\" after pipeline body; arrow function in pipeline body must be parenthesized.',\n PipelineBodySequenceExpression:\n \"Pipeline body may not be a comma-separated sequence expression.\",\n PipelineHeadSequenceExpression:\n \"Pipeline head should not be a comma-separated sequence expression.\",\n PipelineTopicUnused:\n \"Pipeline is in topic style but does not use topic reference.\",\n PrimaryTopicNotAllowed:\n \"Topic reference was used in a lexical context without topic binding.\",\n PrimaryTopicRequiresSmartPipeline:\n 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n\n PrivateInExpectedIn:\n \"Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`).\",\n PrivateNameRedeclaration: \"Duplicate private name #%0.\",\n RecordExpressionBarIncorrectEndSyntaxType:\n \"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n RecordExpressionBarIncorrectStartSyntaxType:\n \"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n RecordExpressionHashIncorrectStartSyntaxType:\n \"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n RecordNoProto: \"'__proto__' is not allowed in Record expressions.\",\n RestTrailingComma: \"Unexpected trailing comma after rest element.\",\n SloppyFunction:\n \"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.\",\n StaticPrototype: \"Classes may not have static property named prototype.\",\n StrictDelete: \"Deleting local variable in strict mode.\",\n StrictEvalArguments: \"Assigning to '%0' in strict mode.\",\n StrictEvalArgumentsBinding: \"Binding '%0' in strict mode.\",\n StrictFunction:\n \"In strict mode code, functions can only be declared at top level or inside a block.\",\n StrictNumericEscape:\n \"The only valid numeric escape in strict mode is '\\\\0'.\",\n StrictOctalLiteral: \"Legacy octal literals are not allowed in strict mode.\",\n StrictWith: \"'with' in strict mode.\",\n SuperNotAllowed:\n \"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?\",\n SuperPrivateField: \"Private fields can't be accessed on super.\",\n TrailingDecorator: \"Decorators must be attached to a class element.\",\n TupleExpressionBarIncorrectEndSyntaxType:\n \"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n TupleExpressionBarIncorrectStartSyntaxType:\n \"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n TupleExpressionHashIncorrectStartSyntaxType:\n \"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n UnexpectedArgumentPlaceholder: \"Unexpected argument placeholder.\",\n UnexpectedAwaitAfterPipelineBody:\n 'Unexpected \"await\" after pipeline body; await must have parentheses in minimal proposal.',\n UnexpectedDigitAfterHash: \"Unexpected digit after hash token.\",\n UnexpectedImportExport:\n \"'import' and 'export' may only appear at the top level.\",\n UnexpectedKeyword: \"Unexpected keyword '%0'.\",\n UnexpectedLeadingDecorator:\n \"Leading decorators must be attached to a class declaration.\",\n UnexpectedLexicalDeclaration:\n \"Lexical declaration cannot appear in a single-statement context.\",\n UnexpectedNewTarget:\n \"`new.target` can only be used in functions or class properties.\",\n UnexpectedNumericSeparator:\n \"A numeric separator is only allowed between two digits.\",\n UnexpectedPrivateField:\n \"Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\\n or a property of member expression (i.e. this.#p).\",\n UnexpectedReservedWord: \"Unexpected reserved word '%0'.\",\n UnexpectedSuper: \"'super' is only allowed in object methods and classes.\",\n UnexpectedToken: \"Unexpected token '%0'.\",\n UnexpectedTokenUnaryExponentiation:\n \"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.\",\n UnsupportedBind: \"Binding should be performed on object property.\",\n UnsupportedDecoratorExport:\n \"A decorated export must export a class declaration.\",\n UnsupportedDefaultExport:\n \"Only expressions, functions or classes are allowed as the `default` export.\",\n UnsupportedImport:\n \"`import` can only be used in `import()` or `import.meta`.\",\n UnsupportedMetaProperty: \"The only valid meta property for %0 is %0.%1.\",\n UnsupportedParameterDecorator:\n \"Decorators cannot be used to decorate parameters.\",\n UnsupportedPropertyDecorator:\n \"Decorators cannot be used to decorate object literal properties.\",\n UnsupportedSuper:\n \"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).\",\n UnterminatedComment: \"Unterminated comment.\",\n UnterminatedRegExp: \"Unterminated regular expression.\",\n UnterminatedString: \"Unterminated string constant.\",\n UnterminatedTemplate: \"Unterminated template.\",\n VarRedeclaration: \"Identifier '%0' has already been declared.\",\n YieldBindingIdentifier:\n \"Can not use 'yield' as identifier inside a generator.\",\n YieldInParameter: \"Yield expression is not allowed in formal parameters.\",\n ZeroDigitNumericSeparator:\n \"Numeric separator can not be used after leading 0.\",\n },\n /* code */ ErrorCodes.SyntaxError,\n);\n\nexport const SourceTypeModuleErrorMessages = makeErrorTemplates(\n {\n ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: \"module\"'`,\n ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: \"module\"'`,\n },\n /* code */ ErrorCodes.SourceTypeModuleError,\n);\n","// @flow\n/* eslint sort-keys: \"error\" */\nimport { getLineInfo, type Position } from \"../util/location\";\nimport CommentsParser from \"./comments\";\nimport { type ErrorCode, ErrorCodes } from \"./error-codes\";\n\n// This function is used to raise exceptions on parse errors. It\n// takes an offset integer (into the current `input`) to indicate\n// the location of the error, attaches the position to the end\n// of the error message, and then raises a `SyntaxError` with that\n// message.\n\ntype ErrorContext = {\n pos: number,\n loc: Position,\n missingPlugin?: Array,\n code?: string,\n reasonCode?: String,\n};\nexport type ParsingError = SyntaxError & ErrorContext;\n\nexport type ErrorTemplate = {\n code: ErrorCode,\n template: string,\n reasonCode: string,\n};\nexport type ErrorTemplates = {\n [key: string]: ErrorTemplate,\n};\n\ntype SyntaxPlugin = \"flow\" | \"typescript\" | \"jsx\" | typeof undefined;\n\nfunction keepReasonCodeCompat(reasonCode: string, syntaxPlugin: SyntaxPlugin) {\n if (!process.env.BABEL_8_BREAKING) {\n // For consistency in TypeScript and Flow error codes\n if (syntaxPlugin === \"flow\" && reasonCode === \"PatternIsOptional\") {\n return \"OptionalBindingPattern\";\n }\n }\n return reasonCode;\n}\n\nexport function makeErrorTemplates(\n messages: {\n [key: string]: string,\n },\n code: ErrorCode,\n syntaxPlugin?: SyntaxPlugin,\n): ErrorTemplates {\n const templates: ErrorTemplates = {};\n Object.keys(messages).forEach(reasonCode => {\n templates[reasonCode] = Object.freeze({\n code,\n reasonCode: keepReasonCodeCompat(reasonCode, syntaxPlugin),\n template: messages[reasonCode],\n });\n });\n return Object.freeze(templates);\n}\n\nexport { ErrorCodes };\nexport {\n ErrorMessages as Errors,\n SourceTypeModuleErrorMessages as SourceTypeModuleErrors,\n} from \"./error-message\";\n\nexport type raiseFunction = (number, ErrorTemplate, ...any) => void;\n\nexport default class ParserError extends CommentsParser {\n // Forward-declaration: defined in tokenizer/index.js\n /*::\n +isLookahead: boolean;\n */\n\n getLocationForPosition(pos: number): Position {\n let loc;\n if (pos === this.state.start) loc = this.state.startLoc;\n else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;\n else if (pos === this.state.end) loc = this.state.endLoc;\n else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;\n else loc = getLineInfo(this.input, pos);\n\n return loc;\n }\n\n raise(\n pos: number,\n { code, reasonCode, template }: ErrorTemplate,\n ...params: any\n ): Error | empty {\n return this.raiseWithData(pos, { code, reasonCode }, template, ...params);\n }\n\n /**\n * Raise a parsing error on given position pos. If errorRecovery is true,\n * it will first search current errors and overwrite the error thrown on the exact\n * position before with the new error message. If errorRecovery is false, it\n * fallbacks to `raise`.\n *\n * @param {number} pos\n * @param {string} errorTemplate\n * @param {...any} params\n * @returns {(Error | empty)}\n * @memberof ParserError\n */\n raiseOverwrite(\n pos: number,\n { code, template }: ErrorTemplate,\n ...params: any\n ): Error | empty {\n const loc = this.getLocationForPosition(pos);\n const message =\n template.replace(/%(\\d+)/g, (_, i: number) => params[i]) +\n ` (${loc.line}:${loc.column})`;\n if (this.options.errorRecovery) {\n const errors = this.state.errors;\n for (let i = errors.length - 1; i >= 0; i--) {\n const error = errors[i];\n if (error.pos === pos) {\n return Object.assign(error, { message });\n } else if (error.pos < pos) {\n break;\n }\n }\n }\n return this._raise({ code, loc, pos }, message);\n }\n\n raiseWithData(\n pos: number,\n data?: {\n missingPlugin?: Array,\n code?: string,\n },\n errorTemplate: string,\n ...params: any\n ): Error | empty {\n const loc = this.getLocationForPosition(pos);\n const message =\n errorTemplate.replace(/%(\\d+)/g, (_, i: number) => params[i]) +\n ` (${loc.line}:${loc.column})`;\n return this._raise(Object.assign(({ loc, pos }: Object), data), message);\n }\n\n _raise(errorContext: ErrorContext, message: string): Error | empty {\n // $FlowIgnore\n const err: SyntaxError & ErrorContext = new SyntaxError(message);\n Object.assign(err, errorContext);\n if (this.options.errorRecovery) {\n if (!this.isLookahead) this.state.errors.push(err);\n return err;\n } else {\n throw err;\n }\n }\n}\n","// @flow\n\nimport { TokenType } from \"../tokenizer/types\";\nimport type Parser from \"../parser\";\nimport type { ExpressionErrors } from \"../parser/util\";\nimport * as N from \"../types\";\nimport type { Position } from \"../util/location\";\nimport { Errors } from \"../parser/error\";\n\nexport default (superClass: Class): Class =>\n class extends superClass {\n parseRegExpLiteral({ pattern, flags }): N.Node {\n let regex = null;\n try {\n regex = new RegExp(pattern, flags);\n } catch (e) {\n // In environments that don't support these flags value will\n // be null as the regex can't be represented natively.\n }\n const node = this.estreeParseLiteral(regex);\n node.regex = { pattern, flags };\n\n return node;\n }\n\n parseBigIntLiteral(value: any): N.Node {\n // https://github.com/estree/estree/blob/master/es2020.md#bigintliteral\n let bigInt;\n try {\n // $FlowIgnore\n bigInt = BigInt(value);\n } catch {\n bigInt = null;\n }\n const node = this.estreeParseLiteral(bigInt);\n node.bigint = String(node.value || value);\n\n return node;\n }\n\n parseDecimalLiteral(value: any): N.Node {\n // https://github.com/estree/estree/blob/master/experimental/decimal.md\n // todo: use BigDecimal when node supports it.\n const decimal = null;\n const node = this.estreeParseLiteral(decimal);\n node.decimal = String(node.value || value);\n\n return node;\n }\n\n estreeParseLiteral(value: any) {\n return this.parseLiteral(value, \"Literal\");\n }\n\n parseStringLiteral(value: any): N.Node {\n return this.estreeParseLiteral(value);\n }\n\n parseNumericLiteral(value: any): any {\n return this.estreeParseLiteral(value);\n }\n\n parseNullLiteral(): N.Node {\n return this.estreeParseLiteral(null);\n }\n\n parseBooleanLiteral(value: boolean): N.BooleanLiteral {\n return this.estreeParseLiteral(value);\n }\n\n directiveToStmt(directive: N.Directive): N.ExpressionStatement {\n const directiveLiteral = directive.value;\n\n const stmt = this.startNodeAt(directive.start, directive.loc.start);\n const expression = this.startNodeAt(\n directiveLiteral.start,\n directiveLiteral.loc.start,\n );\n\n expression.value = directiveLiteral.extra.expressionValue;\n expression.raw = directiveLiteral.extra.raw;\n\n stmt.expression = this.finishNodeAt(\n expression,\n \"Literal\",\n directiveLiteral.end,\n directiveLiteral.loc.end,\n );\n stmt.directive = directiveLiteral.extra.raw.slice(1, -1);\n\n return this.finishNodeAt(\n stmt,\n \"ExpressionStatement\",\n directive.end,\n directive.loc.end,\n );\n }\n\n // ==================================\n // Overrides\n // ==================================\n\n initFunction(\n node: N.BodilessFunctionOrMethodBase,\n isAsync: ?boolean,\n ): void {\n super.initFunction(node, isAsync);\n node.expression = false;\n }\n\n checkDeclaration(node: N.Pattern | N.ObjectProperty): void {\n if (node != null && this.isObjectProperty(node)) {\n this.checkDeclaration(((node: any): N.EstreeProperty).value);\n } else {\n super.checkDeclaration(node);\n }\n }\n\n getObjectOrClassMethodParams(method: N.ObjectMethod | N.ClassMethod) {\n return ((method: any): N.EstreeProperty | N.EstreeMethodDefinition).value\n .params;\n }\n\n isValidDirective(stmt: N.Statement): boolean {\n return (\n stmt.type === \"ExpressionStatement\" &&\n stmt.expression.type === \"Literal\" &&\n typeof stmt.expression.value === \"string\" &&\n !stmt.expression.extra?.parenthesized\n );\n }\n\n stmtToDirective(stmt: N.Statement): N.Directive {\n const value = stmt.expression.value;\n const directive = super.stmtToDirective(stmt);\n\n // Record the expression value as in estree mode we want\n // the stmt to have the real value e.g. (\"use strict\") and\n // not the raw value e.g. (\"use\\\\x20strict\")\n this.addExtra(directive.value, \"expressionValue\", value);\n\n return directive;\n }\n\n parseBlockBody(\n node: N.BlockStatementLike,\n ...args: [?boolean, boolean, TokenType, void | (boolean => void)]\n ): void {\n super.parseBlockBody(node, ...args);\n\n const directiveStatements = node.directives.map(d =>\n this.directiveToStmt(d),\n );\n node.body = directiveStatements.concat(node.body);\n // $FlowIgnore - directives isn't optional in the type definition\n delete node.directives;\n }\n\n pushClassMethod(\n classBody: N.ClassBody,\n method: N.ClassMethod,\n isGenerator: boolean,\n isAsync: boolean,\n isConstructor: boolean,\n allowsDirectSuper: boolean,\n ): void {\n this.parseMethod(\n method,\n isGenerator,\n isAsync,\n isConstructor,\n allowsDirectSuper,\n \"ClassMethod\",\n true,\n );\n if (method.typeParameters) {\n // $FlowIgnore\n method.value.typeParameters = method.typeParameters;\n delete method.typeParameters;\n }\n classBody.body.push(method);\n }\n\n parseMaybePrivateName(...args: [boolean]): any {\n const node = super.parseMaybePrivateName(...args);\n if (\n node.type === \"PrivateName\" &&\n this.getPluginOption(\"estree\", \"classFeatures\")\n ) {\n return this.convertPrivateNameToPrivateIdentifier(node);\n }\n return node;\n }\n\n convertPrivateNameToPrivateIdentifier(\n node: N.PrivateName,\n ): N.EstreePrivateIdentifier {\n const name = super.getPrivateNameSV(node);\n node = (node: any);\n delete node.id;\n node.name = name;\n node.type = \"PrivateIdentifier\";\n return node;\n }\n\n isPrivateName(node: N.Node): boolean {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return super.isPrivateName(node);\n }\n return node.type === \"PrivateIdentifier\";\n }\n\n getPrivateNameSV(node: N.Node): string {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return super.getPrivateNameSV(node);\n }\n return node.name;\n }\n\n parseLiteral(value: any, type: $ElementType): T {\n const node = super.parseLiteral(value, type);\n node.raw = node.extra.raw;\n delete node.extra;\n\n return node;\n }\n\n parseFunctionBody(\n node: N.Function,\n allowExpression: ?boolean,\n isMethod?: boolean = false,\n ): void {\n super.parseFunctionBody(node, allowExpression, isMethod);\n node.expression = node.body.type !== \"BlockStatement\";\n }\n\n parseMethod(\n node: T,\n isGenerator: boolean,\n isAsync: boolean,\n isConstructor: boolean,\n allowDirectSuper: boolean,\n type: string,\n inClassScope: boolean = false,\n ): T {\n let funcNode = this.startNode();\n funcNode.kind = node.kind; // provide kind, so super method correctly sets state\n funcNode = super.parseMethod(\n funcNode,\n isGenerator,\n isAsync,\n isConstructor,\n allowDirectSuper,\n type,\n inClassScope,\n );\n funcNode.type = \"FunctionExpression\";\n delete funcNode.kind;\n // $FlowIgnore\n node.value = funcNode;\n if (type === \"ClassPrivateMethod\") {\n // $FlowIgnore\n node.computed = false;\n }\n type = \"MethodDefinition\";\n return this.finishNode(node, type);\n }\n\n parseClassProperty(...args: [N.ClassProperty]): any {\n const propertyNode = (super.parseClassProperty(...args): any);\n if (this.getPluginOption(\"estree\", \"classFeatures\")) {\n propertyNode.type = \"PropertyDefinition\";\n }\n return (propertyNode: N.EstreePropertyDefinition);\n }\n\n parseClassPrivateProperty(...args: [N.ClassPrivateProperty]): any {\n const propertyNode = (super.parseClassPrivateProperty(...args): any);\n if (this.getPluginOption(\"estree\", \"classFeatures\")) {\n propertyNode.type = \"PropertyDefinition\";\n propertyNode.computed = false;\n }\n return (propertyNode: N.EstreePropertyDefinition);\n }\n\n parseObjectMethod(\n prop: N.ObjectMethod,\n isGenerator: boolean,\n isAsync: boolean,\n isPattern: boolean,\n isAccessor: boolean,\n ): ?N.ObjectMethod {\n const node: N.EstreeProperty = (super.parseObjectMethod(\n prop,\n isGenerator,\n isAsync,\n isPattern,\n isAccessor,\n ): any);\n\n if (node) {\n node.type = \"Property\";\n if (((node: any): N.ClassMethod).kind === \"method\") node.kind = \"init\";\n node.shorthand = false;\n }\n\n return (node: any);\n }\n\n parseObjectProperty(\n prop: N.ObjectProperty,\n startPos: ?number,\n startLoc: ?Position,\n isPattern: boolean,\n refExpressionErrors: ?ExpressionErrors,\n ): ?N.ObjectProperty {\n const node: N.EstreeProperty = (super.parseObjectProperty(\n prop,\n startPos,\n startLoc,\n isPattern,\n refExpressionErrors,\n ): any);\n\n if (node) {\n node.kind = \"init\";\n node.type = \"Property\";\n }\n\n return (node: any);\n }\n\n isAssignable(node: N.Node, isBinding?: boolean): boolean {\n if (node != null && this.isObjectProperty(node)) {\n return this.isAssignable(node.value, isBinding);\n }\n return super.isAssignable(node, isBinding);\n }\n\n toAssignable(node: N.Node, isLHS: boolean = false): N.Node {\n if (node != null && this.isObjectProperty(node)) {\n this.toAssignable(node.value, isLHS);\n\n return node;\n }\n\n return super.toAssignable(node, isLHS);\n }\n\n toAssignableObjectExpressionProp(prop: N.Node, ...args) {\n if (prop.kind === \"get\" || prop.kind === \"set\") {\n this.raise(prop.key.start, Errors.PatternHasAccessor);\n } else if (prop.method) {\n this.raise(prop.key.start, Errors.PatternHasMethod);\n } else {\n super.toAssignableObjectExpressionProp(prop, ...args);\n }\n }\n\n finishCallExpression(\n node: T,\n optional: boolean,\n ): N.Expression {\n super.finishCallExpression(node, optional);\n\n if (node.callee.type === \"Import\") {\n ((node: N.Node): N.EstreeImportExpression).type = \"ImportExpression\";\n ((node: N.Node): N.EstreeImportExpression).source = node.arguments[0];\n if (this.hasPlugin(\"importAssertions\")) {\n ((node: N.Node): N.EstreeImportExpression).attributes =\n node.arguments[1] ?? null;\n }\n // $FlowIgnore - arguments isn't optional in the type definition\n delete node.arguments;\n // $FlowIgnore - callee isn't optional in the type definition\n delete node.callee;\n }\n\n return node;\n }\n\n toReferencedArguments(\n node:\n | N.CallExpression\n | N.OptionalCallExpression\n | N.EstreeImportExpression,\n /* isParenthesizedExpr?: boolean, */\n ) {\n // ImportExpressions do not have an arguments array.\n if (node.type === \"ImportExpression\") {\n return;\n }\n\n super.toReferencedArguments(node);\n }\n\n parseExport(node: N.Node) {\n super.parseExport(node);\n\n switch (node.type) {\n case \"ExportAllDeclaration\":\n node.exported = null;\n break;\n\n case \"ExportNamedDeclaration\":\n if (\n node.specifiers.length === 1 &&\n node.specifiers[0].type === \"ExportNamespaceSpecifier\"\n ) {\n node.type = \"ExportAllDeclaration\";\n node.exported = node.specifiers[0].exported;\n delete node.specifiers;\n }\n\n break;\n }\n\n return node;\n }\n\n parseSubscript(\n base: N.Expression,\n startPos: number,\n startLoc: Position,\n noCalls: ?boolean,\n state: N.ParseSubscriptState,\n ) {\n const node = super.parseSubscript(\n base,\n startPos,\n startLoc,\n noCalls,\n state,\n );\n\n if (state.optionalChainMember) {\n // https://github.com/estree/estree/blob/master/es2020.md#chainexpression\n if (\n node.type === \"OptionalMemberExpression\" ||\n node.type === \"OptionalCallExpression\"\n ) {\n node.type = node.type.substring(8); // strip Optional prefix\n }\n if (state.stop) {\n const chain = this.startNodeAtNode(node);\n chain.expression = node;\n return this.finishNode(chain, \"ChainExpression\");\n }\n } else if (\n node.type === \"MemberExpression\" ||\n node.type === \"CallExpression\"\n ) {\n node.optional = false;\n }\n\n return node;\n }\n\n hasPropertyAsPrivateName(node: N.Node): boolean {\n if (node.type === \"ChainExpression\") {\n node = node.expression;\n }\n return super.hasPropertyAsPrivateName(node);\n }\n\n isOptionalChain(node: N.Node): boolean {\n return node.type === \"ChainExpression\";\n }\n\n isObjectProperty(node: N.Node): boolean {\n return node.type === \"Property\" && node.kind === \"init\" && !node.method;\n }\n\n isObjectMethod(node: N.Node): boolean {\n return node.method || node.kind === \"get\" || node.kind === \"set\";\n }\n };\n","// @flow\n\n// The token context is used to track whether the apostrophe \"`\"\n// starts or ends a string template\n\nimport { types as tt } from \"./types\";\n\nexport class TokContext {\n constructor(token: string, preserveSpace?: boolean) {\n this.token = token;\n this.preserveSpace = !!preserveSpace;\n }\n\n token: string;\n preserveSpace: boolean;\n}\n\nexport const types: {\n [key: string]: TokContext,\n} = {\n brace: new TokContext(\"{\"),\n template: new TokContext(\"`\", true),\n};\n\n// Token-specific context update code\n// Note that we should avoid accessing `this.prodParam` in context update,\n// because it is executed immediately when last token is consumed, which may be\n// before `this.prodParam` is updated. e.g.\n// ```\n// function *g() { () => yield / 2 }\n// ```\n// When `=>` is eaten, the context update of `yield` is executed, however,\n// `this.prodParam` still has `[Yield]` production because it is not yet updated\n\ntt.braceR.updateContext = context => {\n context.pop();\n};\n\n// we don't need to update context for tt.braceBarL because we do not pop context for tt.braceBarR\n// ideally only dollarBraceL \"${\" needs a non-template context\n// in order to indicate that the last \"`\" in `${`\" starts a new string template\n// inside a template element within outer string template.\n// but when we popped such context in `}`, we lost track of whether this\n// `}` matches a `${` or other tokens matching `}`, so we have to push\n// such context in every token that `}` will match.\ntt.braceL.updateContext =\n tt.braceHashL.updateContext =\n tt.dollarBraceL.updateContext =\n context => {\n context.push(types.brace);\n };\n\ntt.backQuote.updateContext = context => {\n if (context[context.length - 1] === types.template) {\n context.pop();\n } else {\n context.push(types.template);\n }\n};\n","import * as charCodes from \"charcodes\";\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point between 0x80 and 0xffff.\n// Generated by `scripts/generate-identifier-regex.js`.\n\n/* prettier-ignore */\nlet nonASCIIidentifierStartChars = \"\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u08a0-\\u08b4\\u08b6-\\u08c7\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d04-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e86-\\u0e8a\\u0e8c-\\u0ea3\\u0ea5\\u0ea7-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c88\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf3\\u1cf5\\u1cf6\\u1cfa\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31bf\\u31f0-\\u31ff\\u3400-\\u4dbf\\u4e00-\\u9ffc\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7bf\\ua7c2-\\ua7ca\\ua7f5-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab69\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\";\n/* prettier-ignore */\nlet nonASCIIidentifierChars = \"\\u200c\\u200d\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u08d3-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u09fe\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0afa-\\u0aff\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b55-\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c04\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0d00-\\u0d03\\u0d3b\\u0d3c\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d81-\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0ebc\\u0ec8-\\u0ecd\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u1810-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1abf\\u1ac0\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf4\\u1cf7-\\u1cf9\\u1dc0-\\u1df9\\u1dfb-\\u1dff\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua82c\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua8ff-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f\";\n\nconst nonASCIIidentifierStart = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + \"]\",\n);\nconst nonASCIIidentifier = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\",\n);\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset-encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by `scripts/generate-identifier-regex.js`.\n/* prettier-ignore */\n/* prettier-ignore */\nconst astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];\n/* prettier-ignore */\nconst astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code: number, set: readonly number[]): boolean {\n let pos = 0x10000;\n for (let i = 0, length = set.length; i < length; i += 2) {\n pos += set[i];\n if (pos > code) return false;\n\n pos += set[i + 1];\n if (pos >= code) return true;\n }\n return false;\n}\n\n// Test whether a given character code starts an identifier.\n\nexport function isIdentifierStart(code: number): boolean {\n if (code < charCodes.uppercaseA) return code === charCodes.dollarSign;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return (\n code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))\n );\n }\n return isInAstralSet(code, astralIdentifierStartCodes);\n}\n\n// Test whether a given character is part of an identifier.\n\nexport function isIdentifierChar(code: number): boolean {\n if (code < charCodes.digit0) return code === charCodes.dollarSign;\n if (code < charCodes.colon) return true;\n if (code < charCodes.uppercaseA) return false;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));\n }\n return (\n isInAstralSet(code, astralIdentifierStartCodes) ||\n isInAstralSet(code, astralIdentifierCodes)\n );\n}\n\n// Test whether a given string is a valid identifier name\n\nexport function isIdentifierName(name: string): boolean {\n let isFirst = true;\n for (let i = 0; i < name.length; i++) {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `name` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = name.charCodeAt(i);\n if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {\n const trail = name.charCodeAt(++i);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n if (isFirst) {\n isFirst = false;\n if (!isIdentifierStart(cp)) {\n return false;\n }\n } else if (!isIdentifierChar(cp)) {\n return false;\n }\n }\n return !isFirst;\n}\n","const reservedWords = {\n keyword: [\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n ],\n strict: [\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n ],\n strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n word: string,\n inModule: boolean,\n): boolean {\n return (\n isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n );\n}\n\nexport function isKeyword(word: string): boolean {\n return keywords.has(word);\n}\n","/* eslint max-len: 0 */\n\n// @flow\n\nimport * as charCodes from \"charcodes\";\n\nexport {\n isIdentifierStart,\n isIdentifierChar,\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"@babel/helper-validator-identifier\";\n\nexport const keywordRelationalOperator = /^in(stanceof)?$/;\n\n// Test whether a current state character code and next character code is @\n\nexport function isIteratorStart(current: number, next: number): boolean {\n return current === charCodes.atSign && next === charCodes.atSign;\n}\n\n// This is the comprehensive set of JavaScript reserved words\n// If a word is in this set, it could be a reserved word,\n// depending on sourceType/strictMode/binding info. In other words\n// if a word is not in this set, it is not a reserved word under\n// any circumstance.\nconst reservedWordLikeSet = new Set([\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n // strict\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n // strictBind\n \"eval\",\n \"arguments\",\n // reservedWorkLike\n \"enum\",\n \"await\",\n]);\n\nexport function canBeReservedWord(word: string): boolean {\n return reservedWordLikeSet.has(word);\n}\n","// @flow\n\n// Each scope gets a bitset that may contain these flags\n// prettier-ignore\nexport const SCOPE_OTHER = 0b000000000,\n SCOPE_PROGRAM = 0b000000001,\n SCOPE_FUNCTION = 0b000000010,\n SCOPE_ARROW = 0b000000100,\n SCOPE_SIMPLE_CATCH = 0b000001000,\n SCOPE_SUPER = 0b000010000,\n SCOPE_DIRECT_SUPER = 0b000100000,\n SCOPE_CLASS = 0b001000000,\n SCOPE_STATIC_BLOCK = 0b010000000,\n SCOPE_TS_MODULE = 0b100000000,\n SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;\n\nexport type ScopeFlags =\n | typeof SCOPE_OTHER\n | typeof SCOPE_PROGRAM\n | typeof SCOPE_FUNCTION\n | typeof SCOPE_VAR\n | typeof SCOPE_ARROW\n | typeof SCOPE_SIMPLE_CATCH\n | typeof SCOPE_SUPER\n | typeof SCOPE_DIRECT_SUPER\n | typeof SCOPE_CLASS\n | typeof SCOPE_STATIC_BLOCK;\n\n// These flags are meant to be _only_ used inside the Scope class (or subclasses).\n// prettier-ignore\nexport const BIND_KIND_VALUE = 0b000000_0000_01,\n BIND_KIND_TYPE = 0b000000_0000_10,\n // Used in checkLVal and declareName to determine the type of a binding\n BIND_SCOPE_VAR = 0b000000_0001_00, // Var-style binding\n BIND_SCOPE_LEXICAL = 0b000000_0010_00, // Let- or const-style binding\n BIND_SCOPE_FUNCTION = 0b000000_0100_00, // Function declaration\n BIND_SCOPE_OUTSIDE = 0b000000_1000_00, // Special case for function names as\n // bound inside the function\n // Misc flags\n BIND_FLAGS_NONE = 0b000001_0000_00,\n BIND_FLAGS_CLASS = 0b000010_0000_00,\n BIND_FLAGS_TS_ENUM = 0b000100_0000_00,\n BIND_FLAGS_TS_CONST_ENUM = 0b001000_0000_00,\n BIND_FLAGS_TS_EXPORT_ONLY = 0b010000_0000_00,\n BIND_FLAGS_FLOW_DECLARE_FN = 0b100000_0000_00;\n\n// These flags are meant to be _only_ used by Scope consumers\n// prettier-ignore\n/* = is value? | is type? | scope | misc flags */\nexport const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS ,\n BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0 ,\n BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0 ,\n BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0 ,\n BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS ,\n BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0 ,\n BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,\n BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,\n // These bindings don't introduce anything in the scope. They are used for assignments and\n // function expressions IDs.\n BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE ,\n BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE ,\n\n BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,\n BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,\n\n BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;\n\nexport type BindingTypes =\n | typeof BIND_NONE\n | typeof BIND_OUTSIDE\n | typeof BIND_VAR\n | typeof BIND_LEXICAL\n | typeof BIND_CLASS\n | typeof BIND_FUNCTION\n | typeof BIND_TS_INTERFACE\n | typeof BIND_TS_TYPE\n | typeof BIND_TS_ENUM\n | typeof BIND_TS_AMBIENT\n | typeof BIND_TS_NAMESPACE;\n\n// prettier-ignore\nexport const CLASS_ELEMENT_FLAG_STATIC = 0b1_00,\n CLASS_ELEMENT_KIND_GETTER = 0b0_10,\n CLASS_ELEMENT_KIND_SETTER = 0b0_01,\n CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;\n\n// prettier-ignore\nexport const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,\n CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,\n CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,\n CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,\n CLASS_ELEMENT_OTHER = 0;\n\nexport type ClassElementTypes =\n | typeof CLASS_ELEMENT_STATIC_GETTER\n | typeof CLASS_ELEMENT_STATIC_SETTER\n | typeof CLASS_ELEMENT_INSTANCE_GETTER\n | typeof CLASS_ELEMENT_INSTANCE_SETTER\n | typeof CLASS_ELEMENT_OTHER;\n","// @flow\nimport {\n SCOPE_ARROW,\n SCOPE_DIRECT_SUPER,\n SCOPE_FUNCTION,\n SCOPE_SIMPLE_CATCH,\n SCOPE_SUPER,\n SCOPE_PROGRAM,\n SCOPE_VAR,\n SCOPE_CLASS,\n SCOPE_STATIC_BLOCK,\n BIND_SCOPE_FUNCTION,\n BIND_SCOPE_VAR,\n BIND_SCOPE_LEXICAL,\n BIND_KIND_VALUE,\n type ScopeFlags,\n type BindingTypes,\n} from \"./scopeflags\";\nimport * as N from \"../types\";\nimport { Errors, type raiseFunction } from \"../parser/error\";\n\n// Start an AST node, attaching a start offset.\nexport class Scope {\n declare flags: ScopeFlags;\n // A set of var-declared names in the current lexical scope\n var: Set = new Set();\n // A set of lexically-declared names in the current lexical scope\n lexical: Set = new Set();\n // A set of lexically-declared FunctionDeclaration names in the current lexical scope\n functions: Set = new Set();\n\n constructor(flags: ScopeFlags) {\n this.flags = flags;\n }\n}\n\n// The functions in this module keep track of declared variables in the\n// current scope in order to detect duplicate variable names.\nexport default class ScopeHandler {\n scopeStack: Array = [];\n declare raise: raiseFunction;\n declare inModule: boolean;\n undefinedExports: Map = new Map();\n undefinedPrivateNames: Map = new Map();\n\n constructor(raise: raiseFunction, inModule: boolean) {\n this.raise = raise;\n this.inModule = inModule;\n }\n\n get inFunction() {\n return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;\n }\n get allowSuper() {\n return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;\n }\n get allowDirectSuper() {\n return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;\n }\n get inClass() {\n return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;\n }\n get inClassAndNotInNonArrowFunction() {\n const flags = this.currentThisScopeFlags();\n return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;\n }\n get inStaticBlock() {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & SCOPE_STATIC_BLOCK) {\n return true;\n }\n if (flags & (SCOPE_VAR | SCOPE_CLASS)) {\n // function body, module body, class property initializers\n return false;\n }\n }\n }\n get inNonArrowFunction() {\n return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0;\n }\n get treatFunctionsAsVar() {\n return this.treatFunctionsAsVarInScope(this.currentScope());\n }\n\n createScope(flags: ScopeFlags): Scope {\n return new Scope(flags);\n }\n // This method will be overwritten by subclasses\n /*:: +createScope: (flags: ScopeFlags) => IScope; */\n\n enter(flags: ScopeFlags) {\n this.scopeStack.push(this.createScope(flags));\n }\n\n exit() {\n this.scopeStack.pop();\n }\n\n // The spec says:\n // > At the top level of a function, or script, function declarations are\n // > treated like var declarations rather than like lexical declarations.\n treatFunctionsAsVarInScope(scope: IScope): boolean {\n return !!(\n scope.flags & SCOPE_FUNCTION ||\n (!this.inModule && scope.flags & SCOPE_PROGRAM)\n );\n }\n\n declareName(name: string, bindingType: BindingTypes, pos: number) {\n let scope = this.currentScope();\n if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {\n this.checkRedeclarationInScope(scope, name, bindingType, pos);\n\n if (bindingType & BIND_SCOPE_FUNCTION) {\n scope.functions.add(name);\n } else {\n scope.lexical.add(name);\n }\n\n if (bindingType & BIND_SCOPE_LEXICAL) {\n this.maybeExportDefined(scope, name);\n }\n } else if (bindingType & BIND_SCOPE_VAR) {\n for (let i = this.scopeStack.length - 1; i >= 0; --i) {\n scope = this.scopeStack[i];\n this.checkRedeclarationInScope(scope, name, bindingType, pos);\n scope.var.add(name);\n this.maybeExportDefined(scope, name);\n\n if (scope.flags & SCOPE_VAR) break;\n }\n }\n if (this.inModule && scope.flags & SCOPE_PROGRAM) {\n this.undefinedExports.delete(name);\n }\n }\n\n maybeExportDefined(scope: IScope, name: string) {\n if (this.inModule && scope.flags & SCOPE_PROGRAM) {\n this.undefinedExports.delete(name);\n }\n }\n\n checkRedeclarationInScope(\n scope: IScope,\n name: string,\n bindingType: BindingTypes,\n pos: number,\n ) {\n if (this.isRedeclaredInScope(scope, name, bindingType)) {\n this.raise(pos, Errors.VarRedeclaration, name);\n }\n }\n\n isRedeclaredInScope(\n scope: IScope,\n name: string,\n bindingType: BindingTypes,\n ): boolean {\n if (!(bindingType & BIND_KIND_VALUE)) return false;\n\n if (bindingType & BIND_SCOPE_LEXICAL) {\n return (\n scope.lexical.has(name) ||\n scope.functions.has(name) ||\n scope.var.has(name)\n );\n }\n\n if (bindingType & BIND_SCOPE_FUNCTION) {\n return (\n scope.lexical.has(name) ||\n (!this.treatFunctionsAsVarInScope(scope) && scope.var.has(name))\n );\n }\n\n return (\n (scope.lexical.has(name) &&\n !(\n scope.flags & SCOPE_SIMPLE_CATCH &&\n scope.lexical.values().next().value === name\n )) ||\n (!this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name))\n );\n }\n\n checkLocalExport(id: N.Identifier) {\n const { name } = id;\n const topLevelScope = this.scopeStack[0];\n if (\n !topLevelScope.lexical.has(name) &&\n !topLevelScope.var.has(name) &&\n // In strict mode, scope.functions will always be empty.\n // Modules are strict by default, but the `scriptMode` option\n // can overwrite this behavior.\n !topLevelScope.functions.has(name)\n ) {\n this.undefinedExports.set(name, id.start);\n }\n }\n\n currentScope(): IScope {\n return this.scopeStack[this.scopeStack.length - 1];\n }\n\n // $FlowIgnore\n currentVarScopeFlags(): ScopeFlags {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & SCOPE_VAR) {\n return flags;\n }\n }\n }\n\n // Could be useful for `arguments`, `this`, `new.target`, `super()`, `super.property`, and `super[property]`.\n // $FlowIgnore\n currentThisScopeFlags(): ScopeFlags {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {\n return flags;\n }\n }\n }\n}\n","// @flow\n\nimport ScopeHandler, { Scope } from \"../../util/scope\";\nimport {\n BIND_FLAGS_FLOW_DECLARE_FN,\n type ScopeFlags,\n type BindingTypes,\n} from \"../../util/scopeflags\";\nimport * as N from \"../../types\";\n\n// Reference implementation: https://github.com/facebook/flow/blob/23aeb2a2ef6eb4241ce178fde5d8f17c5f747fb5/src/typing/env.ml#L536-L584\nclass FlowScope extends Scope {\n // declare function foo(): type;\n declareFunctions: Set = new Set();\n}\n\nexport default class FlowScopeHandler extends ScopeHandler {\n createScope(flags: ScopeFlags): FlowScope {\n return new FlowScope(flags);\n }\n\n declareName(name: string, bindingType: BindingTypes, pos: number) {\n const scope = this.currentScope();\n if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {\n this.checkRedeclarationInScope(scope, name, bindingType, pos);\n this.maybeExportDefined(scope, name);\n scope.declareFunctions.add(name);\n return;\n }\n\n super.declareName(...arguments);\n }\n\n isRedeclaredInScope(\n scope: FlowScope,\n name: string,\n bindingType: BindingTypes,\n ): boolean {\n if (super.isRedeclaredInScope(...arguments)) return true;\n\n if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {\n return (\n !scope.declareFunctions.has(name) &&\n (scope.lexical.has(name) || scope.functions.has(name))\n );\n }\n\n return false;\n }\n\n checkLocalExport(id: N.Identifier) {\n if (!this.scopeStack[0].declareFunctions.has(id.name)) {\n super.checkLocalExport(id);\n }\n }\n}\n","// @flow\n\nimport type { Options } from \"../options\";\nimport * as N from \"../types\";\nimport type { CommentWhitespace } from \"../parser/comments\";\nimport { Position } from \"../util/location\";\n\nimport { types as ct, type TokContext } from \"./context\";\nimport { types as tt, type TokenType } from \"./types\";\nimport type { ParsingError, ErrorTemplate } from \"../parser/error\";\n\ntype TopicContextState = {\n // When a topic binding has been currently established,\n // then this is 1. Otherwise, it is 0. This is forwards compatible\n // with a future plugin for multiple lexical topics.\n maxNumOfResolvableTopics: number,\n\n // When a topic binding has been currently established, and if that binding\n // has been used as a topic reference `#`, then this is 0. Otherwise, it is\n // `null`. This is forwards compatible with a future plugin for multiple\n // lexical topics.\n maxTopicIndex: null | 0,\n};\n\nexport default class State {\n strict: boolean;\n curLine: number;\n\n // And, if locations are used, the {line, column} object\n // corresponding to those offsets\n startLoc: Position;\n endLoc: Position;\n\n init(options: Options): void {\n this.strict =\n options.strictMode === false\n ? false\n : options.strictMode === true\n ? true\n : options.sourceType === \"module\";\n\n this.curLine = options.startLine;\n this.startLoc = this.endLoc = this.curPosition();\n }\n\n errors: ParsingError[] = [];\n\n // Used to signify the start of a potential arrow function\n potentialArrowAt: number = -1;\n\n // Used to signify the start of an expression which looks like a\n // typed arrow function, but it isn't\n // e.g. a ? (b) : c => d\n // ^\n noArrowAt: number[] = [];\n\n // Used to signify the start of an expression whose params, if it looks like\n // an arrow function, shouldn't be converted to assignable nodes.\n // This is used to defer the validation of typed arrow functions inside\n // conditional expressions.\n // e.g. a ? (b) : c => d\n // ^\n noArrowParamsConversionAt: number[] = [];\n\n // Flags to track\n maybeInArrowParameters: boolean = false;\n inType: boolean = false;\n noAnonFunctionType: boolean = false;\n inPropertyName: boolean = false;\n hasFlowComment: boolean = false;\n isAmbientContext: boolean = false;\n inAbstractClass: boolean = false;\n\n // For the Hack-style pipelines plugin\n topicContext: TopicContextState = {\n maxNumOfResolvableTopics: 0,\n maxTopicIndex: null,\n };\n\n // For the F#-style pipelines plugin\n soloAwait: boolean = false;\n inFSharpPipelineDirectBody: boolean = false;\n\n // Labels in scope.\n labels: Array<{\n kind: ?(\"loop\" | \"switch\"),\n name?: ?string,\n statementStart?: number,\n }> = [];\n\n // Leading decorators. Last element of the stack represents the decorators in current context.\n // Supports nesting of decorators, e.g. @foo(@bar class inner {}) class outer {}\n // where @foo belongs to the outer class and @bar to the inner\n decoratorStack: Array> = [[]];\n\n // Comment store for Program.comments\n comments: Array = [];\n\n // Comment attachment store\n commentStack: Array = [];\n\n // The current position of the tokenizer in the input.\n pos: number = 0;\n lineStart: number = 0;\n\n // Properties of the current token:\n // Its type\n type: TokenType = tt.eof;\n\n // For tokens that include more information than their type, the value\n value: any = null;\n\n // Its start and end offset\n start: number = 0;\n end: number = 0;\n\n // Position information for the previous token\n // $FlowIgnore this is initialized when generating the second token.\n lastTokEndLoc: Position = null;\n // $FlowIgnore this is initialized when generating the second token.\n lastTokStartLoc: Position = null;\n lastTokStart: number = 0;\n lastTokEnd: number = 0;\n\n // The context stack is used to track whether the apostrophe \"`\" starts\n // or ends a string template\n context: Array = [ct.brace];\n // Used to track whether a JSX element is allowed to form\n exprAllowed: boolean = true;\n\n // Used to signal to callers of `readWord1` whether the word\n // contained any escape sequences. This is needed because words with\n // escape sequences must not be interpreted as keywords.\n containsEsc: boolean = false;\n\n // This property is used to track the following errors\n // - StrictNumericEscape\n // - StrictOctalLiteral\n //\n // in a literal that occurs prior to/immediately after a \"use strict\" directive.\n\n // todo(JLHwung): set strictErrors to null and avoid recording string errors\n // after a non-directive is parsed\n strictErrors: Map = new Map();\n\n // Tokens length in token store\n tokensLength: number = 0;\n\n curPosition(): Position {\n return new Position(this.curLine, this.pos - this.lineStart);\n }\n\n clone(skipArrays?: boolean): State {\n const state = new State();\n const keys = Object.keys(this);\n for (let i = 0, length = keys.length; i < length; i++) {\n const key = keys[i];\n // $FlowIgnore\n let val = this[key];\n\n if (!skipArrays && Array.isArray(val)) {\n val = val.slice();\n }\n\n // $FlowIgnore\n state[key] = val;\n }\n\n return state;\n }\n}\n\nexport type LookaheadState = {\n pos: number,\n value: any,\n type: TokenType,\n start: number,\n end: number,\n /* Used only in readToken_mult_modulo */\n inType: boolean,\n};\n","// @flow\n\n/*:: declare var invariant; */\n\nimport type { Options } from \"../options\";\nimport * as N from \"../types\";\nimport * as charCodes from \"charcodes\";\nimport { isIdentifierStart, isIdentifierChar } from \"../util/identifier\";\nimport { types as tt, keywords as keywordTypes, type TokenType } from \"./types\";\nimport { type TokContext, types as ct } from \"./context\";\nimport ParserErrors, { Errors, type ErrorTemplate } from \"../parser/error\";\nimport { SourceLocation } from \"../util/location\";\nimport {\n lineBreakG,\n isNewLine,\n isWhitespace,\n skipWhiteSpace,\n} from \"../util/whitespace\";\nimport State from \"./state\";\nimport type { LookaheadState } from \"./state\";\n\nconst VALID_REGEX_FLAGS = new Set([\n charCodes.lowercaseG,\n charCodes.lowercaseM,\n charCodes.lowercaseS,\n charCodes.lowercaseI,\n charCodes.lowercaseY,\n charCodes.lowercaseU,\n charCodes.lowercaseD,\n]);\n\n// The following character codes are forbidden from being\n// an immediate sibling of NumericLiteralSeparator _\n\nconst forbiddenNumericSeparatorSiblings = {\n decBinOct: [\n charCodes.dot,\n charCodes.uppercaseB,\n charCodes.uppercaseE,\n charCodes.uppercaseO,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseB,\n charCodes.lowercaseE,\n charCodes.lowercaseO,\n ],\n hex: [\n charCodes.dot,\n charCodes.uppercaseX,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseX,\n ],\n};\n\nconst allowedNumericSeparatorSiblings = {};\nallowedNumericSeparatorSiblings.bin = [\n // 0 - 1\n charCodes.digit0,\n charCodes.digit1,\n];\nallowedNumericSeparatorSiblings.oct = [\n // 0 - 7\n ...allowedNumericSeparatorSiblings.bin,\n\n charCodes.digit2,\n charCodes.digit3,\n charCodes.digit4,\n charCodes.digit5,\n charCodes.digit6,\n charCodes.digit7,\n];\nallowedNumericSeparatorSiblings.dec = [\n // 0 - 9\n ...allowedNumericSeparatorSiblings.oct,\n\n charCodes.digit8,\n charCodes.digit9,\n];\n\nallowedNumericSeparatorSiblings.hex = [\n // 0 - 9, A - F, a - f,\n ...allowedNumericSeparatorSiblings.dec,\n\n charCodes.uppercaseA,\n charCodes.uppercaseB,\n charCodes.uppercaseC,\n charCodes.uppercaseD,\n charCodes.uppercaseE,\n charCodes.uppercaseF,\n\n charCodes.lowercaseA,\n charCodes.lowercaseB,\n charCodes.lowercaseC,\n charCodes.lowercaseD,\n charCodes.lowercaseE,\n charCodes.lowercaseF,\n];\n\n// Object type used to represent tokens. Note that normally, tokens\n// simply exist as properties on the parser object. This is only\n// used for the onToken callback and the external tokenizer.\n\nexport class Token {\n constructor(state: State) {\n this.type = state.type;\n this.value = state.value;\n this.start = state.start;\n this.end = state.end;\n this.loc = new SourceLocation(state.startLoc, state.endLoc);\n }\n\n declare type: TokenType;\n declare value: any;\n declare start: number;\n declare end: number;\n declare loc: SourceLocation;\n}\n\n// ## Tokenizer\n\nexport default class Tokenizer extends ParserErrors {\n // Forward-declarations\n // parser/util.js\n /*::\n +hasPrecedingLineBreak: () => boolean;\n +unexpected: (pos?: ?number, messageOrType?: ErrorTemplate | TokenType) => empty;\n +expectPlugin: (name: string, pos?: ?number) => true;\n */\n\n isLookahead: boolean;\n\n // Token store.\n tokens: Array = [];\n\n constructor(options: Options, input: string) {\n super();\n this.state = new State();\n this.state.init(options);\n this.input = input;\n this.length = input.length;\n this.isLookahead = false;\n }\n\n pushToken(token: Token | N.Comment) {\n // Pop out invalid tokens trapped by try-catch parsing.\n // Those parsing branches are mainly created by typescript and flow plugins.\n this.tokens.length = this.state.tokensLength;\n this.tokens.push(token);\n ++this.state.tokensLength;\n }\n\n // Move to the next token\n\n next(): void {\n this.checkKeywordEscapes();\n if (this.options.tokens) {\n this.pushToken(new Token(this.state));\n }\n\n this.state.lastTokEnd = this.state.end;\n this.state.lastTokStart = this.state.start;\n this.state.lastTokEndLoc = this.state.endLoc;\n this.state.lastTokStartLoc = this.state.startLoc;\n this.nextToken();\n }\n\n // TODO\n\n eat(type: TokenType): boolean {\n if (this.match(type)) {\n this.next();\n return true;\n } else {\n return false;\n }\n }\n\n // TODO\n\n match(type: TokenType): boolean {\n return this.state.type === type;\n }\n\n /**\n * Create a LookaheadState from current parser state\n *\n * @param {State} state\n * @returns {LookaheadState}\n * @memberof Tokenizer\n */\n createLookaheadState(state: State): LookaheadState {\n return {\n pos: state.pos,\n value: null,\n type: state.type,\n start: state.start,\n end: state.end,\n lastTokEnd: state.end,\n context: [this.curContext()],\n inType: state.inType,\n };\n }\n\n /**\n * lookahead peeks the next token, skipping changes to token context and\n * comment stack. For performance it returns a limited LookaheadState\n * instead of full parser state.\n *\n * The { column, line } Loc info is not included in lookahead since such usage\n * is rare. Although it may return other location properties e.g. `curLine` and\n * `lineStart`, these properties are not listed in the LookaheadState interface\n * and thus the returned value is _NOT_ reliable.\n *\n * The tokenizer should make best efforts to avoid using any parser state\n * other than those defined in LookaheadState\n *\n * @returns {LookaheadState}\n * @memberof Tokenizer\n */\n lookahead(): LookaheadState {\n const old = this.state;\n // For performance we use a simpified tokenizer state structure\n // $FlowIgnore\n this.state = this.createLookaheadState(old);\n\n this.isLookahead = true;\n this.nextToken();\n this.isLookahead = false;\n\n const curr = this.state;\n this.state = old;\n return curr;\n }\n\n nextTokenStart(): number {\n return this.nextTokenStartSince(this.state.pos);\n }\n\n nextTokenStartSince(pos: number): number {\n skipWhiteSpace.lastIndex = pos;\n return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;\n }\n\n lookaheadCharCode(): number {\n return this.input.charCodeAt(this.nextTokenStart());\n }\n\n codePointAtPos(pos: number): number {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `input` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = this.input.charCodeAt(pos);\n if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {\n const trail = this.input.charCodeAt(pos);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n return cp;\n }\n\n // Toggle strict mode. Re-reads the next number or string to please\n // pedantic tests (`\"use strict\"; 010;` should fail).\n\n setStrict(strict: boolean): void {\n this.state.strict = strict;\n if (strict) {\n // Throw an error for any string decimal escape found before/immediately\n // after a \"use strict\" directive. Strict mode will be set at parse\n // time for any literals that occur after the next node of the strict\n // directive.\n this.state.strictErrors.forEach((message, pos) =>\n /* eslint-disable @babel/development-internal/dry-error-messages */\n this.raise(pos, message),\n );\n this.state.strictErrors.clear();\n }\n }\n\n curContext(): TokContext {\n return this.state.context[this.state.context.length - 1];\n }\n\n // Read a single token, updating the parser object's token-related\n // properties.\n\n nextToken(): void {\n const curContext = this.curContext();\n if (!curContext.preserveSpace) this.skipSpace();\n this.state.start = this.state.pos;\n if (!this.isLookahead) this.state.startLoc = this.state.curPosition();\n if (this.state.pos >= this.length) {\n this.finishToken(tt.eof);\n return;\n }\n\n if (curContext === ct.template) {\n this.readTmplToken();\n } else {\n this.getTokenFromCode(this.codePointAtPos(this.state.pos));\n }\n }\n\n skipBlockComment(): N.CommentBlock | void {\n let startLoc;\n if (!this.isLookahead) startLoc = this.state.curPosition();\n const start = this.state.pos;\n const end = this.input.indexOf(\"*/\", start + 2);\n if (end === -1) throw this.raise(start, Errors.UnterminatedComment);\n\n this.state.pos = end + 2;\n lineBreakG.lastIndex = start + 2;\n while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {\n ++this.state.curLine;\n this.state.lineStart = lineBreakG.lastIndex;\n }\n\n // If we are doing a lookahead right now we need to advance the position (above code)\n // but we do not want to push the comment to the state.\n if (this.isLookahead) return;\n /*:: invariant(startLoc) */\n\n const comment = {\n type: \"CommentBlock\",\n value: this.input.slice(start + 2, end),\n start,\n end: end + 2,\n loc: new SourceLocation(startLoc, this.state.curPosition()),\n };\n if (this.options.tokens) this.pushToken(comment);\n return comment;\n }\n\n skipLineComment(startSkip: number): N.CommentLine | void {\n const start = this.state.pos;\n let startLoc;\n if (!this.isLookahead) startLoc = this.state.curPosition();\n let ch = this.input.charCodeAt((this.state.pos += startSkip));\n if (this.state.pos < this.length) {\n while (!isNewLine(ch) && ++this.state.pos < this.length) {\n ch = this.input.charCodeAt(this.state.pos);\n }\n }\n\n // If we are doing a lookahead right now we need to advance the position (above code)\n // but we do not want to push the comment to the state.\n if (this.isLookahead) return;\n /*:: invariant(startLoc) */\n\n const end = this.state.pos;\n const value = this.input.slice(start + startSkip, end);\n\n const comment = {\n type: \"CommentLine\",\n value,\n start,\n end,\n loc: new SourceLocation(startLoc, this.state.curPosition()),\n };\n if (this.options.tokens) this.pushToken(comment);\n return comment;\n }\n\n // Called at the start of the parse and after every token. Skips\n // whitespace and comments, and.\n\n skipSpace(): void {\n const spaceStart = this.state.pos;\n const comments = [];\n loop: while (this.state.pos < this.length) {\n const ch = this.input.charCodeAt(this.state.pos);\n switch (ch) {\n case charCodes.space:\n case charCodes.nonBreakingSpace:\n case charCodes.tab:\n ++this.state.pos;\n break;\n case charCodes.carriageReturn:\n if (\n this.input.charCodeAt(this.state.pos + 1) === charCodes.lineFeed\n ) {\n ++this.state.pos;\n }\n // fall through\n case charCodes.lineFeed:\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n ++this.state.pos;\n ++this.state.curLine;\n this.state.lineStart = this.state.pos;\n break;\n\n case charCodes.slash:\n switch (this.input.charCodeAt(this.state.pos + 1)) {\n case charCodes.asterisk: {\n const comment = this.skipBlockComment();\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n break;\n }\n\n case charCodes.slash: {\n const comment = this.skipLineComment(2);\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n break;\n }\n\n default:\n break loop;\n }\n break;\n\n default:\n if (isWhitespace(ch)) {\n ++this.state.pos;\n } else if (ch === charCodes.dash && !this.inModule) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.dash &&\n this.input.charCodeAt(pos + 2) === charCodes.greaterThan &&\n (spaceStart === 0 || this.state.lineStart > spaceStart)\n ) {\n // A `-->` line comment\n const comment = this.skipLineComment(3);\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n } else {\n break loop;\n }\n } else if (ch === charCodes.lessThan && !this.inModule) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.exclamationMark &&\n this.input.charCodeAt(pos + 2) === charCodes.dash &&\n this.input.charCodeAt(pos + 3) === charCodes.dash\n ) {\n // ` + +> This module contains methods for building ASTs manually and for checking the types of AST nodes. + +## Install + +\`\`\`sh +npm install --save-dev @babel/types +\`\`\` + +## API`, +]; + +const customTypes = { + ClassMethod: { + key: "if computed then `Expression` else `Identifier | Literal`", + }, + Identifier: { + name: "`string`", + }, + MemberExpression: { + property: "if computed then `Expression` else `Identifier`", + }, + ObjectMethod: { + key: "if computed then `Expression` else `Identifier | Literal`", + }, + ObjectProperty: { + key: "if computed then `Expression` else `Identifier | Literal`", + }, + ClassPrivateMethod: { + computed: "'false'", + }, + ClassPrivateProperty: { + computed: "'false'", + }, +}; +const APIHistory = { + ClassProperty: [["v7.6.0", "Supports `static`"]], +}; +function formatHistory(historyItems) { + const lines = historyItems.map( + item => "| `" + item[0] + "` | " + item[1] + " |" + ); + return [ + "
", + " History", + "| Version | Changes |", + "| --- | --- |", + ...lines, + "
", + ]; +} +function printAPIHistory(key, readme) { + if (APIHistory[key]) { + readme.push(""); + readme.push(...formatHistory(APIHistory[key])); + } +} +function printNodeFields(key, readme) { + if (Object.keys(t.NODE_FIELDS[key]).length > 0) { + readme.push(""); + readme.push("AST Node `" + key + "` shape:"); + Object.keys(t.NODE_FIELDS[key]) + .sort(function (fieldA, fieldB) { + const indexA = t.BUILDER_KEYS[key].indexOf(fieldA); + const indexB = t.BUILDER_KEYS[key].indexOf(fieldB); + if (indexA === indexB) return fieldA < fieldB ? -1 : 1; + if (indexA === -1) return 1; + if (indexB === -1) return -1; + return indexA - indexB; + }) + .forEach(function (field) { + const defaultValue = t.NODE_FIELDS[key][field].default; + const fieldDescription = ["`" + field + "`"]; + const validator = t.NODE_FIELDS[key][field].validate; + if (customTypes[key] && customTypes[key][field]) { + fieldDescription.push(`: ${customTypes[key][field]}`); + } else if (validator) { + try { + fieldDescription.push( + ": `" + stringifyValidator(validator, "") + "`" + ); + } catch (ex) { + if (ex.code === "UNEXPECTED_VALIDATOR_TYPE") { + console.log( + "Unrecognised validator type for " + key + "." + field + ); + console.dir(ex.validator, { depth: 10, colors: true }); + } + } + } + if (defaultValue !== null || t.NODE_FIELDS[key][field].optional) { + fieldDescription.push( + " (default: `" + util.inspect(defaultValue) + "`" + ); + if (t.BUILDER_KEYS[key].indexOf(field) < 0) { + fieldDescription.push(", excluded from builder function"); + } + fieldDescription.push(")"); + } else { + fieldDescription.push(" (required)"); + } + readme.push("- " + fieldDescription.join("")); + }); + } +} + +function printAliasKeys(key, readme) { + if (t.ALIAS_KEYS[key] && t.ALIAS_KEYS[key].length) { + readme.push(""); + readme.push( + "Aliases: " + + t.ALIAS_KEYS[key] + .map(function (key) { + return "[`" + key + "`](#" + key.toLowerCase() + ")"; + }) + .join(", ") + ); + } +} +readme.push("### Node Builders"); +readme.push(""); +Object.keys(t.BUILDER_KEYS) + .sort() + .forEach(function (key) { + readme.push("#### " + toFunctionName(key)); + readme.push(""); + readme.push("```javascript"); + readme.push( + "t." + toFunctionName(key) + "(" + t.BUILDER_KEYS[key].join(", ") + ");" + ); + readme.push("```"); + printAPIHistory(key, readme); + readme.push(""); + readme.push( + "See also `t.is" + + key + + "(node, opts)` and `t.assert" + + key + + "(node, opts)`." + ); + + printNodeFields(key, readme); + printAliasKeys(key, readme); + + readme.push(""); + readme.push("---"); + readme.push(""); + }); + +function generateMapAliasToNodeTypes() { + const result = new Map(); + for (const nodeType of Object.keys(t.ALIAS_KEYS)) { + const aliases = t.ALIAS_KEYS[nodeType]; + if (!aliases) continue; + for (const alias of aliases) { + if (!result.has(alias)) { + result.set(alias, []); + } + const nodeTypes = result.get(alias); + nodeTypes.push(nodeType); + } + } + return result; +} +const aliasDescriptions = { + Binary: + "A cover of BinaryExpression and LogicalExpression, which share the same AST shape.", + Block: "Deprecated. Will be removed in Babel 8.", + BlockParent: + "A cover of AST nodes that start an execution context with new [LexicalEnvironment](https://tc39.es/ecma262/#table-additional-state-components-for-ecmascript-code-execution-contexts). In other words, they define the scope of `let` and `const` declarations.", + Class: + "A cover of ClassExpression and ClassDeclaration, which share the same AST shape.", + CompletionStatement: + "A statement that indicates the [completion records](https://tc39.es/ecma262/#sec-completion-record-specification-type). In other words, they define the control flow of the program, such as when should a loop break or an action throws critical errors.", + Conditional: + "A cover of ConditionalExpression and IfStatement, which share the same AST shape.", + Declaration: + "A cover of any [Declaration](https://tc39.es/ecma262/#prod-Declaration)s.", + EnumBody: "A cover of Flow enum bodies.", + EnumMember: "A cover of Flow enum membors.", + ExportDeclaration: + "A cover of any [ExportDeclaration](https://tc39.es/ecma262/#prod-ExportDeclaration)s.", + Expression: + "A cover of any [Expression](https://tc39.es/ecma262/#sec-ecmascript-language-expressions)s.", + ExpressionWrapper: + "A wrapper of expression that does not have runtime semantics.", + Flow: "A cover of AST nodes defined for Flow.", + FlowBaseAnnotation: "A cover of primary Flow type annotations.", + FlowDeclaration: "A cover of Flow declarations.", + FlowPredicate: "A cover of Flow predicates.", + FlowType: "A cover of Flow type annotations.", + For: "A cover of [ForStatement](https://tc39.es/ecma262/#sec-for-statement)s and [ForXStatement](#forxstatement)s.", + ForXStatement: + "A cover of [ForInStatements and ForOfStatements](https://tc39.es/ecma262/#sec-for-in-and-for-of-statements).", + Function: + "A cover of functions and [method](#method)s, the must have `body` and `params`. Note: `Function` is different to `FunctionParent`.", + FunctionParent: + "A cover of AST nodes that start an execution context with new [VariableEnvironment](https://tc39.es/ecma262/#table-additional-state-components-for-ecmascript-code-execution-contexts). In other words, they define the scope of `var` declarations. FunctionParent did not include `Program` since Babel 7.", + Immutable: + "A cover of immutable objects and JSX elements. An object is [immutable](https://tc39.es/ecma262/#immutable-prototype-exotic-object) if no other properties can be defined once created.", + JSX: "A cover of AST nodes defined for [JSX](https://facebook.github.io/jsx/).", + LVal: "A cover of left hand side expressions used in the `left` of assignment expressions and [ForXStatement](#forxstatement)s. ", + Literal: + "A cover of [Literal](https://tc39.es/ecma262/#sec-primary-expression-literals)s, [Regular Expression Literal](https://tc39.es/ecma262/#sec-primary-expression-regular-expression-literals)s and [Template Literal](https://tc39.es/ecma262/#sec-template-literals)s.", + Loop: "A cover of loop statements.", + Method: "A cover of object methods and class methods.", + ModuleDeclaration: + "A cover of ImportDeclaration and [ExportDeclaration](#exportdeclaration)", + ModuleSpecifier: + "A cover of import and export specifiers. Note: It is _not_ the [ModuleSpecifier](https://tc39.es/ecma262/#prod-ModuleSpecifier) defined in the spec.", + ObjectMember: + "A cover of [members](https://tc39.es/ecma262/#prod-PropertyDefinitionList) in an object literal.", + Pattern: + "A cover of [BindingPattern](https://tc39.es/ecma262/#prod-BindingPattern) except Identifiers.", + PatternLike: + "A cover of [BindingPattern](https://tc39.es/ecma262/#prod-BindingPattern)s. ", + Private: "A cover of private class elements and private identifiers.", + Property: "A cover of object properties and class properties.", + Pureish: + "A cover of AST nodes which do not have side-effects. In other words, there is no observable behaviour changes if they are evaluated more than once.", + Scopable: + "A cover of [FunctionParent](#functionparent) and [BlockParent](#blockparent).", + Statement: + "A cover of any [Statement](https://tc39.es/ecma262/#prod-Statement)s.", + TSBaseType: "A cover of primary TypeScript type annotations.", + TSEntityName: "A cover of ts entities.", + TSType: "A cover of TypeScript type annotations.", + TSTypeElement: "A cover of TypeScript type declarations.", + Terminatorless: + "A cover of AST nodes whose semantic will change when a line terminator is inserted between the operator and the operand.", + UnaryLike: "A cover of UnaryExpression and SpreadElement.", + UserWhitespacable: "Deprecated. Will be removed in Babel 8.", + While: + "A cover of DoWhileStatement and WhileStatement, which share the same AST shape.", +}; +const mapAliasToNodeTypes = generateMapAliasToNodeTypes(); +readme.push("### Aliases"); +readme.push(""); +for (const alias of [...mapAliasToNodeTypes.keys()].sort()) { + const nodeTypes = mapAliasToNodeTypes.get(alias); + nodeTypes.sort(); + if (!(alias in aliasDescriptions)) { + throw new Error( + 'Missing alias descriptions of "' + + alias + + ", which covers " + + nodeTypes.join(",") + ); + } + readme.push("#### " + alias); + readme.push(""); + readme.push(aliasDescriptions[alias]); + readme.push("```javascript"); + readme.push("t.is" + alias + "(node);"); + readme.push("```"); + readme.push(""); + readme.push("Covered nodes: "); + for (const nodeType of nodeTypes) { + readme.push("- [`" + nodeType + "`](#" + nodeType.toLowerCase() + ")"); + } + readme.push(""); +} + +process.stdout.write(readme.join("\n")); diff --git a/node_modules/@babel/types/scripts/generators/flow.js b/node_modules/@babel/types/scripts/generators/flow.js new file mode 100644 index 0000000..7fabcc6 --- /dev/null +++ b/node_modules/@babel/types/scripts/generators/flow.js @@ -0,0 +1,260 @@ +import t from "../../lib/index.js"; +import stringifyValidator from "../utils/stringifyValidator.js"; +import toFunctionName from "../utils/toFunctionName.js"; + +const NODE_PREFIX = "BabelNode"; + +let code = `// NOTE: This file is autogenerated. Do not modify. +// See packages/babel-types/scripts/generators/flow.js for script used. + +declare class ${NODE_PREFIX}Comment { + value: string; + start: number; + end: number; + loc: ${NODE_PREFIX}SourceLocation; +} + +declare class ${NODE_PREFIX}CommentBlock extends ${NODE_PREFIX}Comment { + type: "CommentBlock"; +} + +declare class ${NODE_PREFIX}CommentLine extends ${NODE_PREFIX}Comment { + type: "CommentLine"; +} + +declare class ${NODE_PREFIX}SourceLocation { + start: { + line: number; + column: number; + }; + + end: { + line: number; + column: number; + }; +} + +declare class ${NODE_PREFIX} { + leadingComments?: Array<${NODE_PREFIX}Comment>; + innerComments?: Array<${NODE_PREFIX}Comment>; + trailingComments?: Array<${NODE_PREFIX}Comment>; + start: ?number; + end: ?number; + loc: ?${NODE_PREFIX}SourceLocation; + extra?: { [string]: mixed }; +}\n\n`; + +// + +const lines = []; + +for (const type in t.NODE_FIELDS) { + const fields = t.NODE_FIELDS[type]; + + const struct = ['type: "' + type + '";']; + const args = []; + const builderNames = t.BUILDER_KEYS[type]; + + Object.keys(t.NODE_FIELDS[type]) + .sort((fieldA, fieldB) => { + const indexA = t.BUILDER_KEYS[type].indexOf(fieldA); + const indexB = t.BUILDER_KEYS[type].indexOf(fieldB); + if (indexA === indexB) return fieldA < fieldB ? -1 : 1; + if (indexA === -1) return 1; + if (indexB === -1) return -1; + return indexA - indexB; + }) + .forEach(fieldName => { + const field = fields[fieldName]; + + let suffix = ""; + if (field.optional || field.default != null) suffix += "?"; + + let typeAnnotation = "any"; + + const validate = field.validate; + if (validate) { + typeAnnotation = stringifyValidator(validate, NODE_PREFIX); + } + + if (typeAnnotation) { + suffix += ": " + typeAnnotation; + } + if (builderNames.includes(fieldName)) { + args.push(t.toBindingIdentifierName(fieldName) + suffix); + } + + if (t.isValidIdentifier(fieldName)) { + struct.push(fieldName + suffix + ";"); + } + }); + + code += `declare class ${NODE_PREFIX}${type} extends ${NODE_PREFIX} { + ${struct.join("\n ").trim()} +}\n\n`; + + // Flow chokes on super() and import() :/ + if (type !== "Super" && type !== "Import") { + lines.push( + `declare export function ${toFunctionName(type)}(${args.join( + ", " + )}): ${NODE_PREFIX}${type};` + ); + } else { + const functionName = toFunctionName(type); + lines.push( + `declare function _${functionName}(${args.join( + ", " + )}): ${NODE_PREFIX}${type};`, + `declare export { _${functionName} as ${functionName} }` + ); + } +} + +for (const typeName of t.TYPES) { + const isDeprecated = !!t.DEPRECATED_KEYS[typeName]; + const realName = isDeprecated ? t.DEPRECATED_KEYS[typeName] : typeName; + + let decl = `declare export function is${typeName}(node: ?Object, opts?: ?Object): boolean`; + if (t.NODE_FIELDS[realName]) { + decl += ` %checks (node instanceof ${NODE_PREFIX}${realName})`; + } + lines.push(decl); + + lines.push( + `declare export function assert${typeName}(node: ?Object, opts?: ?Object): void` + ); +} + +lines.push( + `declare export var VISITOR_KEYS: { [type: string]: string[] }`, + + // assert/ + `declare export function assertNode(obj: any): void`, + + // builders/ + // eslint-disable-next-line max-len + `declare export function createTypeAnnotationBasedOnTypeof(type: 'string' | 'number' | 'undefined' | 'boolean' | 'function' | 'object' | 'symbol'): ${NODE_PREFIX}TypeAnnotation`, + // eslint-disable-next-line max-len + `declare export function createUnionTypeAnnotation(types: Array<${NODE_PREFIX}FlowType>): ${NODE_PREFIX}UnionTypeAnnotation`, + // eslint-disable-next-line max-len + `declare export function createFlowUnionType(types: Array<${NODE_PREFIX}FlowType>): ${NODE_PREFIX}UnionTypeAnnotation`, + // this smells like "internal API" + // eslint-disable-next-line max-len + `declare export function buildChildren(node: { children: Array<${NODE_PREFIX}JSXText | ${NODE_PREFIX}JSXExpressionContainer | ${NODE_PREFIX}JSXSpreadChild | ${NODE_PREFIX}JSXElement | ${NODE_PREFIX}JSXFragment | ${NODE_PREFIX}JSXEmptyExpression> }): Array<${NODE_PREFIX}JSXText | ${NODE_PREFIX}JSXExpressionContainer | ${NODE_PREFIX}JSXSpreadChild | ${NODE_PREFIX}JSXElement | ${NODE_PREFIX}JSXFragment>`, + + // clone/ + `declare export function clone(n: T): T;`, + `declare export function cloneDeep(n: T): T;`, + `declare export function cloneDeepWithoutLoc(n: T): T;`, + `declare export function cloneNode(n: T, deep?: boolean, withoutLoc?: boolean): T;`, + `declare export function cloneWithoutLoc(n: T): T;`, + + // comments/ + `declare type CommentTypeShorthand = 'leading' | 'inner' | 'trailing'`, + // eslint-disable-next-line max-len + `declare export function addComment(node: T, type: CommentTypeShorthand, content: string, line?: boolean): T`, + // eslint-disable-next-line max-len + `declare export function addComments(node: T, type: CommentTypeShorthand, comments: Array): T`, + `declare export function inheritInnerComments(node: BabelNode, parent: BabelNode): void`, + `declare export function inheritLeadingComments(node: BabelNode, parent: BabelNode): void`, + `declare export function inheritsComments(node: T, parent: BabelNode): void`, + `declare export function inheritTrailingComments(node: BabelNode, parent: BabelNode): void`, + `declare export function removeComments(node: T): T`, + + // converters/ + `declare export function ensureBlock(node: ${NODE_PREFIX}, key: string): ${NODE_PREFIX}BlockStatement`, + `declare export function toBindingIdentifierName(name?: ?string): string`, + // eslint-disable-next-line max-len + `declare export function toBlock(node: ${NODE_PREFIX}Statement | ${NODE_PREFIX}Expression, parent?: ${NODE_PREFIX}Function | null): ${NODE_PREFIX}BlockStatement`, + // eslint-disable-next-line max-len + `declare export function toComputedKey(node: ${NODE_PREFIX}Method | ${NODE_PREFIX}Property, key?: ${NODE_PREFIX}Expression | ${NODE_PREFIX}Identifier): ${NODE_PREFIX}Expression`, + // eslint-disable-next-line max-len + `declare export function toExpression(node: ${NODE_PREFIX}ExpressionStatement | ${NODE_PREFIX}Expression | ${NODE_PREFIX}Class | ${NODE_PREFIX}Function): ${NODE_PREFIX}Expression`, + `declare export function toIdentifier(name?: ?string): string`, + // eslint-disable-next-line max-len + `declare export function toKeyAlias(node: ${NODE_PREFIX}Method | ${NODE_PREFIX}Property, key?: ${NODE_PREFIX}): string`, + // toSequenceExpression relies on types that aren't declared in flow + // eslint-disable-next-line max-len + `declare export function toStatement(node: ${NODE_PREFIX}Statement | ${NODE_PREFIX}Class | ${NODE_PREFIX}Function | ${NODE_PREFIX}AssignmentExpression, ignore?: boolean): ${NODE_PREFIX}Statement | void`, + `declare export function valueToNode(value: any): ${NODE_PREFIX}Expression`, + + // modifications/ + // eslint-disable-next-line max-len + `declare export function removeTypeDuplicates(types: Array<${NODE_PREFIX}FlowType>): Array<${NODE_PREFIX}FlowType>`, + // eslint-disable-next-line max-len + `declare export function appendToMemberExpression(member: ${NODE_PREFIX}MemberExpression, append: ${NODE_PREFIX}, computed?: boolean): ${NODE_PREFIX}MemberExpression`, + // eslint-disable-next-line max-len + `declare export function inherits(child: T, parent: ${NODE_PREFIX} | null | void): T`, + // eslint-disable-next-line max-len + `declare export function prependToMemberExpression(member: ${NODE_PREFIX}MemberExpression, prepend: ${NODE_PREFIX}Expression): ${NODE_PREFIX}MemberExpression`, + `declare export function removeProperties(n: T, opts: ?{}): void;`, + `declare export function removePropertiesDeep(n: T, opts: ?{}): T;`, + + // retrievers/ + // eslint-disable-next-line max-len + `declare export var getBindingIdentifiers: { + (node: ${NODE_PREFIX}, duplicates?: boolean, outerOnly?: boolean): { [key: string]: ${NODE_PREFIX}Identifier | Array<${NODE_PREFIX}Identifier> }, + keys: { [type: string]: string[] } + }`, + // eslint-disable-next-line max-len + `declare export function getOuterBindingIdentifiers(node: BabelNode, duplicates?: boolean): { [key: string]: ${NODE_PREFIX}Identifier | Array<${NODE_PREFIX}Identifier> }`, + + // traverse/ + `declare type TraversalAncestors = Array<{ + node: BabelNode, + key: string, + index?: number, + }>; + declare type TraversalHandler = (BabelNode, TraversalAncestors, T) => void; + declare type TraversalHandlers = { + enter?: TraversalHandler, + exit?: TraversalHandler, + };`.replace(/(^|\n) {2}/g, "$1"), + // eslint-disable-next-line + `declare export function traverse(n: BabelNode, TraversalHandler | TraversalHandlers, state?: T): void;`, + `declare export function traverseFast(n: BabelNode, h: TraversalHandler, state?: T): void;`, + + // utils/ + // cleanJSXElementLiteralChild is not exported + // inherit is not exported + `declare export function shallowEqual(actual: Object, expected: Object): boolean`, + + // validators/ + // eslint-disable-next-line max-len + `declare export function buildMatchMemberExpression(match: string, allowPartial?: boolean): (?BabelNode) => boolean`, + `declare export function is(type: string, n: BabelNode, opts: Object): boolean;`, + `declare export function isBinding(node: BabelNode, parent: BabelNode, grandparent?: BabelNode): boolean`, + `declare export function isBlockScoped(node: BabelNode): boolean`, + `declare export function isImmutable(node: BabelNode): boolean`, + `declare export function isLet(node: BabelNode): boolean`, + `declare export function isNode(node: ?Object): boolean`, + `declare export function isNodesEquivalent(a: any, b: any): boolean`, + `declare export function isPlaceholderType(placeholderType: string, targetType: string): boolean`, + `declare export function isReferenced(node: BabelNode, parent: BabelNode, grandparent?: BabelNode): boolean`, + `declare export function isScope(node: BabelNode, parent: BabelNode): boolean`, + `declare export function isSpecifierDefault(specifier: BabelNodeModuleSpecifier): boolean`, + `declare export function isType(nodetype: ?string, targetType: string): boolean`, + `declare export function isValidES3Identifier(name: string): boolean`, + `declare export function isValidES3Identifier(name: string): boolean`, + `declare export function isValidIdentifier(name: string): boolean`, + `declare export function isVar(node: BabelNode): boolean`, + // eslint-disable-next-line max-len + `declare export function matchesPattern(node: ?BabelNode, match: string | Array, allowPartial?: boolean): boolean`, + `declare export function validate(n: BabelNode, key: string, value: mixed): void;` +); + +for (const type in t.FLIPPED_ALIAS_KEYS) { + const types = t.FLIPPED_ALIAS_KEYS[type]; + code += `type ${NODE_PREFIX}${type} = ${types + .map(type => `${NODE_PREFIX}${type}`) + .join(" | ")};\n`; +} + +code += `\ndeclare module "@babel/types" { + ${lines.join("\n").replace(/\n/g, "\n ").trim()} +}\n`; + +// + +process.stdout.write(code); diff --git a/node_modules/@babel/types/scripts/generators/typescript-legacy.js b/node_modules/@babel/types/scripts/generators/typescript-legacy.js new file mode 100644 index 0000000..40da48f --- /dev/null +++ b/node_modules/@babel/types/scripts/generators/typescript-legacy.js @@ -0,0 +1,369 @@ +import t from "../../lib/index.js"; +import stringifyValidator from "../utils/stringifyValidator.js"; +import toFunctionName from "../utils/toFunctionName.js"; + +let code = `// NOTE: This file is autogenerated. Do not modify. +// See packages/babel-types/scripts/generators/typescript-legacy.js for script used. + +interface BaseComment { + value: string; + start: number; + end: number; + loc: SourceLocation; + type: "CommentBlock" | "CommentLine"; +} + +export interface CommentBlock extends BaseComment { + type: "CommentBlock"; +} + +export interface CommentLine extends BaseComment { + type: "CommentLine"; +} + +export type Comment = CommentBlock | CommentLine; + +export interface SourceLocation { + start: { + line: number; + column: number; + }; + + end: { + line: number; + column: number; + }; +} + +interface BaseNode { + leadingComments: ReadonlyArray | null; + innerComments: ReadonlyArray | null; + trailingComments: ReadonlyArray | null; + start: number | null; + end: number | null; + loc: SourceLocation | null; + type: Node["type"]; + extra?: Record; +} + +export type Node = ${t.TYPES.sort().join(" | ")};\n\n`; + +// + +const lines = []; + +for (const type in t.NODE_FIELDS) { + const fields = t.NODE_FIELDS[type]; + const fieldNames = sortFieldNames(Object.keys(t.NODE_FIELDS[type]), type); + const builderNames = t.BUILDER_KEYS[type]; + + const struct = ['type: "' + type + '";']; + const args = []; + + fieldNames.forEach(fieldName => { + const field = fields[fieldName]; + // Future / annoying TODO: + // MemberExpression.property, ObjectProperty.key and ObjectMethod.key need special cases; either: + // - convert the declaration to chain() like ClassProperty.key and ClassMethod.key, + // - declare an alias type for valid keys, detect the case and reuse it here, + // - declare a disjoint union with, for example, ObjectPropertyBase, + // ObjectPropertyLiteralKey and ObjectPropertyComputedKey, and declare ObjectProperty + // as "ObjectPropertyBase & (ObjectPropertyLiteralKey | ObjectPropertyComputedKey)" + let typeAnnotation = stringifyValidator(field.validate, ""); + + if (isNullable(field) && !hasDefault(field)) { + typeAnnotation += " | null"; + } + + if (builderNames.includes(fieldName)) { + if (areAllRemainingFieldsNullable(fieldName, builderNames, fields)) { + args.push( + `${t.toBindingIdentifierName(fieldName)}${ + isNullable(field) ? "?:" : ":" + } ${typeAnnotation}` + ); + } else { + args.push( + `${t.toBindingIdentifierName(fieldName)}: ${typeAnnotation}${ + isNullable(field) ? " | undefined" : "" + }` + ); + } + } + + const alphaNumeric = /^\w+$/; + + if (t.isValidIdentifier(fieldName) || alphaNumeric.test(fieldName)) { + struct.push(`${fieldName}: ${typeAnnotation};`); + } else { + struct.push(`"${fieldName}": ${typeAnnotation};`); + } + }); + + code += `export interface ${type} extends BaseNode { + ${struct.join("\n ").trim()} +}\n\n`; + + // super and import are reserved words in JavaScript + if (type !== "Super" && type !== "Import") { + lines.push( + `export function ${toFunctionName(type)}(${args.join(", ")}): ${type};` + ); + } else { + const functionName = toFunctionName(type); + lines.push( + `declare function _${functionName}(${args.join(", ")}): ${type};`, + `export { _${functionName} as ${functionName}}` + ); + } +} + +for (const typeName of t.TYPES) { + const isDeprecated = !!t.DEPRECATED_KEYS[typeName]; + const realName = isDeprecated ? t.DEPRECATED_KEYS[typeName] : typeName; + + const result = + t.NODE_FIELDS[realName] || t.FLIPPED_ALIAS_KEYS[realName] + ? `node is ${realName}` + : "boolean"; + + if (isDeprecated) { + lines.push(`/** @deprecated Use \`is${realName}\` */`); + } + lines.push( + `export function is${typeName}(node: object | null | undefined, opts?: object | null): ${result};` + ); + + if (isDeprecated) { + lines.push(`/** @deprecated Use \`assert${realName}\` */`); + } + lines.push( + `export function assert${typeName}(node: object | null | undefined, opts?: object | null): void;` + ); +} + +lines.push( + // assert/ + `export function assertNode(obj: any): void`, + + // builders/ + // eslint-disable-next-line max-len + `export function createTypeAnnotationBasedOnTypeof(type: 'string' | 'number' | 'undefined' | 'boolean' | 'function' | 'object' | 'symbol'): StringTypeAnnotation | VoidTypeAnnotation | NumberTypeAnnotation | BooleanTypeAnnotation | GenericTypeAnnotation`, + `export function createUnionTypeAnnotation(types: [T]): T`, + `export function createFlowUnionType(types: [T]): T`, + // this probably misbehaves if there are 0 elements, and it's not a UnionTypeAnnotation if there's only 1 + // it is possible to require "2 or more" for this overload ([T, T, ...T[]]) but it requires typescript 3.0 + `export function createUnionTypeAnnotation(types: ReadonlyArray): UnionTypeAnnotation`, + `export function createFlowUnionType(types: ReadonlyArray): UnionTypeAnnotation`, + // this smells like "internal API" + // eslint-disable-next-line max-len + `export function buildChildren(node: { children: ReadonlyArray }): JSXElement['children']`, + + // clone/ + `export function clone(n: T): T;`, + `export function cloneDeep(n: T): T;`, + `export function cloneDeepWithoutLoc(n: T): T;`, + `export function cloneNode(n: T, deep?: boolean, withoutLoc?: boolean): T;`, + `export function cloneWithoutLoc(n: T): T;`, + + // comments/ + `export type CommentTypeShorthand = 'leading' | 'inner' | 'trailing'`, + // eslint-disable-next-line max-len + `export function addComment(node: T, type: CommentTypeShorthand, content: string, line?: boolean): T`, + // eslint-disable-next-line max-len + `export function addComments(node: T, type: CommentTypeShorthand, comments: ReadonlyArray): T`, + `export function inheritInnerComments(node: Node, parent: Node): void`, + `export function inheritLeadingComments(node: Node, parent: Node): void`, + `export function inheritsComments(node: T, parent: Node): void`, + `export function inheritTrailingComments(node: Node, parent: Node): void`, + `export function removeComments(node: T): T`, + + // converters/ + // eslint-disable-next-line max-len + `export function ensureBlock(node: Extract): BlockStatement`, + // too complex? + // eslint-disable-next-line max-len + `export function ensureBlock = 'body'>(node: Extract>, key: K): BlockStatement`, + // gatherSequenceExpressions is not exported + `export function toBindingIdentifierName(name: { toString(): string } | null | undefined): string`, + `export function toBlock(node: Statement | Expression, parent?: Function | null): BlockStatement`, + // it is possible for `node` to be an arbitrary object if `key` is always provided, + // but that doesn't look like intended API + // eslint-disable-next-line max-len + `export function toComputedKey>(node: T, key?: Expression | Identifier): Expression`, + `export function toExpression(node: Function): FunctionExpression`, + `export function toExpression(node: Class): ClassExpression`, + `export function toExpression(node: ExpressionStatement | Expression | Class | Function): Expression`, + `export function toIdentifier(name: { toString(): string } | null | undefined): string`, + `export function toKeyAlias(node: Method | Property, key?: Node): string`, + // NOTE: this actually uses Scope from @babel/traverse, but we can't add a dependency on its types, + // as they live in @types. Declare the structural subset that is required. + // eslint-disable-next-line max-len + `export function toSequenceExpression(nodes: ReadonlyArray, scope: { push(value: { id: LVal; kind: 'var'; init?: Expression}): void; buildUndefinedNode(): Node }): SequenceExpression | undefined`, + `export function toStatement(node: AssignmentExpression, ignore?: boolean): ExpressionStatement`, + `export function toStatement(node: Statement | AssignmentExpression, ignore?: boolean): Statement`, + `export function toStatement(node: Class, ignore: true): ClassDeclaration | undefined`, + `export function toStatement(node: Class, ignore?: boolean): ClassDeclaration`, + `export function toStatement(node: Function, ignore: true): FunctionDeclaration | undefined`, + `export function toStatement(node: Function, ignore?: boolean): FunctionDeclaration`, + // eslint-disable-next-line max-len + `export function toStatement(node: Statement | Class | Function | AssignmentExpression, ignore: true): Statement | undefined`, + // eslint-disable-next-line max-len + `export function toStatement(node: Statement | Class | Function | AssignmentExpression, ignore?: boolean): Statement`, + // eslint-disable-next-line max-len + `export function valueToNode(value: undefined): Identifier`, // (should this not be a UnaryExpression to avoid shadowing?) + `export function valueToNode(value: boolean): BooleanLiteral`, + `export function valueToNode(value: null): NullLiteral`, + `export function valueToNode(value: string): StringLiteral`, + // Infinities and NaN need to use a BinaryExpression; negative values must be wrapped in UnaryExpression + `export function valueToNode(value: number): NumericLiteral | BinaryExpression | UnaryExpression`, + `export function valueToNode(value: RegExp): RegExpLiteral`, + // eslint-disable-next-line max-len + `export function valueToNode(value: ReadonlyArray): ArrayExpression`, + // this throws with objects that are not PlainObject according to lodash, + // or if there are non-valueToNode-able values + `export function valueToNode(value: object): ObjectExpression`, + // eslint-disable-next-line max-len + `export function valueToNode(value: undefined | boolean | null | string | number | RegExp | object): Expression`, + + // modifications/ + // eslint-disable-next-line max-len + `export function removeTypeDuplicates(types: ReadonlyArray): FlowType[]`, + // eslint-disable-next-line max-len + `export function appendToMemberExpression>(member: T, append: MemberExpression['property'], computed?: boolean): T`, + // eslint-disable-next-line max-len + `export function inherits(child: T, parent: Node | null | undefined): T`, + // eslint-disable-next-line max-len + `export function prependToMemberExpression>(member: T, prepend: MemberExpression['object']): T`, + `export function removeProperties( + n: Node, + opts?: { preserveComments: boolean } | null +): void;`, + `export function removePropertiesDeep( + n: T, + opts?: { preserveComments: boolean } | null +): T;`, + + // retrievers/ + // eslint-disable-next-line max-len + `export function getBindingIdentifiers(node: Node, duplicates: true, outerOnly?: boolean): Record>`, + // eslint-disable-next-line max-len + `export function getBindingIdentifiers(node: Node, duplicates?: false, outerOnly?: boolean): Record`, + // eslint-disable-next-line max-len + `export function getBindingIdentifiers(node: Node, duplicates: boolean, outerOnly?: boolean): Record>`, + // eslint-disable-next-line max-len + `export function getOuterBindingIdentifiers(node: Node, duplicates: true): Record>`, + `export function getOuterBindingIdentifiers(node: Node, duplicates?: false): Record`, + // eslint-disable-next-line max-len + `export function getOuterBindingIdentifiers(node: Node, duplicates: boolean): Record>`, + + // traverse/ + `export type TraversalAncestors = ReadonlyArray<{ + node: Node, + key: string, + index?: number, + }>; + export type TraversalHandler = ( + this: undefined, node: Node, parent: TraversalAncestors, type: T + ) => void; + export type TraversalHandlers = { + enter?: TraversalHandler, + exit?: TraversalHandler, + };`.replace(/(^|\n) {2}/g, "$1"), + // eslint-disable-next-line + `export function traverse(n: Node, h: TraversalHandler | TraversalHandlers, state?: T): void;`, + `export function traverseFast(n: Node, h: TraversalHandler, state?: T): void;`, + + // utils/ + // cleanJSXElementLiteralChild is not exported + // inherit is not exported + `export function shallowEqual(actual: object, expected: T): actual is T`, + + // validators/ + // eslint-disable-next-line max-len + `export function buildMatchMemberExpression(match: string, allowPartial?: boolean): (node: Node | null | undefined) => node is MemberExpression`, + // eslint-disable-next-line max-len + `export function is(type: T, n: Node | null | undefined, required?: undefined): n is Extract`, + // eslint-disable-next-line max-len + `export function is>(type: T, n: Node | null | undefined, required: Partial

): n is P`, + // eslint-disable-next-line max-len + `export function is

(type: string, n: Node | null | undefined, required: Partial

): n is P`, + `export function is(type: string, n: Node | null | undefined, required?: Partial): n is Node`, + `export function isBinding(node: Node, parent: Node, grandparent?: Node): boolean`, + // eslint-disable-next-line max-len + `export function isBlockScoped(node: Node): node is FunctionDeclaration | ClassDeclaration | VariableDeclaration`, + `export function isImmutable(node: Node): node is Immutable`, + `export function isLet(node: Node): node is VariableDeclaration`, + `export function isNode(node: object | null | undefined): node is Node`, + `export function isNodesEquivalent>(a: T, b: any): b is T`, + `export function isNodesEquivalent(a: any, b: any): boolean`, + `export function isPlaceholderType(placeholderType: Node['type'], targetType: Node['type']): boolean`, + `export function isReferenced(node: Node, parent: Node, grandparent?: Node): boolean`, + `export function isScope(node: Node, parent: Node): node is Scopable`, + `export function isSpecifierDefault(specifier: ModuleSpecifier): boolean`, + `export function isType(nodetype: string, targetType: T): nodetype is T`, + `export function isType(nodetype: string | null | undefined, targetType: string): boolean`, + `export function isValidES3Identifier(name: string): boolean`, + `export function isValidIdentifier(name: string): boolean`, + `export function isVar(node: Node): node is VariableDeclaration`, + // the MemberExpression implication is incidental, but it follows from the implementation + // eslint-disable-next-line max-len + `export function matchesPattern(node: Node | null | undefined, match: string | ReadonlyArray, allowPartial?: boolean): node is MemberExpression`, + // eslint-disable-next-line max-len + `export function validate(n: Node | null | undefined, key: K, value: T[K]): void;`, + `export function validate(n: Node, key: string, value: any): void;` +); + +for (const type in t.DEPRECATED_KEYS) { + code += `/** + * @deprecated Use \`${t.DEPRECATED_KEYS[type]}\` + */ +export type ${type} = ${t.DEPRECATED_KEYS[type]};\n +`; +} + +for (const type in t.FLIPPED_ALIAS_KEYS) { + const types = t.FLIPPED_ALIAS_KEYS[type]; + code += `export type ${type} = ${types + .map(type => `${type}`) + .join(" | ")};\n`; +} +code += "\n"; + +code += "export interface Aliases {\n"; +for (const type in t.FLIPPED_ALIAS_KEYS) { + code += ` ${type}: ${type};\n`; +} +code += "}\n\n"; + +code += lines.join("\n") + "\n"; + +// + +process.stdout.write(code); + +// + +function areAllRemainingFieldsNullable(fieldName, fieldNames, fields) { + const index = fieldNames.indexOf(fieldName); + return fieldNames.slice(index).every(_ => isNullable(fields[_])); +} + +function hasDefault(field) { + return field.default != null; +} + +function isNullable(field) { + return field.optional || hasDefault(field); +} + +function sortFieldNames(fields, type) { + return fields.sort((fieldA, fieldB) => { + const indexA = t.BUILDER_KEYS[type].indexOf(fieldA); + const indexB = t.BUILDER_KEYS[type].indexOf(fieldB); + if (indexA === indexB) return fieldA < fieldB ? -1 : 1; + if (indexA === -1) return 1; + if (indexB === -1) return -1; + return indexA - indexB; + }); +} diff --git a/node_modules/@babel/types/scripts/generators/validators.js b/node_modules/@babel/types/scripts/generators/validators.js new file mode 100644 index 0000000..acd6da6 --- /dev/null +++ b/node_modules/@babel/types/scripts/generators/validators.js @@ -0,0 +1,87 @@ +import definitions from "../../lib/definitions/index.js"; + +const has = Function.call.bind(Object.prototype.hasOwnProperty); + +function joinComparisons(leftArr, right) { + return ( + leftArr.map(JSON.stringify).join(` === ${right} || `) + ` === ${right}` + ); +} + +function addIsHelper(type, aliasKeys, deprecated) { + const targetType = JSON.stringify(type); + let aliasSource = ""; + if (aliasKeys) { + aliasSource = joinComparisons(aliasKeys, "nodeType"); + } + + let placeholderSource = ""; + const placeholderTypes = []; + if ( + definitions.PLACEHOLDERS.includes(type) && + has(definitions.FLIPPED_ALIAS_KEYS, type) + ) { + placeholderTypes.push(type); + } + if (has(definitions.PLACEHOLDERS_FLIPPED_ALIAS, type)) { + placeholderTypes.push(...definitions.PLACEHOLDERS_FLIPPED_ALIAS[type]); + } + if (placeholderTypes.length > 0) { + placeholderSource = + ' || nodeType === "Placeholder" && (' + + joinComparisons( + placeholderTypes, + "(node as t.Placeholder).expectedNode" + ) + + ")"; + } + + const result = + definitions.NODE_FIELDS[type] || definitions.FLIPPED_ALIAS_KEYS[type] + ? `node is t.${type}` + : "boolean"; + + return `export function is${type}(node: object | null | undefined, opts?: object | null): ${result} { + ${deprecated || ""} + if (!node) return false; + + const nodeType = (node as t.Node).type; + if (${ + aliasSource ? aliasSource : `nodeType === ${targetType}` + }${placeholderSource}) { + if (typeof opts === "undefined") { + return true; + } else { + return shallowEqual(node, opts); + } + } + + return false; + } + `; +} + +export default function generateValidators() { + let output = `/* + * This file is auto-generated! Do not modify it directly. + * To re-generate run 'make build' + */ +import shallowEqual from "../../utils/shallowEqual"; +import type * as t from "../..";\n\n`; + + Object.keys(definitions.VISITOR_KEYS).forEach(type => { + output += addIsHelper(type); + }); + + Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => { + output += addIsHelper(type, definitions.FLIPPED_ALIAS_KEYS[type]); + }); + + Object.keys(definitions.DEPRECATED_KEYS).forEach(type => { + const newType = definitions.DEPRECATED_KEYS[type]; + const deprecated = `console.trace("The node type ${type} has been renamed to ${newType}");`; + output += addIsHelper(type, null, deprecated); + }); + + return output; +} diff --git a/node_modules/@babel/types/scripts/package.json b/node_modules/@babel/types/scripts/package.json new file mode 100644 index 0000000..5ffd980 --- /dev/null +++ b/node_modules/@babel/types/scripts/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/node_modules/@babel/types/scripts/utils/formatBuilderName.js b/node_modules/@babel/types/scripts/utils/formatBuilderName.js new file mode 100644 index 0000000..f00a3c4 --- /dev/null +++ b/node_modules/@babel/types/scripts/utils/formatBuilderName.js @@ -0,0 +1,8 @@ +const toLowerCase = Function.call.bind("".toLowerCase); + +export default function formatBuilderName(type) { + // FunctionExpression -> functionExpression + // JSXIdentifier -> jsxIdentifier + // V8IntrinsicIdentifier -> v8IntrinsicIdentifier + return type.replace(/^([A-Z](?=[a-z0-9])|[A-Z]+(?=[A-Z]))/, toLowerCase); +} diff --git a/node_modules/@babel/types/scripts/utils/lowerFirst.js b/node_modules/@babel/types/scripts/utils/lowerFirst.js new file mode 100644 index 0000000..012f252 --- /dev/null +++ b/node_modules/@babel/types/scripts/utils/lowerFirst.js @@ -0,0 +1,3 @@ +export default function lowerFirst(string) { + return string[0].toLowerCase() + string.slice(1); +} diff --git a/node_modules/@babel/types/scripts/utils/stringifyValidator.js b/node_modules/@babel/types/scripts/utils/stringifyValidator.js new file mode 100644 index 0000000..4b8d29c --- /dev/null +++ b/node_modules/@babel/types/scripts/utils/stringifyValidator.js @@ -0,0 +1,66 @@ +export default function stringifyValidator(validator, nodePrefix) { + if (validator === undefined) { + return "any"; + } + + if (validator.each) { + return `Array<${stringifyValidator(validator.each, nodePrefix)}>`; + } + + if (validator.chainOf) { + return stringifyValidator(validator.chainOf[1], nodePrefix); + } + + if (validator.oneOf) { + return validator.oneOf.map(JSON.stringify).join(" | "); + } + + if (validator.oneOfNodeTypes) { + return validator.oneOfNodeTypes.map(_ => nodePrefix + _).join(" | "); + } + + if (validator.oneOfNodeOrValueTypes) { + return validator.oneOfNodeOrValueTypes + .map(_ => { + return isValueType(_) ? _ : nodePrefix + _; + }) + .join(" | "); + } + + if (validator.type) { + return validator.type; + } + + if (validator.shapeOf) { + return ( + "{ " + + Object.keys(validator.shapeOf) + .map(shapeKey => { + const propertyDefinition = validator.shapeOf[shapeKey]; + if (propertyDefinition.validate) { + const isOptional = + propertyDefinition.optional || propertyDefinition.default != null; + return ( + shapeKey + + (isOptional ? "?: " : ": ") + + stringifyValidator(propertyDefinition.validate) + ); + } + return null; + }) + .filter(Boolean) + .join(", ") + + " }" + ); + } + + return ["any"]; +} + +/** + * Heuristic to decide whether or not the given type is a value type (eg. "null") + * or a Node type (eg. "Expression"). + */ +function isValueType(type) { + return type.charAt(0).toLowerCase() === type.charAt(0); +} diff --git a/node_modules/@babel/types/scripts/utils/toFunctionName.js b/node_modules/@babel/types/scripts/utils/toFunctionName.js new file mode 100644 index 0000000..2b64578 --- /dev/null +++ b/node_modules/@babel/types/scripts/utils/toFunctionName.js @@ -0,0 +1,4 @@ +export default function toFunctionName(typeName) { + const _ = typeName.replace(/^TS/, "ts").replace(/^JSX/, "jsx"); + return _.slice(0, 1).toLowerCase() + _.slice(1); +} diff --git a/node_modules/@types/estree/LICENSE b/node_modules/@types/estree/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/estree/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/@types/estree/README.md b/node_modules/@types/estree/README.md new file mode 100644 index 0000000..95fcf63 --- /dev/null +++ b/node_modules/@types/estree/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/estree` + +# Summary +This package contains type definitions for ESTree AST specification (https://github.com/estree/estree). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree. + +### Additional Details + * Last updated: Wed, 02 Jun 2021 05:31:29 GMT + * Dependencies: none + * Global values: none + +# Credits +These definitions were written by [RReverser](https://github.com/RReverser). diff --git a/node_modules/@types/estree/flow.d.ts b/node_modules/@types/estree/flow.d.ts new file mode 100644 index 0000000..605765e --- /dev/null +++ b/node_modules/@types/estree/flow.d.ts @@ -0,0 +1,174 @@ +// Type definitions for ESTree AST extensions for Facebook Flow +// Project: https://github.com/estree/estree +// Definitions by: RReverser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +declare namespace ESTree { + interface FlowTypeAnnotation extends Node {} + + interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {} + + interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {} + + interface FlowDeclaration extends Declaration {} + + interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ArrayTypeAnnotation extends FlowTypeAnnotation { + elementType: FlowTypeAnnotation; + } + + interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ClassImplements extends Node { + id: Identifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface ClassProperty { + key: Expression; + value?: Expression | null; + typeAnnotation?: TypeAnnotation | null; + computed: boolean; + static: boolean; + } + + interface DeclareClass extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + body: ObjectTypeAnnotation; + extends: Array; + } + + interface DeclareFunction extends FlowDeclaration { + id: Identifier; + } + + interface DeclareModule extends FlowDeclaration { + id: Literal | Identifier; + body: BlockStatement; + } + + interface DeclareVariable extends FlowDeclaration { + id: Identifier; + } + + interface FunctionTypeAnnotation extends FlowTypeAnnotation { + params: Array; + returnType: FlowTypeAnnotation; + rest?: FunctionTypeParam | null; + typeParameters?: TypeParameterDeclaration | null; + } + + interface FunctionTypeParam { + name: Identifier; + typeAnnotation: FlowTypeAnnotation; + optional: boolean; + } + + interface GenericTypeAnnotation extends FlowTypeAnnotation { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceExtends extends Node { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceDeclaration extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + extends: Array; + body: ObjectTypeAnnotation; + } + + interface IntersectionTypeAnnotation extends FlowTypeAnnotation { + types: Array; + } + + interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface NullableTypeAnnotation extends FlowTypeAnnotation { + typeAnnotation: TypeAnnotation; + } + + interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface StringTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface TupleTypeAnnotation extends FlowTypeAnnotation { + types: Array; + } + + interface TypeofTypeAnnotation extends FlowTypeAnnotation { + argument: FlowTypeAnnotation; + } + + interface TypeAlias extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + right: FlowTypeAnnotation; + } + + interface TypeAnnotation extends Node { + typeAnnotation: FlowTypeAnnotation; + } + + interface TypeCastExpression extends Expression { + expression: Expression; + typeAnnotation: TypeAnnotation; + } + + interface TypeParameterDeclaration extends Node { + params: Array; + } + + interface TypeParameterInstantiation extends Node { + params: Array; + } + + interface ObjectTypeAnnotation extends FlowTypeAnnotation { + properties: Array; + indexers: Array; + callProperties: Array; + } + + interface ObjectTypeCallProperty extends Node { + value: FunctionTypeAnnotation; + static: boolean; + } + + interface ObjectTypeIndexer extends Node { + id: Identifier; + key: FlowTypeAnnotation; + value: FlowTypeAnnotation; + static: boolean; + } + + interface ObjectTypeProperty extends Node { + key: Expression; + value: FlowTypeAnnotation; + optional: boolean; + static: boolean; + } + + interface QualifiedTypeIdentifier extends Node { + qualification: Identifier | QualifiedTypeIdentifier; + id: Identifier; + } + + interface UnionTypeAnnotation extends FlowTypeAnnotation { + types: Array; + } + + interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {} +} diff --git a/node_modules/@types/estree/index.d.ts b/node_modules/@types/estree/index.d.ts new file mode 100644 index 0000000..f652c30 --- /dev/null +++ b/node_modules/@types/estree/index.d.ts @@ -0,0 +1,590 @@ +// Type definitions for ESTree AST specification +// Project: https://github.com/estree/estree +// Definitions by: RReverser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// This definition file follows a somewhat unusual format. ESTree allows +// runtime type checks based on the `type` parameter. In order to explain this +// to typescript we want to use discriminated union types: +// https://github.com/Microsoft/TypeScript/pull/9163 +// +// For ESTree this is a bit tricky because the high level interfaces like +// Node or Function are pulling double duty. We want to pass common fields down +// to the interfaces that extend them (like Identifier or +// ArrowFunctionExpression), but you can't extend a type union or enforce +// common fields on them. So we've split the high level interfaces into two +// types, a base type which passes down inherited fields, and a type union of +// all types which extend the base type. Only the type union is exported, and +// the union is how other types refer to the collection of inheriting types. +// +// This makes the definitions file here somewhat more difficult to maintain, +// but it has the notable advantage of making ESTree much easier to use as +// an end user. + +interface BaseNodeWithoutComments { + // Every leaf interface that extends BaseNode must specify a type property. + // The type property should be a string literal. For example, Identifier + // has: `type: "Identifier"` + type: string; + loc?: SourceLocation | null; + range?: [number, number]; +} + +interface BaseNode extends BaseNodeWithoutComments { + leadingComments?: Array; + trailingComments?: Array; +} + +export type Node = + Identifier | Literal | Program | Function | SwitchCase | CatchClause | + VariableDeclarator | Statement | Expression | PrivateIdentifier | Property | PropertyDefinition | + AssignmentProperty | Super | TemplateElement | SpreadElement | Pattern | + ClassBody | Class | MethodDefinition | ModuleDeclaration | ModuleSpecifier; + +export interface Comment extends BaseNodeWithoutComments { + type: "Line" | "Block"; + value: string; +} + +interface SourceLocation { + source?: string | null; + start: Position; + end: Position; +} + +export interface Position { + /** >= 1 */ + line: number; + /** >= 0 */ + column: number; +} + +export interface Program extends BaseNode { + type: "Program"; + sourceType: "script" | "module"; + body: Array; + comments?: Array; +} + +export interface Directive extends BaseNode { + type: "ExpressionStatement"; + expression: Literal; + directive: string; +} + +interface BaseFunction extends BaseNode { + params: Array; + generator?: boolean; + async?: boolean; + // The body is either BlockStatement or Expression because arrow functions + // can have a body that's either. FunctionDeclarations and + // FunctionExpressions have only BlockStatement bodies. + body: BlockStatement | Expression; +} + +export type Function = + FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; + +export type Statement = + ExpressionStatement | BlockStatement | EmptyStatement | + DebuggerStatement | WithStatement | ReturnStatement | LabeledStatement | + BreakStatement | ContinueStatement | IfStatement | SwitchStatement | + ThrowStatement | TryStatement | WhileStatement | DoWhileStatement | + ForStatement | ForInStatement | ForOfStatement | Declaration; + +interface BaseStatement extends BaseNode { } + +export interface EmptyStatement extends BaseStatement { + type: "EmptyStatement"; +} + +export interface BlockStatement extends BaseStatement { + type: "BlockStatement"; + body: Array; + innerComments?: Array; +} + +export interface ExpressionStatement extends BaseStatement { + type: "ExpressionStatement"; + expression: Expression; +} + +export interface IfStatement extends BaseStatement { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate?: Statement | null; +} + +export interface LabeledStatement extends BaseStatement { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +export interface BreakStatement extends BaseStatement { + type: "BreakStatement"; + label?: Identifier | null; +} + +export interface ContinueStatement extends BaseStatement { + type: "ContinueStatement"; + label?: Identifier | null; +} + +export interface WithStatement extends BaseStatement { + type: "WithStatement"; + object: Expression; + body: Statement; +} + +export interface SwitchStatement extends BaseStatement { + type: "SwitchStatement"; + discriminant: Expression; + cases: Array; +} + +export interface ReturnStatement extends BaseStatement { + type: "ReturnStatement"; + argument?: Expression | null; +} + +export interface ThrowStatement extends BaseStatement { + type: "ThrowStatement"; + argument: Expression; +} + +export interface TryStatement extends BaseStatement { + type: "TryStatement"; + block: BlockStatement; + handler?: CatchClause | null; + finalizer?: BlockStatement | null; +} + +export interface WhileStatement extends BaseStatement { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +export interface DoWhileStatement extends BaseStatement { + type: "DoWhileStatement"; + body: Statement; + test: Expression; +} + +export interface ForStatement extends BaseStatement { + type: "ForStatement"; + init?: VariableDeclaration | Expression | null; + test?: Expression | null; + update?: Expression | null; + body: Statement; +} + +interface BaseForXStatement extends BaseStatement { + left: VariableDeclaration | Pattern; + right: Expression; + body: Statement; +} + +export interface ForInStatement extends BaseForXStatement { + type: "ForInStatement"; +} + +export interface DebuggerStatement extends BaseStatement { + type: "DebuggerStatement"; +} + +export type Declaration = + FunctionDeclaration | VariableDeclaration | ClassDeclaration; + +interface BaseDeclaration extends BaseStatement { } + +export interface FunctionDeclaration extends BaseFunction, BaseDeclaration { + type: "FunctionDeclaration"; + /** It is null when a function declaration is a part of the `export default function` statement */ + id: Identifier | null; + body: BlockStatement; +} + +export interface VariableDeclaration extends BaseDeclaration { + type: "VariableDeclaration"; + declarations: Array; + kind: "var" | "let" | "const"; +} + +export interface VariableDeclarator extends BaseNode { + type: "VariableDeclarator"; + id: Pattern; + init?: Expression | null; +} + +type Expression = + ThisExpression | ArrayExpression | ObjectExpression | FunctionExpression | + ArrowFunctionExpression | YieldExpression | Literal | UnaryExpression | + UpdateExpression | BinaryExpression | AssignmentExpression | + LogicalExpression | MemberExpression | ConditionalExpression | + CallExpression | NewExpression | SequenceExpression | TemplateLiteral | + TaggedTemplateExpression | ClassExpression | MetaProperty | Identifier | + AwaitExpression | ImportExpression | ChainExpression; + +export interface BaseExpression extends BaseNode { } + +type ChainElement = SimpleCallExpression | MemberExpression; + +export interface ChainExpression extends BaseExpression { + type: "ChainExpression"; + expression: ChainElement; +} + +export interface ThisExpression extends BaseExpression { + type: "ThisExpression"; +} + +export interface ArrayExpression extends BaseExpression { + type: "ArrayExpression"; + elements: Array; +} + +export interface ObjectExpression extends BaseExpression { + type: "ObjectExpression"; + properties: Array; +} + +export interface PrivateIdentifier extends BaseNode { + type: "PrivateIdentifier"; + name: string; +} + +export interface Property extends BaseNode { + type: "Property"; + key: Expression | PrivateIdentifier; + value: Expression | Pattern; // Could be an AssignmentProperty + kind: "init" | "get" | "set"; + method: boolean; + shorthand: boolean; + computed: boolean; +} + +export interface PropertyDefinition extends BaseNode { + type: "PropertyDefinition"; + key: Expression | PrivateIdentifier; + value?: Expression | null; + computed: boolean; + static: boolean; +} + +export interface FunctionExpression extends BaseFunction, BaseExpression { + id?: Identifier | null; + type: "FunctionExpression"; + body: BlockStatement; +} + +export interface SequenceExpression extends BaseExpression { + type: "SequenceExpression"; + expressions: Array; +} + +export interface UnaryExpression extends BaseExpression { + type: "UnaryExpression"; + operator: UnaryOperator; + prefix: true; + argument: Expression; +} + +export interface BinaryExpression extends BaseExpression { + type: "BinaryExpression"; + operator: BinaryOperator; + left: Expression; + right: Expression; +} + +export interface AssignmentExpression extends BaseExpression { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; +} + +export interface UpdateExpression extends BaseExpression { + type: "UpdateExpression"; + operator: UpdateOperator; + argument: Expression; + prefix: boolean; +} + +export interface LogicalExpression extends BaseExpression { + type: "LogicalExpression"; + operator: LogicalOperator; + left: Expression; + right: Expression; +} + +export interface ConditionalExpression extends BaseExpression { + type: "ConditionalExpression"; + test: Expression; + alternate: Expression; + consequent: Expression; +} + +interface BaseCallExpression extends BaseExpression { + callee: Expression | Super; + arguments: Array; +} +export type CallExpression = SimpleCallExpression | NewExpression; + +export interface SimpleCallExpression extends BaseCallExpression { + type: "CallExpression"; + optional: boolean; +} + +export interface NewExpression extends BaseCallExpression { + type: "NewExpression"; +} + +export interface MemberExpression extends BaseExpression, BasePattern { + type: "MemberExpression"; + object: Expression | Super; + property: Expression | PrivateIdentifier; + computed: boolean; + optional: boolean; +} + +export type Pattern = + Identifier | ObjectPattern | ArrayPattern | RestElement | + AssignmentPattern | MemberExpression; + +interface BasePattern extends BaseNode { } + +export interface SwitchCase extends BaseNode { + type: "SwitchCase"; + test?: Expression | null; + consequent: Array; +} + +export interface CatchClause extends BaseNode { + type: "CatchClause"; + param: Pattern | null; + body: BlockStatement; +} + +export interface Identifier extends BaseNode, BaseExpression, BasePattern { + type: "Identifier"; + name: string; +} + +export type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; + +export interface SimpleLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value: string | boolean | number | null; + raw?: string; +} + +export interface RegExpLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: RegExp | null; + regex: { + pattern: string; + flags: string; + }; + raw?: string; +} + +export interface BigIntLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: bigint | null; + bigint: string; + raw?: string; +} + +export type UnaryOperator = + "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + +export type BinaryOperator = + "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | + ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "**" | "|" | "^" | "&" | "in" | + "instanceof"; + +export type LogicalOperator = "||" | "&&" | "??"; + +export type AssignmentOperator = + "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "**=" | "<<=" | ">>=" | ">>>=" | + "|=" | "^=" | "&="; + +export type UpdateOperator = "++" | "--"; + +export interface ForOfStatement extends BaseForXStatement { + type: "ForOfStatement"; + await: boolean; +} + +export interface Super extends BaseNode { + type: "Super"; +} + +export interface SpreadElement extends BaseNode { + type: "SpreadElement"; + argument: Expression; +} + +export interface ArrowFunctionExpression extends BaseExpression, BaseFunction { + type: "ArrowFunctionExpression"; + expression: boolean; + body: BlockStatement | Expression; +} + +export interface YieldExpression extends BaseExpression { + type: "YieldExpression"; + argument?: Expression | null; + delegate: boolean; +} + +export interface TemplateLiteral extends BaseExpression { + type: "TemplateLiteral"; + quasis: Array; + expressions: Array; +} + +export interface TaggedTemplateExpression extends BaseExpression { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +export interface TemplateElement extends BaseNode { + type: "TemplateElement"; + tail: boolean; + value: { + /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ + cooked?: string | null; + raw: string; + }; +} + +export interface AssignmentProperty extends Property { + value: Pattern; + kind: "init"; + method: boolean; // false +} + +export interface ObjectPattern extends BasePattern { + type: "ObjectPattern"; + properties: Array; +} + +export interface ArrayPattern extends BasePattern { + type: "ArrayPattern"; + elements: Array; +} + +export interface RestElement extends BasePattern { + type: "RestElement"; + argument: Pattern; +} + +export interface AssignmentPattern extends BasePattern { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +export type Class = ClassDeclaration | ClassExpression; +interface BaseClass extends BaseNode { + superClass?: Expression | null; + body: ClassBody; +} + +export interface ClassBody extends BaseNode { + type: "ClassBody"; + body: Array; +} + +export interface MethodDefinition extends BaseNode { + type: "MethodDefinition"; + key: Expression | PrivateIdentifier; + value: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; +} + +export interface ClassDeclaration extends BaseClass, BaseDeclaration { + type: "ClassDeclaration"; + /** It is null when a class declaration is a part of the `export default class` statement */ + id: Identifier | null; +} + +export interface ClassExpression extends BaseClass, BaseExpression { + type: "ClassExpression"; + id?: Identifier | null; +} + +export interface MetaProperty extends BaseExpression { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +export type ModuleDeclaration = + ImportDeclaration | ExportNamedDeclaration | ExportDefaultDeclaration | + ExportAllDeclaration; +interface BaseModuleDeclaration extends BaseNode { } + +export type ModuleSpecifier = + ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | + ExportSpecifier; +interface BaseModuleSpecifier extends BaseNode { + local: Identifier; +} + +export interface ImportDeclaration extends BaseModuleDeclaration { + type: "ImportDeclaration"; + specifiers: Array; + source: Literal; +} + +export interface ImportSpecifier extends BaseModuleSpecifier { + type: "ImportSpecifier"; + imported: Identifier; +} + +export interface ImportExpression extends BaseExpression { + type: "ImportExpression"; + source: Expression; +} + +export interface ImportDefaultSpecifier extends BaseModuleSpecifier { + type: "ImportDefaultSpecifier"; +} + +export interface ImportNamespaceSpecifier extends BaseModuleSpecifier { + type: "ImportNamespaceSpecifier"; +} + +export interface ExportNamedDeclaration extends BaseModuleDeclaration { + type: "ExportNamedDeclaration"; + declaration?: Declaration | null; + specifiers: Array; + source?: Literal | null; +} + +export interface ExportSpecifier extends BaseModuleSpecifier { + type: "ExportSpecifier"; + exported: Identifier; +} + +export interface ExportDefaultDeclaration extends BaseModuleDeclaration { + type: "ExportDefaultDeclaration"; + declaration: Declaration | Expression; +} + +export interface ExportAllDeclaration extends BaseModuleDeclaration { + type: "ExportAllDeclaration"; + source: Literal; +} + +export interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} diff --git a/node_modules/@types/estree/package.json b/node_modules/@types/estree/package.json new file mode 100644 index 0000000..59eb482 --- /dev/null +++ b/node_modules/@types/estree/package.json @@ -0,0 +1,25 @@ +{ + "name": "@types/estree", + "version": "0.0.48", + "description": "TypeScript definitions for ESTree AST specification", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree", + "license": "MIT", + "contributors": [ + { + "name": "RReverser", + "url": "https://github.com/RReverser", + "githubUsername": "RReverser" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/estree" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "474f09de11b819537a7e8519b411dcbd4a51eb978402550a42a6cca2fe689bde", + "typeScriptVersion": "3.6" +} \ No newline at end of file diff --git a/node_modules/@vitejs/plugin-vue/CHANGELOG.md b/node_modules/@vitejs/plugin-vue/CHANGELOG.md new file mode 100644 index 0000000..58e05a6 --- /dev/null +++ b/node_modules/@vitejs/plugin-vue/CHANGELOG.md @@ -0,0 +1,210 @@ +# [1.6.0](https://github.com/vitejs/vite/compare/plugin-vue@1.5.0...plugin-vue@1.6.0) (2021-08-24) + + +### Features + +* **plugin-vue:** latest ref transform support ([533b002](https://github.com/vitejs/vite/commit/533b0029adc912257251b5021879ab1d676a16ab)) +* **plugin-vue:** warn compiler-sfc version mismatch ([e7263b9](https://github.com/vitejs/vite/commit/e7263b98f2e174198b322d26c6a7207d706a6639)) + + + +# [1.5.0](https://github.com/vitejs/vite/compare/plugin-vue@1.4.0...plugin-vue@1.5.0) (2021-08-24) + + + +# [1.4.0](https://github.com/vitejs/vite/compare/plugin-vue@1.3.0...plugin-vue@1.4.0) (2021-08-07) + +### Features + +* Custom Elements mode behavior changed: now only inlines the CSS and no longer exports the custom element constructor (exports the component as in normal mode). Users now need to explicitly call `defineCustomElement` on the component. This allows the custom element to be defined using an async version of the source component. + +### Bug Fixes + +* revert update dependency slash to v4 ([#4118](https://github.com/vitejs/vite/issues/4118)) ([#4519](https://github.com/vitejs/vite/issues/4519)) ([9b4fe1f](https://github.com/vitejs/vite/commit/9b4fe1fa68c522878d1bdef87d7aa02ae08e986f)) + + + +# [1.3.0](https://github.com/vitejs/vite/compare/plugin-vue@1.2.5...plugin-vue@1.3.0) (2021-07-27) + + +### Bug Fixes + +* reuse the old preprocessor after changing the lang attr ([#4224](https://github.com/vitejs/vite/issues/4224)) ([7a3c6e6](https://github.com/vitejs/vite/commit/7a3c6e616385cbc069620ae583d6739a972c0ead)) + + +### Features + +* **plugin-vue:** support importing vue files as custom elements ([3a3af6e](https://github.com/vitejs/vite/commit/3a3af6eeafbc9fc686fc909ec6a61c61283316fc)) + + + +## [1.2.5](https://github.com/vitejs/vite/compare/plugin-vue@1.2.4...plugin-vue@1.2.5) (2021-07-12) + + + +## [1.2.4](https://github.com/vitejs/vite/compare/plugin-vue@1.2.3...plugin-vue@1.2.4) (2021-06-27) + + +### Bug Fixes + +* **ssr:** normalize manifest filenames ([#3706](https://github.com/vitejs/vite/issues/3706)) ([aa8ca3f](https://github.com/vitejs/vite/commit/aa8ca3f35218c9fb48f87d3f6f4681d379ee45ca)), closes [#3303](https://github.com/vitejs/vite/issues/3303) + + + +## [1.2.3](https://github.com/vitejs/vite/compare/plugin-vue@1.2.2...plugin-vue@1.2.3) (2021-06-01) + + +### Bug Fixes + +* **plugin-vue:** rewrite default after ts compiled ([#3591](https://github.com/vitejs/vite/issues/3591)) ([ea5bafa](https://github.com/vitejs/vite/commit/ea5bafaefbafd858389f88e537cb3473b4669802)) + + + +## [1.2.2](https://github.com/vitejs/vite/compare/plugin-vue@1.2.1...plugin-vue@1.2.2) (2021-04-24) + + +### Bug Fixes + +* **plugin-vue:** add newline character before class components, fix [#2787](https://github.com/vitejs/vite/issues/2787) ([#2933](https://github.com/vitejs/vite/issues/2933)) ([8fe828e](https://github.com/vitejs/vite/commit/8fe828e9be9e9de67463af6f5dc35ebdbfdbda28)) +* **plugin-vue:** avoid duplicate import, fix [#2640](https://github.com/vitejs/vite/issues/2640) ([#2897](https://github.com/vitejs/vite/issues/2897)) ([011438d](https://github.com/vitejs/vite/commit/011438d16dc42408d5229b842d67dba28868566b)) +* **plugin-vue:** respect `hmr: false` server config, fix [#2790](https://github.com/vitejs/vite/issues/2790) ([#2797](https://github.com/vitejs/vite/issues/2797)) ([27e0c3f](https://github.com/vitejs/vite/commit/27e0c3fffd32a0ff90d06a909a5d5cc7d73f44b0)) + + + +## [1.2.1](https://github.com/vitejs/vite/compare/plugin-vue@1.2.0...plugin-vue@1.2.1) (2021-03-31) + + +### Bug Fixes + +* **plugin-vue:** allow to overwrite feature flags ([#2675](https://github.com/vitejs/vite/issues/2675)) ([a4acc16](https://github.com/vitejs/vite/commit/a4acc161e10fb6d122f808ad6211feef389d41a9)) + + + +# [1.2.0](https://github.com/vitejs/vite/compare/plugin-vue@1.1.5...plugin-vue@1.2.0) (2021-03-26) + + +### Features + +* **plugin-vue:** enable :slotted usage detection ([c40c49f](https://github.com/vitejs/vite/commit/c40c49f6fa806406364f4982fe45a69db15c204f)) + + + +## [1.1.5](https://github.com/vitejs/vite/compare/plugin-vue@1.1.4...plugin-vue@1.1.5) (2021-02-26) + + +### Bug Fixes + +* **plugin-vue:** fix hmr when emptying sfc file ([#2142](https://github.com/vitejs/vite/issues/2142)) ([493b942](https://github.com/vitejs/vite/commit/493b94259d6a499e03684d6001fea1a96d56810c)), closes [#2128](https://github.com/vitejs/vite/issues/2128) +* **plugin-vue:** handle default rewrite edge case for commented class ([2900a9a](https://github.com/vitejs/vite/commit/2900a9a6a501628588b31f7453e2fe5a71fe45ce)), closes [#2277](https://github.com/vitejs/vite/issues/2277) +* **plugin-vue:** import vue file as raw correctly ([#1923](https://github.com/vitejs/vite/issues/1923)) ([5b56d70](https://github.com/vitejs/vite/commit/5b56d70c1d173d4c5e3d9532f9c3bc6f8bfc020c)) + + + +## [1.1.4](https://github.com/vitejs/vite/compare/plugin-vue@1.1.3...plugin-vue@1.1.4) (2021-01-30) + + +### Bug Fixes + +* **plugin-vue:** handle block src pointing to dependency files ([bb7da3f](https://github.com/vitejs/vite/commit/bb7da3f0f07da6558f0e81bd82ede4cfe1785a56)), closes [#1812](https://github.com/vitejs/vite/issues/1812) + + + +## [1.1.3](https://github.com/vitejs/vite/compare/plugin-vue@1.1.2...plugin-vue@1.1.3) (2021-01-29) + + +### Bug Fixes + +* **plugin-vue:** special handling for class default export in sfc ([d3397e6](https://github.com/vitejs/vite/commit/d3397e61cd9d0761606506dcc176a1cbc845d8b5)), closes [#1476](https://github.com/vitejs/vite/issues/1476) + + + +## [1.1.2](https://github.com/vitejs/vite/compare/plugin-vue@1.1.1...plugin-vue@1.1.2) (2021-01-24) + + + +## [1.1.1](https://github.com/vitejs/vite/compare/plugin-vue@1.1.0...plugin-vue@1.1.1) (2021-01-23) + + +### Bug Fixes + +* avoid eager hmr api access ([fa37456](https://github.com/vitejs/vite/commit/fa37456584a09b52b39a61760a6d130e261886ff)) + + +### Features + +* support `base` option during dev, deprecate `build.base` ([#1556](https://github.com/vitejs/vite/issues/1556)) ([809d4bd](https://github.com/vitejs/vite/commit/809d4bd3bf62d3bc6b35f182178922d2ab2175f1)) + + + +# [1.1.0](https://github.com/vitejs/vite/compare/plugin-vue@1.0.6...plugin-vue@1.1.0) (2021-01-19) + + +### Features + +* ssr manifest for preload inference ([107e79e](https://github.com/vitejs/vite/commit/107e79e7b7d422f0d1dbe8b7b435636df7c6281c)) +* **plugin-vue:** support for vite core new ssr impl ([a93ab23](https://github.com/vitejs/vite/commit/a93ab23491ee9fee78345ddc20567e1b0ceec2a7)) + + + +## [1.0.6](https://github.com/vitejs/vite/compare/plugin-vue@1.0.5...plugin-vue@1.0.6) (2021-01-15) + + +### Bug Fixes + +* **plugin-vue:** sfc src import respect alias ([#1544](https://github.com/vitejs/vite/issues/1544)) ([d8754de](https://github.com/vitejs/vite/commit/d8754deeb16ef0d86b17dfa2a3394d0919bcd72e)), closes [#1542](https://github.com/vitejs/vite/issues/1542) + + + +## [1.0.5](https://github.com/vitejs/vite/compare/plugin-vue@1.0.4...plugin-vue@1.0.5) (2021-01-09) + + +### Bug Fixes + +* **plugin-vue:** default pug doctype ([756a0f2](https://github.com/vitejs/vite/commit/756a0f26911e5bff9c1ea3f780a0a1eccd1f1cfd)), closes [#1383](https://github.com/vitejs/vite/issues/1383) +* **plugin-vue:** pass on script and style options to compiler-sfc ([0503d42](https://github.com/vitejs/vite/commit/0503d42aaddbc4b8428c94ede07cf7b84f800cef)), closes [#1450](https://github.com/vitejs/vite/issues/1450) + + + +## [1.0.4](https://github.com/vitejs/vite/compare/plugin-vue@1.0.3...plugin-vue@1.0.4) (2021-01-04) + + +### Bug Fixes + +* **plugin-vue:** mark SFC compiler options as `Partial` ([#1316](https://github.com/vitejs/vite/issues/1316)) ([331484c](https://github.com/vitejs/vite/commit/331484c2600e96543aa8007b4940d023cb5cc19f)) + + +### Features + +* **plugin-vue:** export vue query parse API ([#1303](https://github.com/vitejs/vite/issues/1303)) ([56bcb0c](https://github.com/vitejs/vite/commit/56bcb0c475a5dff31527cad6dcd7c61fde424f5e)) + + + +## [1.0.3](https://github.com/vitejs/vite/compare/plugin-vue@1.0.2...plugin-vue@1.0.3) (2021-01-02) + + +### Bug Fixes + +* **plugin-vue:** custom block prev handling ([8dbc2b4](https://github.com/vitejs/vite/commit/8dbc2b47dd8fea4a953fb05057edb47122e2dcb7)) + + +### Code Refactoring + +* **hmr:** pass context object to `handleHotUpdate` plugin hook ([b314771](https://github.com/vitejs/vite/commit/b3147710e96a8f88ab81b2e45dbf7e7174ad976c)) + + +### BREAKING CHANGES + +* **hmr:** `handleHotUpdate` plugin hook now receives a single +`HmrContext` argument instead of multiple args. + + + +## [1.0.2](https://github.com/vitejs/vite/compare/plugin-vue@1.0.2...plugin-vue@1.0.2) (2021-01-02) + + +### Bug Fixes + +* **plugin-vue:** avoid throwing on never requested file ([48a24c1](https://github.com/vitejs/vite/commit/48a24c1fa1f64e89ca853635580911859ef5881b)) +* **plugin-vue:** custom block prev handling ([8dbc2b4](https://github.com/vitejs/vite/commit/8dbc2b47dd8fea4a953fb05057edb47122e2dcb7)) +* avoid self referencing type in plugin-vue ([9cccdaa](https://github.com/vitejs/vite/commit/9cccdaa0935ca664c8a709a89ebd1f2216565546)) +* **plugin-vue:** ensure id on descriptor ([91217f6](https://github.com/vitejs/vite/commit/91217f6d968485303e71128bb79ad4400b9b4412)) diff --git a/node_modules/@vitejs/plugin-vue/LICENSE b/node_modules/@vitejs/plugin-vue/LICENSE new file mode 100644 index 0000000..b3d494d --- /dev/null +++ b/node_modules/@vitejs/plugin-vue/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-present, Yuxi (Evan) You and 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/@vitejs/plugin-vue/README.md b/node_modules/@vitejs/plugin-vue/README.md new file mode 100644 index 0000000..ebc660c --- /dev/null +++ b/node_modules/@vitejs/plugin-vue/README.md @@ -0,0 +1,110 @@ +# @vitejs/plugin-vue [![npm](https://img.shields.io/npm/v/@vitejs/plugin-vue.svg)](https://npmjs.com/package/@vitejs/plugin-vue) + +Note: requires `@vue/compiler-sfc` as peer dependency. This is largely a port of `rollup-plugin-vue` with some vite-specific tweaks. + +```js +// vite.config.js +import vue from '@vitejs/plugin-vue' + +export default { + plugins: [vue()] +} +``` + +## Options + +```ts +export interface Options { + include?: string | RegExp | (string | RegExp)[] + exclude?: string | RegExp | (string | RegExp)[] + + ssr?: boolean + isProduction?: boolean + + /** + * Transform Vue SFCs into custom elements (requires Vue >= 3.2.0) + * - `true` -> all `*.vue` imports are converted into custom elements + * - `string | RegExp` -> matched files are converted into custom elements + * + * @default /\.ce\.vue$/ + */ + customElement?: boolean | string | RegExp | (string | RegExp)[] + + // options to pass on to @vue/compiler-sfc + script?: Partial + template?: Partial + style?: Partial +} +``` + +## Example for passing options to `@vue/compiler-dom`: + +```ts +import vue from '@vitejs/plugin-vue' + +export default { + plugins: [ + vue({ + template: { + compilerOptions: { + // ... + } + } + }) + ] +} +``` + +## Example for transforming custom blocks + +```ts +import vue from '@vitejs/plugin-vue' + +const vueI18nPlugin = { + name: 'vue-i18n', + transform(code, id) { + if (!/vue&type=i18n/.test(id)) { + return + } + if (/\.ya?ml$/.test(id)) { + code = JSON.stringify(require('js-yaml').safeLoad(code.trim())) + } + return `export default Comp => { + Comp.i18n = ${code} + }` + } +} + +export default { + plugins: [vue(), vueI18nPlugin] +} +``` + +## Using Vue SFCs as Custom Elements + +> Requires `vue@^3.2.0` & `@vitejs/plugin-vue@^1.4.0` + +Vue 3.2 introduces the `defineCustomElement` method, which works with SFCs. By default, `' + * ) + * document.type //=> 'document' + * document.nodes.length //=> 2 + * ``` + */ +export default class Document extends Container { + type: 'document' + parent: undefined + + constructor(defaults?: DocumentProps) + + /** + * Returns a `Result` instance representing the document’s CSS roots. + * + * ```js + * const root1 = postcss.parse(css1, { from: 'a.css' }) + * const root2 = postcss.parse(css2, { from: 'b.css' }) + * const document = postcss.document() + * document.append(root1) + * document.append(root2) + * const result = document.toResult({ to: 'all.css', map: true }) + * ``` + * + * @param opts Options. + * @return Result with current document’s CSS. + */ + toResult(options?: ProcessOptions): Result +} diff --git a/node_modules/postcss/lib/document.js b/node_modules/postcss/lib/document.js new file mode 100644 index 0000000..4468991 --- /dev/null +++ b/node_modules/postcss/lib/document.js @@ -0,0 +1,33 @@ +'use strict' + +let Container = require('./container') + +let LazyResult, Processor + +class Document extends Container { + constructor(defaults) { + // type needs to be passed to super, otherwise child roots won't be normalized correctly + super({ type: 'document', ...defaults }) + + if (!this.nodes) { + this.nodes = [] + } + } + + toResult(opts = {}) { + let lazy = new LazyResult(new Processor(), this, opts) + + return lazy.stringify() + } +} + +Document.registerLazyResult = dependant => { + LazyResult = dependant +} + +Document.registerProcessor = dependant => { + Processor = dependant +} + +module.exports = Document +Document.default = Document diff --git a/node_modules/postcss/lib/fromJSON.d.ts b/node_modules/postcss/lib/fromJSON.d.ts new file mode 100644 index 0000000..13b169c --- /dev/null +++ b/node_modules/postcss/lib/fromJSON.d.ts @@ -0,0 +1,5 @@ +import { JSONHydrator } from './postcss.js' + +declare const fromJSON: JSONHydrator + +export default fromJSON diff --git a/node_modules/postcss/lib/fromJSON.js b/node_modules/postcss/lib/fromJSON.js new file mode 100644 index 0000000..09f2b89 --- /dev/null +++ b/node_modules/postcss/lib/fromJSON.js @@ -0,0 +1,54 @@ +'use strict' + +let Declaration = require('./declaration') +let PreviousMap = require('./previous-map') +let Comment = require('./comment') +let AtRule = require('./at-rule') +let Input = require('./input') +let Root = require('./root') +let Rule = require('./rule') + +function fromJSON(json, inputs) { + if (Array.isArray(json)) return json.map(n => fromJSON(n)) + + let { inputs: ownInputs, ...defaults } = json + if (ownInputs) { + inputs = [] + for (let input of ownInputs) { + let inputHydrated = { ...input, __proto__: Input.prototype } + if (inputHydrated.map) { + inputHydrated.map = { + ...inputHydrated.map, + __proto__: PreviousMap.prototype + } + } + inputs.push(inputHydrated) + } + } + if (defaults.nodes) { + defaults.nodes = json.nodes.map(n => fromJSON(n, inputs)) + } + if (defaults.source) { + let { inputId, ...source } = defaults.source + defaults.source = source + if (inputId != null) { + defaults.source.input = inputs[inputId] + } + } + if (defaults.type === 'root') { + return new Root(defaults) + } else if (defaults.type === 'decl') { + return new Declaration(defaults) + } else if (defaults.type === 'rule') { + return new Rule(defaults) + } else if (defaults.type === 'comment') { + return new Comment(defaults) + } else if (defaults.type === 'atrule') { + return new AtRule(defaults) + } else { + throw new Error('Unknown node type: ' + json.type) + } +} + +module.exports = fromJSON +fromJSON.default = fromJSON diff --git a/node_modules/postcss/lib/input.d.ts b/node_modules/postcss/lib/input.d.ts new file mode 100644 index 0000000..399f434 --- /dev/null +++ b/node_modules/postcss/lib/input.d.ts @@ -0,0 +1,130 @@ +import { ProcessOptions } from './postcss.js' +import PreviousMap from './previous-map.js' + +export interface FilePosition { + /** + * URL for the source file. + */ + url: string + + /** + * Absolute path to the source file. + */ + file?: string + + /** + * Line in source file. + */ + line: number + + /** + * Column in source file. + */ + column: number + + /** + * Source code. + */ + source?: string +} + +/** + * Represents the source CSS. + * + * ```js + * const root = postcss.parse(css, { from: file }) + * const input = root.source.input + * ``` + */ +export default class Input { + /** + * Input CSS source. + * + * ```js + * const input = postcss.parse('a{}', { from: file }).input + * input.css //=> "a{}" + * ``` + */ + css: string + + /** + * The input source map passed from a compilation step before PostCSS + * (for example, from Sass compiler). + * + * ```js + * root.source.input.map.consumer().sources //=> ['a.sass'] + * ``` + */ + map: PreviousMap + + /** + * The absolute path to the CSS source file defined + * with the `from` option. + * + * ```js + * const root = postcss.parse(css, { from: 'a.css' }) + * root.source.input.file //=> '/home/ai/a.css' + * ``` + */ + file?: string + + /** + * The unique ID of the CSS source. It will be created if `from` option + * is not provided (because PostCSS does not know the file path). + * + * ```js + * const root = postcss.parse(css) + * root.source.input.file //=> undefined + * root.source.input.id //=> "" + * ``` + */ + id?: string + + /** + * The flag to indicate whether or not the source code has Unicode BOM. + */ + hasBOM: boolean + + /** + * @param css Input CSS source. + * @param opts Process options. + */ + constructor(css: string, opts?: ProcessOptions) + + /** + * The CSS source identifier. Contains `Input#file` if the user + * set the `from` option, or `Input#id` if they did not. + * + * ```js + * const root = postcss.parse(css, { from: 'a.css' }) + * root.source.input.from //=> "/home/ai/a.css" + * + * const root = postcss.parse(css) + * root.source.input.from //=> "" + * ``` + */ + get from(): string + + /** + * Reads the input source map and returns a symbol position + * in the input source (e.g., in a Sass file that was compiled + * to CSS before being passed to PostCSS). + * + * ```js + * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 } + * ``` + * + * @param line Line in input CSS. + * @param column Column in input CSS. + * + * @return Position in input source. + */ + origin(line: number, column: number): FilePosition | false + + /** + * Converts source offset to line and column. + * + * @param offset Source offset. + */ + fromOffset(offset: number): { line: number; col: number } | null +} diff --git a/node_modules/postcss/lib/input.js b/node_modules/postcss/lib/input.js new file mode 100644 index 0000000..2a1d26b --- /dev/null +++ b/node_modules/postcss/lib/input.js @@ -0,0 +1,216 @@ +'use strict' + +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { fileURLToPath, pathToFileURL } = require('url') +let { resolve, isAbsolute } = require('path') +let { nanoid } = require('nanoid/non-secure') + +let terminalHighlight = require('./terminal-highlight') +let CssSyntaxError = require('./css-syntax-error') +let PreviousMap = require('./previous-map') + +let fromOffsetCache = Symbol('fromOffsetCache') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(resolve && isAbsolute) + +class Input { + constructor(css, opts = {}) { + if ( + css === null || + typeof css === 'undefined' || + (typeof css === 'object' && !css.toString) + ) { + throw new Error(`PostCSS received ${css} instead of CSS string`) + } + + this.css = css.toString() + + if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { + this.hasBOM = true + this.css = this.css.slice(1) + } else { + this.hasBOM = false + } + + if (opts.from) { + if ( + !pathAvailable || + /^\w+:\/\//.test(opts.from) || + isAbsolute(opts.from) + ) { + this.file = opts.from + } else { + this.file = resolve(opts.from) + } + } + + if (pathAvailable && sourceMapAvailable) { + let map = new PreviousMap(this.css, opts) + if (map.text) { + this.map = map + let file = map.consumer().file + if (!this.file && file) this.file = this.mapResolve(file) + } + } + + if (!this.file) { + this.id = '' + } + if (this.map) this.map.file = this.from + } + + fromOffset(offset) { + let lastLine, lineToIndex + if (!this[fromOffsetCache]) { + let lines = this.css.split('\n') + lineToIndex = new Array(lines.length) + let prevIndex = 0 + + for (let i = 0, l = lines.length; i < l; i++) { + lineToIndex[i] = prevIndex + prevIndex += lines[i].length + 1 + } + + this[fromOffsetCache] = lineToIndex + } else { + lineToIndex = this[fromOffsetCache] + } + lastLine = lineToIndex[lineToIndex.length - 1] + + let min = 0 + if (offset >= lastLine) { + min = lineToIndex.length - 1 + } else { + let max = lineToIndex.length - 2 + let mid + while (min < max) { + mid = min + ((max - min) >> 1) + if (offset < lineToIndex[mid]) { + max = mid - 1 + } else if (offset >= lineToIndex[mid + 1]) { + min = mid + 1 + } else { + min = mid + break + } + } + } + return { + line: min + 1, + col: offset - lineToIndex[min] + 1 + } + } + + error(message, line, column, opts = {}) { + let result + if (!column) { + let pos = this.fromOffset(line) + line = pos.line + column = pos.col + } + let origin = this.origin(line, column) + if (origin) { + result = new CssSyntaxError( + message, + origin.line, + origin.column, + origin.source, + origin.file, + opts.plugin + ) + } else { + result = new CssSyntaxError( + message, + line, + column, + this.css, + this.file, + opts.plugin + ) + } + + result.input = { line, column, source: this.css } + if (this.file) { + if (pathToFileURL) { + result.input.url = pathToFileURL(this.file).toString() + } + result.input.file = this.file + } + + return result + } + + origin(line, column) { + if (!this.map) return false + let consumer = this.map.consumer() + + let from = consumer.originalPositionFor({ line, column }) + if (!from.source) return false + + let fromUrl + + if (isAbsolute(from.source)) { + fromUrl = pathToFileURL(from.source) + } else { + fromUrl = new URL( + from.source, + this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile) + ) + } + + let result = { + url: fromUrl.toString(), + line: from.line, + column: from.column + } + + if (fromUrl.protocol === 'file:') { + if (fileURLToPath) { + result.file = fileURLToPath(fromUrl) + } else { + // istanbul ignore next + throw new Error(`file: protocol is not available in this PostCSS build`) + } + } + + let source = consumer.sourceContentFor(from.source) + if (source) result.source = source + + return result + } + + mapResolve(file) { + if (/^\w+:\/\//.test(file)) { + return file + } + return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file) + } + + get from() { + return this.file || this.id + } + + toJSON() { + let json = {} + for (let name of ['hasBOM', 'css', 'file', 'id']) { + if (this[name] != null) { + json[name] = this[name] + } + } + if (this.map) { + json.map = { ...this.map } + if (json.map.consumerCache) { + json.map.consumerCache = undefined + } + } + return json + } +} + +module.exports = Input +Input.default = Input + +if (terminalHighlight && terminalHighlight.registerInput) { + terminalHighlight.registerInput(Input) +} diff --git a/node_modules/postcss/lib/lazy-result.d.ts b/node_modules/postcss/lib/lazy-result.d.ts new file mode 100644 index 0000000..9da0fb5 --- /dev/null +++ b/node_modules/postcss/lib/lazy-result.d.ts @@ -0,0 +1,175 @@ +import Result, { Message, ResultOptions } from './result.js' +import { SourceMap } from './postcss.js' +import Processor from './processor.js' +import Warning from './warning.js' +import Root from './root.js' + +/** + * A Promise proxy for the result of PostCSS transformations. + * + * A `LazyResult` instance is returned by `Processor#process`. + * + * ```js + * const lazy = postcss([autoprefixer]).process(css) + * ``` + */ +export default class LazyResult implements PromiseLike { + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls `onFulfilled` with a Result instance. If a plugin throws + * an error, the `onRejected` callback will be executed. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css, { from: cssPath }).then(result => { + * console.log(result.css) + * }) + * ``` + */ + then: Promise['then'] + + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls onRejected for each error thrown in any plugin. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css).then(result => { + * console.log(result.css) + * }).catch(error => { + * console.error(error) + * }) + * ``` + */ + catch: Promise['catch'] + + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls onFinally on any error or when all plugins will finish work. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css).finally(() => { + * console.log('processing ended') + * }) + * ``` + */ + finally: Promise['finally'] + + /** + * @param processor Processor used for this transformation. + * @param css CSS to parse and transform. + * @param opts Options from the `Processor#process` or `Root#toResult`. + */ + constructor(processor: Processor, css: string, opts: ResultOptions) + + /** + * Returns the default string description of an object. + * Required to implement the Promise interface. + */ + get [Symbol.toStringTag](): string + + /** + * Returns a `Processor` instance, which will be used + * for CSS transformations. + */ + get processor(): Processor + + /** + * Options from the `Processor#process` call. + */ + get opts(): ResultOptions + + /** + * Processes input CSS through synchronous plugins, converts `Root` + * to a CSS string and returns `Result#css`. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. This is why this method is only + * for debug purpose, you should always use `LazyResult#then`. + */ + get css(): string + + /** + * An alias for the `css` property. Use it with syntaxes + * that generate non-CSS output. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. This is why this method is only + * for debug purpose, you should always use `LazyResult#then`. + */ + get content(): string + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#map`. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. This is why this method is only + * for debug purpose, you should always use `LazyResult#then`. + */ + get map(): SourceMap + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#root`. + * + * This property will only work with synchronous plugins. If the processor + * contains any asynchronous plugins it will throw an error. + * + * This is why this method is only for debug purpose, + * you should always use `LazyResult#then`. + */ + get root(): Root + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#messages`. + * + * This property will only work with synchronous plugins. If the processor + * contains any asynchronous plugins it will throw an error. + * + * This is why this method is only for debug purpose, + * you should always use `LazyResult#then`. + */ + get messages(): Message[] + + /** + * Processes input CSS through synchronous plugins + * and calls `Result#warnings`. + * + * @return Warnings from plugins. + */ + warnings(): Warning[] + + /** + * Alias for the `LazyResult#css` property. + * + * ```js + * lazy + '' === lazy.css + * ``` + * + * @return Output CSS. + */ + toString(): string + + /** + * Run plugin in sync way and return `Result`. + * + * @return Result with output content. + */ + sync(): Result + + /** + * Run plugin in async way and return `Result`. + * + * @return Result with output content. + */ + async(): Promise +} diff --git a/node_modules/postcss/lib/lazy-result.js b/node_modules/postcss/lib/lazy-result.js new file mode 100644 index 0000000..6069ba6 --- /dev/null +++ b/node_modules/postcss/lib/lazy-result.js @@ -0,0 +1,548 @@ +'use strict' + +let { isClean, my } = require('./symbols') +let MapGenerator = require('./map-generator') +let stringify = require('./stringify') +let Container = require('./container') +let Document = require('./document') +let warnOnce = require('./warn-once') +let Result = require('./result') +let parse = require('./parse') +let Root = require('./root') + +const TYPE_TO_CLASS_NAME = { + document: 'Document', + root: 'Root', + atrule: 'AtRule', + rule: 'Rule', + decl: 'Declaration', + comment: 'Comment' +} + +const PLUGIN_PROPS = { + postcssPlugin: true, + prepare: true, + Once: true, + Document: true, + Root: true, + Declaration: true, + Rule: true, + AtRule: true, + Comment: true, + DeclarationExit: true, + RuleExit: true, + AtRuleExit: true, + CommentExit: true, + RootExit: true, + DocumentExit: true, + OnceExit: true +} + +const NOT_VISITORS = { + postcssPlugin: true, + prepare: true, + Once: true +} + +const CHILDREN = 0 + +function isPromise(obj) { + return typeof obj === 'object' && typeof obj.then === 'function' +} + +function getEvents(node) { + let key = false + let type = TYPE_TO_CLASS_NAME[node.type] + if (node.type === 'decl') { + key = node.prop.toLowerCase() + } else if (node.type === 'atrule') { + key = node.name.toLowerCase() + } + + if (key && node.append) { + return [ + type, + type + '-' + key, + CHILDREN, + type + 'Exit', + type + 'Exit-' + key + ] + } else if (key) { + return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key] + } else if (node.append) { + return [type, CHILDREN, type + 'Exit'] + } else { + return [type, type + 'Exit'] + } +} + +function toStack(node) { + let events + if (node.type === 'document') { + events = ['Document', CHILDREN, 'DocumentExit'] + } else if (node.type === 'root') { + events = ['Root', CHILDREN, 'RootExit'] + } else { + events = getEvents(node) + } + + return { + node, + events, + eventIndex: 0, + visitors: [], + visitorIndex: 0, + iterator: 0 + } +} + +function cleanMarks(node) { + node[isClean] = false + if (node.nodes) node.nodes.forEach(i => cleanMarks(i)) + return node +} + +let postcss = {} + +class LazyResult { + constructor(processor, css, opts) { + this.stringified = false + this.processed = false + + let root + if ( + typeof css === 'object' && + css !== null && + (css.type === 'root' || css.type === 'document') + ) { + root = cleanMarks(css) + } else if (css instanceof LazyResult || css instanceof Result) { + root = cleanMarks(css.root) + if (css.map) { + if (typeof opts.map === 'undefined') opts.map = {} + if (!opts.map.inline) opts.map.inline = false + opts.map.prev = css.map + } + } else { + let parser = parse + if (opts.syntax) parser = opts.syntax.parse + if (opts.parser) parser = opts.parser + if (parser.parse) parser = parser.parse + + try { + root = parser(css, opts) + } catch (error) { + this.processed = true + this.error = error + } + + if (root && !root[my]) { + // istanbul ignore next + Container.rebuild(root) + } + } + + this.result = new Result(processor, root, opts) + this.helpers = { ...postcss, result: this.result, postcss } + this.plugins = this.processor.plugins.map(plugin => { + if (typeof plugin === 'object' && plugin.prepare) { + return { ...plugin, ...plugin.prepare(this.result) } + } else { + return plugin + } + }) + } + + get [Symbol.toStringTag]() { + return 'LazyResult' + } + + get processor() { + return this.result.processor + } + + get opts() { + return this.result.opts + } + + get css() { + return this.stringify().css + } + + get content() { + return this.stringify().content + } + + get map() { + return this.stringify().map + } + + get root() { + return this.sync().root + } + + get messages() { + return this.sync().messages + } + + warnings() { + return this.sync().warnings() + } + + toString() { + return this.css + } + + then(onFulfilled, onRejected) { + if (process.env.NODE_ENV !== 'production') { + if (!('from' in this.opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ) + } + } + return this.async().then(onFulfilled, onRejected) + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + async() { + if (this.error) return Promise.reject(this.error) + if (this.processed) return Promise.resolve(this.result) + if (!this.processing) { + this.processing = this.runAsync() + } + return this.processing + } + + sync() { + if (this.error) throw this.error + if (this.processed) return this.result + this.processed = true + + if (this.processing) { + throw this.getAsyncError() + } + + for (let plugin of this.plugins) { + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + this.walkSync(root) + } + if (this.listeners.OnceExit) { + if (root.type === 'document') { + for (let subRoot of root.nodes) { + this.visitSync(this.listeners.OnceExit, subRoot) + } + } else { + this.visitSync(this.listeners.OnceExit, root) + } + } + } + + return this.result + } + + stringify() { + if (this.error) throw this.error + if (this.stringified) return this.result + this.stringified = true + + this.sync() + + let opts = this.result.opts + let str = stringify + if (opts.syntax) str = opts.syntax.stringify + if (opts.stringifier) str = opts.stringifier + if (str.stringify) str = str.stringify + + let map = new MapGenerator(str, this.result.root, this.result.opts) + let data = map.generate() + this.result.css = data[0] + this.result.map = data[1] + + return this.result + } + + walkSync(node) { + node[isClean] = true + let events = getEvents(node) + for (let event of events) { + if (event === CHILDREN) { + if (node.nodes) { + node.each(child => { + if (!child[isClean]) this.walkSync(child) + }) + } + } else { + let visitors = this.listeners[event] + if (visitors) { + if (this.visitSync(visitors, node.toProxy())) return + } + } + } + } + + visitSync(visitors, node) { + for (let [plugin, visitor] of visitors) { + this.result.lastPlugin = plugin + let promise + try { + promise = visitor(node, this.helpers) + } catch (e) { + throw this.handleError(e, node.proxyOf) + } + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + return true + } + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + } + + runOnRoot(plugin) { + this.result.lastPlugin = plugin + try { + if (typeof plugin === 'object' && plugin.Once) { + if (this.result.root.type === 'document') { + let roots = this.result.root.nodes.map(root => + plugin.Once(root, this.helpers) + ) + + if (isPromise(roots[0])) { + return Promise.all(roots) + } + + return roots + } + + return plugin.Once(this.result.root, this.helpers) + } else if (typeof plugin === 'function') { + return plugin(this.result.root, this.result) + } + } catch (error) { + throw this.handleError(error) + } + } + + getAsyncError() { + throw new Error('Use process(css).then(cb) to work with async plugins') + } + + handleError(error, node) { + let plugin = this.result.lastPlugin + try { + if (node) node.addToError(error) + this.error = error + if (error.name === 'CssSyntaxError' && !error.plugin) { + error.plugin = plugin.postcssPlugin + error.setMessage() + } else if (plugin.postcssVersion) { + if (process.env.NODE_ENV !== 'production') { + let pluginName = plugin.postcssPlugin + let pluginVer = plugin.postcssVersion + let runtimeVer = this.result.processor.version + let a = pluginVer.split('.') + let b = runtimeVer.split('.') + + if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { + console.error( + 'Unknown error from PostCSS plugin. Your current PostCSS ' + + 'version is ' + + runtimeVer + + ', but ' + + pluginName + + ' uses ' + + pluginVer + + '. Perhaps this is the source of the error below.' + ) + } + } + } + } catch (err) { + // istanbul ignore next + if (console && console.error) console.error(err) + } + return error + } + + async runAsync() { + this.plugin = 0 + for (let i = 0; i < this.plugins.length; i++) { + let plugin = this.plugins[i] + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + try { + await promise + } catch (error) { + throw this.handleError(error) + } + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + let stack = [toStack(root)] + while (stack.length > 0) { + let promise = this.visitTick(stack) + if (isPromise(promise)) { + try { + await promise + } catch (e) { + let node = stack[stack.length - 1].node + throw this.handleError(e, node) + } + } + } + } + + if (this.listeners.OnceExit) { + for (let [plugin, visitor] of this.listeners.OnceExit) { + this.result.lastPlugin = plugin + try { + if (root.type === 'document') { + let roots = root.nodes.map(subRoot => + visitor(subRoot, this.helpers) + ) + + await Promise.all(roots) + } else { + await visitor(root, this.helpers) + } + } catch (e) { + throw this.handleError(e) + } + } + } + } + + this.processed = true + return this.stringify() + } + + prepareVisitors() { + this.listeners = {} + let add = (plugin, type, cb) => { + if (!this.listeners[type]) this.listeners[type] = [] + this.listeners[type].push([plugin, cb]) + } + for (let plugin of this.plugins) { + if (typeof plugin === 'object') { + for (let event in plugin) { + if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { + throw new Error( + `Unknown event ${event} in ${plugin.postcssPlugin}. ` + + `Try to update PostCSS (${this.processor.version} now).` + ) + } + if (!NOT_VISITORS[event]) { + if (typeof plugin[event] === 'object') { + for (let filter in plugin[event]) { + if (filter === '*') { + add(plugin, event, plugin[event][filter]) + } else { + add( + plugin, + event + '-' + filter.toLowerCase(), + plugin[event][filter] + ) + } + } + } else if (typeof plugin[event] === 'function') { + add(plugin, event, plugin[event]) + } + } + } + } + } + this.hasListener = Object.keys(this.listeners).length > 0 + } + + visitTick(stack) { + let visit = stack[stack.length - 1] + let { node, visitors } = visit + + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + stack.pop() + return + } + + if (visitors.length > 0 && visit.visitorIndex < visitors.length) { + let [plugin, visitor] = visitors[visit.visitorIndex] + visit.visitorIndex += 1 + if (visit.visitorIndex === visitors.length) { + visit.visitors = [] + visit.visitorIndex = 0 + } + this.result.lastPlugin = plugin + try { + return visitor(node.toProxy(), this.helpers) + } catch (e) { + throw this.handleError(e, node) + } + } + + if (visit.iterator !== 0) { + let iterator = visit.iterator + let child + while ((child = node.nodes[node.indexes[iterator]])) { + node.indexes[iterator] += 1 + if (!child[isClean]) { + child[isClean] = true + stack.push(toStack(child)) + return + } + } + visit.iterator = 0 + delete node.indexes[iterator] + } + + let events = visit.events + while (visit.eventIndex < events.length) { + let event = events[visit.eventIndex] + visit.eventIndex += 1 + if (event === CHILDREN) { + if (node.nodes && node.nodes.length) { + node[isClean] = true + visit.iterator = node.getIterator() + } + return + } else if (this.listeners[event]) { + visit.visitors = this.listeners[event] + return + } + } + stack.pop() + } +} + +LazyResult.registerPostcss = dependant => { + postcss = dependant +} + +module.exports = LazyResult +LazyResult.default = LazyResult + +Root.registerLazyResult(LazyResult) +Document.registerLazyResult(LazyResult) diff --git a/node_modules/postcss/lib/list.d.ts b/node_modules/postcss/lib/list.d.ts new file mode 100644 index 0000000..79841ed --- /dev/null +++ b/node_modules/postcss/lib/list.d.ts @@ -0,0 +1,51 @@ +export type List = { + /** + * Safely splits values. + * + * ```js + * Once (root, { list }) { + * list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)'] + * } + * ``` + * + * @param string separated values. + * @param separators array of separators. + * @param last boolean indicator. + * @return Split values. + */ + split(string: string, separators: string[], last: boolean): string[] + /** + * Safely splits space-separated values (such as those for `background`, + * `border-radius`, and other shorthand properties). + * + * ```js + * Once (root, { list }) { + * list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)'] + * } + * ``` + * + * @param str Space-separated values. + * @return Split values. + */ + space(str: string): string[] + + /** + * Safely splits comma-separated values (such as those for `transition-*` + * and `background` properties). + * + * ```js + * Once (root, { list }) { + * list.comma('black, linear-gradient(white, black)') + * //=> ['black', 'linear-gradient(white, black)'] + * } + * ``` + * + * @param str Comma-separated values. + * @return Split values. + */ + comma(str: string): string[] +} + +declare const list: List + +export default list diff --git a/node_modules/postcss/lib/list.js b/node_modules/postcss/lib/list.js new file mode 100644 index 0000000..08e9416 --- /dev/null +++ b/node_modules/postcss/lib/list.js @@ -0,0 +1,56 @@ +'use strict' + +let list = { + split(string, separators, last) { + let array = [] + let current = '' + let split = false + + let func = 0 + let quote = false + let escape = false + + for (let letter of string) { + if (escape) { + escape = false + } else if (letter === '\\') { + escape = true + } else if (quote) { + if (letter === quote) { + quote = false + } + } else if (letter === '"' || letter === "'") { + quote = letter + } else if (letter === '(') { + func += 1 + } else if (letter === ')') { + if (func > 0) func -= 1 + } else if (func === 0) { + if (separators.includes(letter)) split = true + } + + if (split) { + if (current !== '') array.push(current.trim()) + current = '' + split = false + } else { + current += letter + } + } + + if (last || current !== '') array.push(current.trim()) + return array + }, + + space(string) { + let spaces = [' ', '\n', '\t'] + return list.split(string, spaces) + }, + + comma(string) { + return list.split(string, [','], true) + } +} + +module.exports = list +list.default = list diff --git a/node_modules/postcss/lib/map-generator.js b/node_modules/postcss/lib/map-generator.js new file mode 100644 index 0000000..a86cc67 --- /dev/null +++ b/node_modules/postcss/lib/map-generator.js @@ -0,0 +1,300 @@ +'use strict' + +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { dirname, resolve, relative, sep } = require('path') +let { pathToFileURL } = require('url') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(dirname && resolve && relative && sep) + +class MapGenerator { + constructor(stringify, root, opts) { + this.stringify = stringify + this.mapOpts = opts.map || {} + this.root = root + this.opts = opts + } + + isMap() { + if (typeof this.opts.map !== 'undefined') { + return !!this.opts.map + } + return this.previous().length > 0 + } + + previous() { + if (!this.previousMaps) { + this.previousMaps = [] + this.root.walk(node => { + if (node.source && node.source.input.map) { + let map = node.source.input.map + if (!this.previousMaps.includes(map)) { + this.previousMaps.push(map) + } + } + }) + } + + return this.previousMaps + } + + isInline() { + if (typeof this.mapOpts.inline !== 'undefined') { + return this.mapOpts.inline + } + + let annotation = this.mapOpts.annotation + if (typeof annotation !== 'undefined' && annotation !== true) { + return false + } + + if (this.previous().length) { + return this.previous().some(i => i.inline) + } + return true + } + + isSourcesContent() { + if (typeof this.mapOpts.sourcesContent !== 'undefined') { + return this.mapOpts.sourcesContent + } + if (this.previous().length) { + return this.previous().some(i => i.withContent()) + } + return true + } + + clearAnnotation() { + if (this.mapOpts.annotation === false) return + + let node + for (let i = this.root.nodes.length - 1; i >= 0; i--) { + node = this.root.nodes[i] + if (node.type !== 'comment') continue + if (node.text.indexOf('# sourceMappingURL=') === 0) { + this.root.removeChild(i) + } + } + } + + setSourcesContent() { + let already = {} + this.root.walk(node => { + if (node.source) { + let from = node.source.input.from + if (from && !already[from]) { + already[from] = true + this.map.setSourceContent( + this.toUrl(this.path(from)), + node.source.input.css + ) + } + } + }) + } + + applyPrevMaps() { + for (let prev of this.previous()) { + let from = this.toUrl(this.path(prev.file)) + let root = prev.root || dirname(prev.file) + let map + + if (this.mapOpts.sourcesContent === false) { + map = new SourceMapConsumer(prev.text) + if (map.sourcesContent) { + map.sourcesContent = map.sourcesContent.map(() => null) + } + } else { + map = prev.consumer() + } + + this.map.applySourceMap(map, from, this.toUrl(this.path(root))) + } + } + + isAnnotation() { + if (this.isInline()) { + return true + } + if (typeof this.mapOpts.annotation !== 'undefined') { + return this.mapOpts.annotation + } + if (this.previous().length) { + return this.previous().some(i => i.annotation) + } + return true + } + + toBase64(str) { + if (Buffer) { + return Buffer.from(str).toString('base64') + } else { + // istanbul ignore next + return window.btoa(unescape(encodeURIComponent(str))) + } + } + + addAnnotation() { + let content + + if (this.isInline()) { + content = + 'data:application/json;base64,' + this.toBase64(this.map.toString()) + } else if (typeof this.mapOpts.annotation === 'string') { + content = this.mapOpts.annotation + } else if (typeof this.mapOpts.annotation === 'function') { + content = this.mapOpts.annotation(this.opts.to, this.root) + } else { + content = this.outputFile() + '.map' + } + + let eol = '\n' + if (this.css.includes('\r\n')) eol = '\r\n' + + this.css += eol + '/*# sourceMappingURL=' + content + ' */' + } + + outputFile() { + if (this.opts.to) { + return this.path(this.opts.to) + } + if (this.opts.from) { + return this.path(this.opts.from) + } + return 'to.css' + } + + generateMap() { + this.generateString() + if (this.isSourcesContent()) this.setSourcesContent() + if (this.previous().length > 0) this.applyPrevMaps() + if (this.isAnnotation()) this.addAnnotation() + + if (this.isInline()) { + return [this.css] + } + return [this.css, this.map] + } + + path(file) { + if (file.indexOf('<') === 0) return file + if (/^\w+:\/\//.test(file)) return file + if (this.mapOpts.absolute) return file + + let from = this.opts.to ? dirname(this.opts.to) : '.' + + if (typeof this.mapOpts.annotation === 'string') { + from = dirname(resolve(from, this.mapOpts.annotation)) + } + + file = relative(from, file) + return file + } + + toUrl(path) { + if (sep === '\\') { + // istanbul ignore next + path = path.replace(/\\/g, '/') + } + return encodeURI(path).replace(/[#?]/g, encodeURIComponent) + } + + sourcePath(node) { + if (this.mapOpts.from) { + return this.toUrl(this.mapOpts.from) + } else if (this.mapOpts.absolute) { + if (pathToFileURL) { + return pathToFileURL(node.source.input.from).toString() + } else { + // istanbul ignore next + throw new Error( + '`map.absolute` option is not available in this PostCSS build' + ) + } + } else { + return this.toUrl(this.path(node.source.input.from)) + } + } + + generateString() { + this.css = '' + this.map = new SourceMapGenerator({ file: this.outputFile() }) + + let line = 1 + let column = 1 + + let noSource = '' + let mapping = { + source: '', + generated: { line: 0, column: 0 }, + original: { line: 0, column: 0 } + } + + let lines, last + this.stringify(this.root, (str, node, type) => { + this.css += str + + if (node && type !== 'end') { + mapping.generated.line = line + mapping.generated.column = column - 1 + if (node.source && node.source.start) { + mapping.source = this.sourcePath(node) + mapping.original.line = node.source.start.line + mapping.original.column = node.source.start.column - 1 + this.map.addMapping(mapping) + } else { + mapping.source = noSource + mapping.original.line = 1 + mapping.original.column = 0 + this.map.addMapping(mapping) + } + } + + lines = str.match(/\n/g) + if (lines) { + line += lines.length + last = str.lastIndexOf('\n') + column = str.length - last + } else { + column += str.length + } + + if (node && type !== 'start') { + let p = node.parent || { raws: {} } + if (node.type !== 'decl' || node !== p.last || p.raws.semicolon) { + if (node.source && node.source.end) { + mapping.source = this.sourcePath(node) + mapping.original.line = node.source.end.line + mapping.original.column = node.source.end.column - 1 + mapping.generated.line = line + mapping.generated.column = column - 2 + this.map.addMapping(mapping) + } else { + mapping.source = noSource + mapping.original.line = 1 + mapping.original.column = 0 + mapping.generated.line = line + mapping.generated.column = column - 1 + this.map.addMapping(mapping) + } + } + } + }) + } + + generate() { + this.clearAnnotation() + + if (pathAvailable && sourceMapAvailable && this.isMap()) { + return this.generateMap() + } + + let result = '' + this.stringify(this.root, i => { + result += i + }) + return [result] + } +} + +module.exports = MapGenerator diff --git a/node_modules/postcss/lib/node.d.ts b/node_modules/postcss/lib/node.d.ts new file mode 100644 index 0000000..9e46e87 --- /dev/null +++ b/node_modules/postcss/lib/node.d.ts @@ -0,0 +1,444 @@ +import Declaration, { DeclarationProps } from './declaration.js' +import Comment, { CommentProps } from './comment.js' +import { Stringifier, Syntax } from './postcss.js' +import AtRule, { AtRuleProps } from './at-rule.js' +import Rule, { RuleProps } from './rule.js' +import { WarningOptions } from './warning.js' +import CssSyntaxError from './css-syntax-error.js' +import Result from './result.js' +import Input from './input.js' +import Root from './root.js' +import Document from './document.js' +import Container from './container.js' + +export type ChildNode = AtRule | Rule | Declaration | Comment + +export type AnyNode = AtRule | Rule | Declaration | Comment | Root | Document + +export type ChildProps = + | AtRuleProps + | RuleProps + | DeclarationProps + | CommentProps + +export interface Position { + /** + * Source offset in file. It starts from 0. + */ + offset: number + + /** + * Source line in file. In contrast to `offset` it starts from 1. + */ + column: number + + /** + * Source column in file. + */ + line: number +} + +export interface Source { + /** + * The file source of the node. + */ + input: Input + /** + * The starting position of the node’s source. + */ + start?: Position + /** + * The ending position of the node's source. + */ + end?: Position +} + +export interface NodeProps { + source?: Source +} + +interface NodeErrorOptions { + /** + * Plugin name that created this error. PostCSS will set it automatically. + */ + plugin?: string + /** + * A word inside a node's string, that should be highlighted as source + * of error. + */ + word?: string + /** + * An index inside a node's string that should be highlighted as source + * of error. + */ + index?: number +} + +/** + * All node classes inherit the following common methods. + * + * You should not extend this classes to create AST for selector or value + * parser. + */ +export default abstract class Node { + /** + * tring representing the node’s type. Possible values are `root`, `atrule`, + * `rule`, `decl`, or `comment`. + * + * ```js + * new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl' + * ``` + */ + type: string + + /** + * The node’s parent node. + * + * ```js + * root.nodes[0].parent === root + * ``` + */ + parent: Document | Container | undefined + + /** + * The input source of the node. + * + * The property is used in source map generation. + * + * If you create a node manually (e.g., with `postcss.decl()`), + * that node will not have a `source` property and will be absent + * from the source map. For this reason, the plugin developer should + * consider cloning nodes to create new ones (in which case the new node’s + * source will reference the original, cloned node) or setting + * the `source` property manually. + * + * ```js + * decl.source.input.from //=> '/home/ai/a.sass' + * decl.source.start //=> { line: 10, column: 2 } + * decl.source.end //=> { line: 10, column: 12 } + * ``` + * + * ```js + * // Bad + * const prefixed = postcss.decl({ + * prop: '-moz-' + decl.prop, + * value: decl.value + * }) + * + * // Good + * const prefixed = decl.clone({ prop: '-moz-' + decl.prop }) + * ``` + * + * ```js + * if (atrule.name === 'add-link') { + * const rule = postcss.rule({ selector: 'a', source: atrule.source }) + * atrule.parent.insertBefore(atrule, rule) + * } + * ``` + */ + source?: Source + + /** + * Information to generate byte-to-byte equal node string as it was + * in the origin input. + * + * Every parser saves its own properties, + * but the default CSS parser uses: + * + * * `before`: the space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + * * `after`: the space symbols after the last child of the node + * to the end of the node. + * * `between`: the symbols between the property and value + * for declarations, selector and `{` for rules, or last parameter + * and `{` for at-rules. + * * `semicolon`: contains true if the last child has + * an (optional) semicolon. + * * `afterName`: the space between the at-rule name and its parameters. + * * `left`: the space symbols between `/*` and the comment’s text. + * * `right`: the space symbols between the comment’s text + * and */. + * * `important`: the content of the important statement, + * if it is not just `!important`. + * + * PostCSS cleans selectors, declaration values and at-rule parameters + * from comments and extra spaces, but it stores origin content in raws + * properties. As such, if you don’t change a declaration’s value, + * PostCSS will use the raw value with comments. + * + * ```js + * const root = postcss.parse('a {\n color:black\n}') + * root.first.first.raws //=> { before: '\n ', between: ':' } + * ``` + */ + raws: any + + /** + * @param defaults Value for node properties. + */ + constructor(defaults?: object) + + /** + * Returns a `CssSyntaxError` instance containing the original position + * of the node in the source, showing line and column numbers and also + * a small excerpt to facilitate debugging. + * + * If present, an input source map will be used to get the original position + * of the source, even from a previous compilation step + * (e.g., from Sass compilation). + * + * This method produces very useful error messages. + * + * ```js + * if (!variables[name]) { + * throw decl.error(`Unknown variable ${name}`, { word: name }) + * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + * // color: $black + * // a + * // ^ + * // background: white + * } + * ``` + * + * @param message Error description. + * @param opts Options. + * + * @return Error object to throw it. + */ + error(message: string, options?: NodeErrorOptions): CssSyntaxError + + /** + * This method is provided as a convenience wrapper for `Result#warn`. + * + * ```js + * Declaration: { + * bad: (decl, { result }) => { + * decl.warn(result, 'Deprecated property bad') + * } + * } + * ``` + * + * @param result The `Result` instance that will receive the warning. + * @param text Warning message. + * @param opts Warning Options. + * + * @return Created warning object. + */ + warn(result: Result, text: string, opts?: WarningOptions): void + + /** + * Removes the node from its parent and cleans the parent properties + * from the node and its children. + * + * ```js + * if (decl.prop.match(/^-webkit-/)) { + * decl.remove() + * } + * ``` + * + * @return Node to make calls chain. + */ + remove(): this + + /** + * Returns a CSS string representing the node. + * + * ```js + * new Rule({ selector: 'a' }).toString() //=> "a {}" + * ``` + * + * @param stringifier A syntax to use in string generation. + * @return CSS string of this node. + */ + toString(stringifier?: Stringifier | Syntax): string + + /** + * Assigns properties to the current node. + * + * ```js + * decl.assign({ prop: 'word-wrap', value: 'break-word' }) + * ``` + * + * @param overrides New properties to override the node. + * @return Current node to methods chain. + */ + assign(overrides: object): this + + /** + * Returns an exact clone of the node. + * + * The resulting cloned node and its (cloned) children will retain + * code style properties. + * + * ```js + * decl.raws.before //=> "\n " + * const cloned = decl.clone({ prop: '-moz-' + decl.prop }) + * cloned.raws.before //=> "\n " + * cloned.toString() //=> -moz-transform: scale(0) + * ``` + * + * @param overrides New properties to override in the clone. + * @return Clone of the node. + */ + clone(overrides?: object): this + + /** + * Shortcut to clone the node and insert the resulting cloned node + * before the current node. + * + * ```js + * decl.cloneBefore({ prop: '-moz-' + decl.prop }) + * ``` + * + * @param overrides Mew properties to override in the clone. + * + * @return New node + */ + cloneBefore(overrides?: object): this + + /** + * Shortcut to clone the node and insert the resulting cloned node + * after the current node. + * + * @param overrides New properties to override in the clone. + * @return New node. + */ + cloneAfter(overrides?: object): this + + /** + * Inserts node(s) before the current node and removes the current node. + * + * ```js + * AtRule: { + * mixin: atrule => { + * atrule.replaceWith(mixinRules[atrule.params]) + * } + * } + * ``` + * + * @param nodes Mode(s) to replace current one. + * @return Current node to methods chain. + */ + replaceWith( + ...nodes: (ChildNode | ChildProps | ChildNode[] | ChildProps[])[] + ): this + + /** + * Returns the next child of the node’s parent. + * Returns `undefined` if the current node is the last child. + * + * ```js + * if (comment.text === 'delete next') { + * const next = comment.next() + * if (next) { + * next.remove() + * } + * } + * ``` + * + * @return Next node. + */ + next(): ChildNode | undefined + + /** + * Returns the previous child of the node’s parent. + * Returns `undefined` if the current node is the first child. + * + * ```js + * const annotation = decl.prev() + * if (annotation.type === 'comment') { + * readAnnotation(annotation.text) + * } + * ``` + * + * @return Previous node. + */ + prev(): ChildNode | undefined + + /** + * Insert new node before current node to current node’s parent. + * + * Just alias for `node.parent.insertBefore(node, add)`. + * + * ```js + * decl.before('content: ""') + * ``` + * + * @param newNode New node. + * @return This node for methods chain. + */ + before(newNode: Node | ChildProps | string | Node[]): this + + /** + * Insert new node after current node to current node’s parent. + * + * Just alias for `node.parent.insertAfter(node, add)`. + * + * ```js + * decl.after('color: black') + * ``` + * + * @param newNode New node. + * @return This node for methods chain. + */ + after(newNode: Node | ChildProps | string | Node[]): this + + /** + * Finds the Root instance of the node’s tree. + * + * ```js + * root.nodes[0].nodes[0].root() === root + * ``` + * + * @return Root parent. + */ + root(): Root + + /** + * Returns a `Node#raws` value. If the node is missing + * the code style property (because the node was manually built or cloned), + * PostCSS will try to autodetect the code style property by looking + * at other nodes in the tree. + * + * ```js + * const root = postcss.parse('a { background: white }') + * root.nodes[0].append({ prop: 'color', value: 'black' }) + * root.nodes[0].nodes[1].raws.before //=> undefined + * root.nodes[0].nodes[1].raw('before') //=> ' ' + * ``` + * + * @param prop Name of code style property. + * @param defaultType Name of default value, it can be missed + * if the value is the same as prop. + * @return {string} Code style value. + */ + raw(prop: string, defaultType?: string): string + + /** + * Clear the code style properties for the node and its children. + * + * ```js + * node.raws.before //=> ' ' + * node.cleanRaws() + * node.raws.before //=> undefined + * ``` + * + * @param keepBetween Keep the `raws.between` symbols. + */ + cleanRaws(keepBetween?: boolean): void + + /** + * Fix circular links on `JSON.stringify()`. + * + * @return Cleaned object. + */ + toJSON(): object + + /** + * Convert string index to line/column. + * + * @param index The symbol number in the node’s string. + * @return Symbol position in file. + */ + positionInside(index: number): Position +} diff --git a/node_modules/postcss/lib/node.js b/node_modules/postcss/lib/node.js new file mode 100644 index 0000000..d26ef1f --- /dev/null +++ b/node_modules/postcss/lib/node.js @@ -0,0 +1,320 @@ +'use strict' + +let { isClean, my } = require('./symbols') +let CssSyntaxError = require('./css-syntax-error') +let Stringifier = require('./stringifier') +let stringify = require('./stringify') + +function cloneNode(obj, parent) { + let cloned = new obj.constructor() + + for (let i in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, i)) { + // istanbul ignore next + continue + } + if (i === 'proxyCache') continue + let value = obj[i] + let type = typeof value + + if (i === 'parent' && type === 'object') { + if (parent) cloned[i] = parent + } else if (i === 'source') { + cloned[i] = value + } else if (Array.isArray(value)) { + cloned[i] = value.map(j => cloneNode(j, cloned)) + } else { + if (type === 'object' && value !== null) value = cloneNode(value) + cloned[i] = value + } + } + + return cloned +} + +class Node { + constructor(defaults = {}) { + this.raws = {} + this[isClean] = false + this[my] = true + + for (let name in defaults) { + if (name === 'nodes') { + this.nodes = [] + for (let node of defaults[name]) { + if (typeof node.clone === 'function') { + this.append(node.clone()) + } else { + this.append(node) + } + } + } else { + this[name] = defaults[name] + } + } + } + + error(message, opts = {}) { + if (this.source) { + let pos = this.positionBy(opts) + return this.source.input.error(message, pos.line, pos.column, opts) + } + return new CssSyntaxError(message) + } + + warn(result, text, opts) { + let data = { node: this } + for (let i in opts) data[i] = opts[i] + return result.warn(text, data) + } + + remove() { + if (this.parent) { + this.parent.removeChild(this) + } + this.parent = undefined + return this + } + + toString(stringifier = stringify) { + if (stringifier.stringify) stringifier = stringifier.stringify + let result = '' + stringifier(this, i => { + result += i + }) + return result + } + + assign(overrides = {}) { + for (let name in overrides) { + this[name] = overrides[name] + } + return this + } + + clone(overrides = {}) { + let cloned = cloneNode(this) + for (let name in overrides) { + cloned[name] = overrides[name] + } + return cloned + } + + cloneBefore(overrides = {}) { + let cloned = this.clone(overrides) + this.parent.insertBefore(this, cloned) + return cloned + } + + cloneAfter(overrides = {}) { + let cloned = this.clone(overrides) + this.parent.insertAfter(this, cloned) + return cloned + } + + replaceWith(...nodes) { + if (this.parent) { + let bookmark = this + let foundSelf = false + for (let node of nodes) { + if (node === this) { + foundSelf = true + } else if (foundSelf) { + this.parent.insertAfter(bookmark, node) + bookmark = node + } else { + this.parent.insertBefore(bookmark, node) + } + } + + if (!foundSelf) { + this.remove() + } + } + + return this + } + + next() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index + 1] + } + + prev() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index - 1] + } + + before(add) { + this.parent.insertBefore(this, add) + return this + } + + after(add) { + this.parent.insertAfter(this, add) + return this + } + + root() { + let result = this + while (result.parent && result.parent.type !== 'document') { + result = result.parent + } + return result + } + + raw(prop, defaultType) { + let str = new Stringifier() + return str.raw(this, prop, defaultType) + } + + cleanRaws(keepBetween) { + delete this.raws.before + delete this.raws.after + if (!keepBetween) delete this.raws.between + } + + toJSON(_, inputs) { + let fixed = {} + let emitInputs = inputs == null + inputs = inputs || new Map() + let inputsNextIndex = 0 + + for (let name in this) { + if (!Object.prototype.hasOwnProperty.call(this, name)) { + // istanbul ignore next + continue + } + if (name === 'parent' || name === 'proxyCache') continue + let value = this[name] + + if (Array.isArray(value)) { + fixed[name] = value.map(i => { + if (typeof i === 'object' && i.toJSON) { + return i.toJSON(null, inputs) + } else { + return i + } + }) + } else if (typeof value === 'object' && value.toJSON) { + fixed[name] = value.toJSON(null, inputs) + } else if (name === 'source') { + let inputId = inputs.get(value.input) + if (inputId == null) { + inputId = inputsNextIndex + inputs.set(value.input, inputsNextIndex) + inputsNextIndex++ + } + fixed[name] = { + inputId, + start: value.start, + end: value.end + } + } else { + fixed[name] = value + } + } + + if (emitInputs) { + fixed.inputs = [...inputs.keys()].map(input => input.toJSON()) + } + + return fixed + } + + positionInside(index) { + let string = this.toString() + let column = this.source.start.column + let line = this.source.start.line + + for (let i = 0; i < index; i++) { + if (string[i] === '\n') { + column = 1 + line += 1 + } else { + column += 1 + } + } + + return { line, column } + } + + positionBy(opts) { + let pos = this.source.start + if (opts.index) { + pos = this.positionInside(opts.index) + } else if (opts.word) { + let index = this.toString().indexOf(opts.word) + if (index !== -1) pos = this.positionInside(index) + } + return pos + } + + getProxyProcessor() { + return { + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value + if ( + prop === 'prop' || + prop === 'value' || + prop === 'name' || + prop === 'params' || + prop === 'important' || + prop === 'text' + ) { + node.markDirty() + } + return true + }, + + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (prop === 'root') { + return () => node.root().toProxy() + } else { + return node[prop] + } + } + } + } + + toProxy() { + if (!this.proxyCache) { + this.proxyCache = new Proxy(this, this.getProxyProcessor()) + } + return this.proxyCache + } + + addToError(error) { + error.postcssNode = this + if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { + let s = this.source + error.stack = error.stack.replace( + /\n\s{4}at /, + `$&${s.input.from}:${s.start.line}:${s.start.column}$&` + ) + } + return error + } + + markDirty() { + if (this[isClean]) { + this[isClean] = false + let next = this + while ((next = next.parent)) { + next[isClean] = false + } + } + } + + get proxyOf() { + return this + } +} + +module.exports = Node +Node.default = Node diff --git a/node_modules/postcss/lib/parse.d.ts b/node_modules/postcss/lib/parse.d.ts new file mode 100644 index 0000000..d6bdee2 --- /dev/null +++ b/node_modules/postcss/lib/parse.d.ts @@ -0,0 +1,5 @@ +import { Parser } from './postcss.js' + +declare const parse: Parser + +export default parse diff --git a/node_modules/postcss/lib/parse.js b/node_modules/postcss/lib/parse.js new file mode 100644 index 0000000..971431f --- /dev/null +++ b/node_modules/postcss/lib/parse.js @@ -0,0 +1,42 @@ +'use strict' + +let Container = require('./container') +let Parser = require('./parser') +let Input = require('./input') + +function parse(css, opts) { + let input = new Input(css, opts) + let parser = new Parser(input) + try { + parser.parse() + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + if (e.name === 'CssSyntaxError' && opts && opts.from) { + if (/\.scss$/i.test(opts.from)) { + e.message += + '\nYou tried to parse SCSS with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-scss parser' + } else if (/\.sass/i.test(opts.from)) { + e.message += + '\nYou tried to parse Sass with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-sass parser' + } else if (/\.less$/i.test(opts.from)) { + e.message += + '\nYou tried to parse Less with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-less parser' + } + } + } + throw e + } + + return parser.root +} + +module.exports = parse +parse.default = parse + +Container.registerParse(parse) diff --git a/node_modules/postcss/lib/parser.js b/node_modules/postcss/lib/parser.js new file mode 100644 index 0000000..4144cc9 --- /dev/null +++ b/node_modules/postcss/lib/parser.js @@ -0,0 +1,565 @@ +'use strict' + +let Declaration = require('./declaration') +let tokenizer = require('./tokenize') +let Comment = require('./comment') +let AtRule = require('./at-rule') +let Root = require('./root') +let Rule = require('./rule') + +class Parser { + constructor(input) { + this.input = input + + this.root = new Root() + this.current = this.root + this.spaces = '' + this.semicolon = false + this.customProperty = false + + this.createTokenizer() + this.root.source = { input, start: { offset: 0, line: 1, column: 1 } } + } + + createTokenizer() { + this.tokenizer = tokenizer(this.input) + } + + parse() { + let token + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + + switch (token[0]) { + case 'space': + this.spaces += token[1] + break + + case ';': + this.freeSemicolon(token) + break + + case '}': + this.end(token) + break + + case 'comment': + this.comment(token) + break + + case 'at-word': + this.atrule(token) + break + + case '{': + this.emptyRule(token) + break + + default: + this.other(token) + break + } + } + this.endFile() + } + + comment(token) { + let node = new Comment() + this.init(node, token[2]) + node.source.end = this.getPosition(token[3] || token[2]) + + let text = token[1].slice(2, -2) + if (/^\s*$/.test(text)) { + node.text = '' + node.raws.left = text + node.raws.right = '' + } else { + let match = text.match(/^(\s*)([^]*\S)(\s*)$/) + node.text = match[2] + node.raws.left = match[1] + node.raws.right = match[3] + } + } + + emptyRule(token) { + let node = new Rule() + this.init(node, token[2]) + node.selector = '' + node.raws.between = '' + this.current = node + } + + other(start) { + let end = false + let type = null + let colon = false + let bracket = null + let brackets = [] + let customProperty = start[1].startsWith('--') + + let tokens = [] + let token = start + while (token) { + type = token[0] + tokens.push(token) + + if (type === '(' || type === '[') { + if (!bracket) bracket = token + brackets.push(type === '(' ? ')' : ']') + } else if (customProperty && colon && type === '{') { + if (!bracket) bracket = token + brackets.push('}') + } else if (brackets.length === 0) { + if (type === ';') { + if (colon) { + this.decl(tokens, customProperty) + return + } else { + break + } + } else if (type === '{') { + this.rule(tokens) + return + } else if (type === '}') { + this.tokenizer.back(tokens.pop()) + end = true + break + } else if (type === ':') { + colon = true + } + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + if (brackets.length === 0) bracket = null + } + + token = this.tokenizer.nextToken() + } + + if (this.tokenizer.endOfFile()) end = true + if (brackets.length > 0) this.unclosedBracket(bracket) + + if (end && colon) { + while (tokens.length) { + token = tokens[tokens.length - 1][0] + if (token !== 'space' && token !== 'comment') break + this.tokenizer.back(tokens.pop()) + } + this.decl(tokens, customProperty) + } else { + this.unknownWord(tokens) + } + } + + rule(tokens) { + tokens.pop() + + let node = new Rule() + this.init(node, tokens[0][2]) + + node.raws.between = this.spacesAndCommentsFromEnd(tokens) + this.raw(node, 'selector', tokens) + this.current = node + } + + decl(tokens, customProperty) { + let node = new Declaration() + this.init(node, tokens[0][2]) + + let last = tokens[tokens.length - 1] + if (last[0] === ';') { + this.semicolon = true + tokens.pop() + } + node.source.end = this.getPosition(last[3] || last[2]) + + while (tokens[0][0] !== 'word') { + if (tokens.length === 1) this.unknownWord(tokens) + node.raws.before += tokens.shift()[1] + } + node.source.start = this.getPosition(tokens[0][2]) + + node.prop = '' + while (tokens.length) { + let type = tokens[0][0] + if (type === ':' || type === 'space' || type === 'comment') { + break + } + node.prop += tokens.shift()[1] + } + + node.raws.between = '' + + let token + while (tokens.length) { + token = tokens.shift() + + if (token[0] === ':') { + node.raws.between += token[1] + break + } else { + if (token[0] === 'word' && /\w/.test(token[1])) { + this.unknownWord([token]) + } + node.raws.between += token[1] + } + } + + if (node.prop[0] === '_' || node.prop[0] === '*') { + node.raws.before += node.prop[0] + node.prop = node.prop.slice(1) + } + let firstSpaces = this.spacesAndCommentsFromStart(tokens) + this.precheckMissedSemicolon(tokens) + + for (let i = tokens.length - 1; i >= 0; i--) { + token = tokens[i] + if (token[1].toLowerCase() === '!important') { + node.important = true + let string = this.stringFrom(tokens, i) + string = this.spacesFromEnd(tokens) + string + if (string !== ' !important') node.raws.important = string + break + } else if (token[1].toLowerCase() === 'important') { + let cache = tokens.slice(0) + let str = '' + for (let j = i; j > 0; j--) { + let type = cache[j][0] + if (str.trim().indexOf('!') === 0 && type !== 'space') { + break + } + str = cache.pop()[1] + str + } + if (str.trim().indexOf('!') === 0) { + node.important = true + node.raws.important = str + tokens = cache + } + } + + if (token[0] !== 'space' && token[0] !== 'comment') { + break + } + } + + let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment') + this.raw(node, 'value', tokens) + if (hasWord) { + node.raws.between += firstSpaces + } else { + node.value = firstSpaces + node.value + } + + if (node.value.includes(':') && !customProperty) { + this.checkMissedSemicolon(tokens) + } + } + + atrule(token) { + let node = new AtRule() + node.name = token[1].slice(1) + if (node.name === '') { + this.unnamedAtrule(node, token) + } + this.init(node, token[2]) + + let type + let prev + let shift + let last = false + let open = false + let params = [] + let brackets = [] + + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + type = token[0] + + if (type === '(' || type === '[') { + brackets.push(type === '(' ? ')' : ']') + } else if (type === '{' && brackets.length > 0) { + brackets.push('}') + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + } + + if (brackets.length === 0) { + if (type === ';') { + node.source.end = this.getPosition(token[2]) + this.semicolon = true + break + } else if (type === '{') { + open = true + break + } else if (type === '}') { + if (params.length > 0) { + shift = params.length - 1 + prev = params[shift] + while (prev && prev[0] === 'space') { + prev = params[--shift] + } + if (prev) { + node.source.end = this.getPosition(prev[3] || prev[2]) + } + } + this.end(token) + break + } else { + params.push(token) + } + } else { + params.push(token) + } + + if (this.tokenizer.endOfFile()) { + last = true + break + } + } + + node.raws.between = this.spacesAndCommentsFromEnd(params) + if (params.length) { + node.raws.afterName = this.spacesAndCommentsFromStart(params) + this.raw(node, 'params', params) + if (last) { + token = params[params.length - 1] + node.source.end = this.getPosition(token[3] || token[2]) + this.spaces = node.raws.between + node.raws.between = '' + } + } else { + node.raws.afterName = '' + node.params = '' + } + + if (open) { + node.nodes = [] + this.current = node + } + } + + end(token) { + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon + } + this.semicolon = false + + this.current.raws.after = (this.current.raws.after || '') + this.spaces + this.spaces = '' + + if (this.current.parent) { + this.current.source.end = this.getPosition(token[2]) + this.current = this.current.parent + } else { + this.unexpectedClose(token) + } + } + + endFile() { + if (this.current.parent) this.unclosedBlock() + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon + } + this.current.raws.after = (this.current.raws.after || '') + this.spaces + } + + freeSemicolon(token) { + this.spaces += token[1] + if (this.current.nodes) { + let prev = this.current.nodes[this.current.nodes.length - 1] + if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) { + prev.raws.ownSemicolon = this.spaces + this.spaces = '' + } + } + } + + // Helpers + + getPosition(offset) { + let pos = this.input.fromOffset(offset) + return { + offset, + line: pos.line, + column: pos.col + } + } + + init(node, offset) { + this.current.push(node) + node.source = { + start: this.getPosition(offset), + input: this.input + } + node.raws.before = this.spaces + this.spaces = '' + if (node.type !== 'comment') this.semicolon = false + } + + raw(node, prop, tokens) { + let token, type + let length = tokens.length + let value = '' + let clean = true + let next, prev + let pattern = /^([#.|])?(\w)+/i + + for (let i = 0; i < length; i += 1) { + token = tokens[i] + type = token[0] + + if (type === 'comment' && node.type === 'rule') { + prev = tokens[i - 1] + next = tokens[i + 1] + + if ( + prev[0] !== 'space' && + next[0] !== 'space' && + pattern.test(prev[1]) && + pattern.test(next[1]) + ) { + value += token[1] + } else { + clean = false + } + + continue + } + + if (type === 'comment' || (type === 'space' && i === length - 1)) { + clean = false + } else { + value += token[1] + } + } + if (!clean) { + let raw = tokens.reduce((all, i) => all + i[1], '') + node.raws[prop] = { value, raw } + } + node[prop] = value + } + + spacesAndCommentsFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space' && lastTokenType !== 'comment') break + spaces = tokens.pop()[1] + spaces + } + return spaces + } + + spacesAndCommentsFromStart(tokens) { + let next + let spaces = '' + while (tokens.length) { + next = tokens[0][0] + if (next !== 'space' && next !== 'comment') break + spaces += tokens.shift()[1] + } + return spaces + } + + spacesFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space') break + spaces = tokens.pop()[1] + spaces + } + return spaces + } + + stringFrom(tokens, from) { + let result = '' + for (let i = from; i < tokens.length; i++) { + result += tokens[i][1] + } + tokens.splice(from, tokens.length - from) + return result + } + + colon(tokens) { + let brackets = 0 + let token, type, prev + for (let [i, element] of tokens.entries()) { + token = element + type = token[0] + + if (type === '(') { + brackets += 1 + } + if (type === ')') { + brackets -= 1 + } + if (brackets === 0 && type === ':') { + if (!prev) { + this.doubleColon(token) + } else if (prev[0] === 'word' && prev[1] === 'progid') { + continue + } else { + return i + } + } + + prev = token + } + return false + } + + // Errors + + unclosedBracket(bracket) { + throw this.input.error('Unclosed bracket', bracket[2]) + } + + unknownWord(tokens) { + throw this.input.error('Unknown word', tokens[0][2]) + } + + unexpectedClose(token) { + throw this.input.error('Unexpected }', token[2]) + } + + unclosedBlock() { + let pos = this.current.source.start + throw this.input.error('Unclosed block', pos.line, pos.column) + } + + doubleColon(token) { + throw this.input.error('Double colon', token[2]) + } + + unnamedAtrule(node, token) { + throw this.input.error('At-rule without name', token[2]) + } + + precheckMissedSemicolon(/* tokens */) { + // Hook for Safe Parser + } + + checkMissedSemicolon(tokens) { + let colon = this.colon(tokens) + if (colon === false) return + + let founded = 0 + let token + for (let j = colon - 1; j >= 0; j--) { + token = tokens[j] + if (token[0] !== 'space') { + founded += 1 + if (founded === 2) break + } + } + // If the token is a word, e.g. `!important`, `red` or any other valid property's value. + // Then we need to return the colon after that word token. [3] is the "end" colon of that word. + // And because we need it after that one we do +1 to get the next one. + throw this.input.error( + 'Missed semicolon', + token[0] === 'word' ? token[3] + 1 : token[2] + ) + } +} + +module.exports = Parser diff --git a/node_modules/postcss/lib/postcss.d.ts b/node_modules/postcss/lib/postcss.d.ts new file mode 100644 index 0000000..4458806 --- /dev/null +++ b/node_modules/postcss/lib/postcss.d.ts @@ -0,0 +1,472 @@ +import { SourceMapGenerator, RawSourceMap } from 'source-map-js' + +import Node, { + Position, + Source, + ChildNode, + NodeErrorOptions, + NodeProps, + ChildProps, + AnyNode +} from './node.js' +import Declaration, { DeclarationProps } from './declaration.js' +import Root, { RootProps } from './root.js' +import Document, { DocumentProps } from './document.js' +import Comment, { CommentProps } from './comment.js' +import AtRule, { AtRuleProps } from './at-rule.js' +import Result, { Message } from './result.js' +import LazyResult from './lazy-result.js' +import Rule, { RuleProps } from './rule.js' +import Container, { ContainerProps } from './container.js' +import Warning, { WarningOptions } from './warning.js' +import Input, { FilePosition } from './input.js' +import CssSyntaxError from './css-syntax-error.js' +import list, { List } from './list.js' +import Processor from './processor.js' + +export { + WarningOptions, + FilePosition, + Position, + Source, + ChildNode, + AnyNode, + Message, + NodeErrorOptions, + NodeProps, + DeclarationProps, + ContainerProps, + CommentProps, + RuleProps, + ChildProps, + AtRuleProps, + RootProps, + DocumentProps, + Warning, + CssSyntaxError, + Node, + Container, + list, + Declaration, + Comment, + AtRule, + Rule, + Root, + Document, + Result, + LazyResult, + Input +} + +export type SourceMap = SourceMapGenerator & { + toJSON(): RawSourceMap +} + +export type Helpers = { result: Result; postcss: Postcss } & Postcss + +type DocumentProcessor = ( + document: Document, + helper: Helpers +) => Promise | void +type RootProcessor = (root: Root, helper: Helpers) => Promise | void +type DeclarationProcessor = ( + decl: Declaration, + helper: Helpers +) => Promise | void +type RuleProcessor = (rule: Rule, helper: Helpers) => Promise | void +type AtRuleProcessor = (atRule: AtRule, helper: Helpers) => Promise | void +type CommentProcessor = ( + comment: Comment, + helper: Helpers +) => Promise | void + +interface Processors { + /** + * Will be called on `Document` node. + * + * Will be called again on children changes. + */ + Document?: DocumentProcessor + + /** + * Will be called on `Document` node, when all children will be processed. + * + * Will be called again on children changes. + */ + DocumentExit?: DocumentProcessor + + /** + * Will be called on `Root` node once. + */ + Once?: RootProcessor + + /** + * Will be called on `Root` node once, when all children will be processed. + */ + OnceExit?: RootProcessor + + /** + * Will be called on `Root` node. + * + * Will be called again on children changes. + */ + Root?: RootProcessor + + /** + * Will be called on `Root` node, when all children will be processed. + * + * Will be called again on children changes. + */ + RootExit?: RootProcessor + + /** + * Will be called on all `Declaration` nodes after listeners + * for `Declaration` event. + * + * Will be called again on node or children changes. + */ + Declaration?: DeclarationProcessor | { [prop: string]: DeclarationProcessor } + + /** + * Will be called on all `Declaration` nodes. + * + * Will be called again on node or children changes. + */ + DeclarationExit?: + | DeclarationProcessor + | { [prop: string]: DeclarationProcessor } + + /** + * Will be called on all `Rule` nodes. + * + * Will be called again on node or children changes. + */ + Rule?: RuleProcessor + + /** + * Will be called on all `Rule` nodes, when all children will be processed. + * + * Will be called again on node or children changes. + */ + RuleExit?: RuleProcessor + + /** + * Will be called on all`AtRule` nodes. + * + * Will be called again on node or children changes. + */ + AtRule?: AtRuleProcessor | { [name: string]: AtRuleProcessor } + + /** + * Will be called on all `AtRule` nodes, when all children will be processed. + * + * Will be called again on node or children changes. + */ + AtRuleExit?: AtRuleProcessor | { [name: string]: AtRuleProcessor } + + /** + * Will be called on all `Comment` nodes. + * + * Will be called again on node or children changes. + */ + Comment?: CommentProcessor + + /** + * Will be called on all `Comment` nodes after listeners + * for `Comment` event. + * + * Will be called again on node or children changes. + */ + CommentExit?: CommentProcessor + + /** + * Will be called when all other listeners processed the document. + * + * This listener will not be called again. + */ + Exit?: RootProcessor +} + +export interface Plugin extends Processors { + postcssPlugin: string + prepare?: (result: Result) => Processors +} + +export interface PluginCreator { + (opts?: PluginOptions): Plugin | Processor + postcss: true +} + +export interface Transformer extends TransformCallback { + postcssPlugin: string + postcssVersion: string +} + +export interface TransformCallback { + (root: Root, result: Result): Promise | void +} + +export interface OldPlugin extends Transformer { + (opts?: T): Transformer + postcss: Transformer +} + +export type AcceptedPlugin = + | Plugin + | PluginCreator + | OldPlugin + | TransformCallback + | { + postcss: TransformCallback | Processor + } + | Processor + +export interface Parser { + ( + css: string | { toString(): string }, + opts?: Pick + ): RootNode +} + +export interface Builder { + (part: string, node?: AnyNode, type?: 'start' | 'end'): void +} + +export interface Stringifier { + (node: AnyNode, builder: Builder): void +} + +export interface JSONHydrator { + (data: object[]): Node[] + (data: object): Node +} + +export interface Syntax { + /** + * Function to generate AST by string. + */ + parse?: Parser + + /** + * Class to generate string by AST. + */ + stringify?: Stringifier +} + +export interface SourceMapOptions { + /** + * Indicates that the source map should be embedded in the output CSS + * as a Base64-encoded comment. By default, it is `true`. + * But if all previous maps are external, not inline, PostCSS will not embed + * the map even if you do not set this option. + * + * If you have an inline source map, the result.map property will be empty, + * as the source map will be contained within the text of `result.css`. + */ + inline?: boolean + + /** + * Source map content from a previous processing step (e.g., Sass). + * + * PostCSS will try to read the previous source map + * automatically (based on comments within the source CSS), but you can use + * this option to identify it manually. + * + * If desired, you can omit the previous map with prev: `false`. + */ + prev?: string | boolean | object | ((file: string) => string) + + /** + * Indicates that PostCSS should set the origin content (e.g., Sass source) + * of the source map. By default, it is true. But if all previous maps do not + * contain sources content, PostCSS will also leave it out even if you + * do not set this option. + */ + sourcesContent?: boolean + + /** + * Indicates that PostCSS should add annotation comments to the CSS. + * By default, PostCSS will always add a comment with a path + * to the source map. PostCSS will not add annotations to CSS files + * that do not contain any comments. + * + * By default, PostCSS presumes that you want to save the source map as + * `opts.to + '.map'` and will use this path in the annotation comment. + * A different path can be set by providing a string value for annotation. + * + * If you have set `inline: true`, annotation cannot be disabled. + */ + annotation?: string | boolean | ((file: string, root: Root) => string) + + /** + * Override `from` in map’s sources. + */ + from?: string + + /** + * Use absolute path in generated source map. + */ + absolute?: boolean +} + +export interface ProcessOptions { + /** + * The path of the CSS source file. You should always set `from`, + * because it is used in source map generation and syntax error messages. + */ + from?: string + + /** + * The path where you'll put the output CSS file. You should always set `to` + * to generate correct source maps. + */ + to?: string + + /** + * Function to generate AST by string. + */ + parser?: Syntax | Parser + + /** + * Class to generate string by AST. + */ + stringifier?: Syntax | Stringifier + + /** + * Object with parse and stringify. + */ + syntax?: Syntax + + /** + * Source map options + */ + map?: SourceMapOptions | boolean +} + +export interface Postcss { + /** + * Create a new `Processor` instance that will apply `plugins` + * as CSS processors. + * + * ```js + * let postcss = require('postcss') + * + * postcss(plugins).process(css, { from, to }).then(result => { + * console.log(result.css) + * }) + * ``` + * + * @param plugins PostCSS plugins. + * @return Processor to process multiple CSS. + */ + (plugins?: AcceptedPlugin[]): Processor + (...plugins: AcceptedPlugin[]): Processor + + /** + * Default function to convert a node tree into a CSS string. + */ + stringify: Stringifier + + /** + * Parses source css and returns a new `Root` or `Document` node, + * which contains the source CSS nodes. + * + * ```js + * // Simple CSS concatenation with source map support + * const root1 = postcss.parse(css1, { from: file1 }) + * const root2 = postcss.parse(css2, { from: file2 }) + * root1.append(root2).toResult().css + * ``` + */ + parse: Parser + + /** + * Rehydrate a JSON AST (from `Node#toJSON`) back into the AST classes. + * + * ```js + * const json = root.toJSON() + * // save to file, send by network, etc + * const root2 = postcss.fromJSON(json) + * ``` + */ + fromJSON: JSONHydrator + + /** + * Contains the `list` module. + */ + list: List + + /** + * Creates a new `Comment` node. + * + * @param defaults Properties for the new node. + * @return New comment node + */ + comment(defaults?: CommentProps): Comment + + /** + * Creates a new `AtRule` node. + * + * @param defaults Properties for the new node. + * @return New at-rule node. + */ + atRule(defaults?: AtRuleProps): AtRule + + /** + * Creates a new `Declaration` node. + * + * @param defaults Properties for the new node. + * @return New declaration node. + */ + decl(defaults?: DeclarationProps): Declaration + + /** + * Creates a new `Rule` node. + * + * @param default Properties for the new node. + * @return New rule node. + */ + rule(defaults?: RuleProps): Rule + + /** + * Creates a new `Root` node. + * + * @param defaults Properties for the new node. + * @return New root node. + */ + root(defaults?: RootProps): Root + + /** + * Creates a new `Document` node. + * + * @param defaults Properties for the new node. + * @return New document node. + */ + document(defaults?: DocumentProps): Document + + CssSyntaxError: typeof CssSyntaxError + Declaration: typeof Declaration + Container: typeof Container + Comment: typeof Comment + Warning: typeof Warning + AtRule: typeof AtRule + Result: typeof Result + Input: typeof Input + Rule: typeof Rule + Root: typeof Root + Node: typeof Node +} + +export const stringify: Stringifier +export const parse: Parser +export const fromJSON: JSONHydrator + +export const comment: Postcss['comment'] +export const atRule: Postcss['atRule'] +export const decl: Postcss['decl'] +export const rule: Postcss['rule'] +export const root: Postcss['root'] + +declare const postcss: Postcss + +export default postcss diff --git a/node_modules/postcss/lib/postcss.js b/node_modules/postcss/lib/postcss.js new file mode 100644 index 0000000..b03bb18 --- /dev/null +++ b/node_modules/postcss/lib/postcss.js @@ -0,0 +1,95 @@ +'use strict' + +let CssSyntaxError = require('./css-syntax-error') +let Declaration = require('./declaration') +let LazyResult = require('./lazy-result') +let Container = require('./container') +let Processor = require('./processor') +let stringify = require('./stringify') +let fromJSON = require('./fromJSON') +let Document = require('./document') +let Warning = require('./warning') +let Comment = require('./comment') +let AtRule = require('./at-rule') +let Result = require('./result.js') +let Input = require('./input') +let parse = require('./parse') +let list = require('./list') +let Rule = require('./rule') +let Root = require('./root') +let Node = require('./node') + +function postcss(...plugins) { + if (plugins.length === 1 && Array.isArray(plugins[0])) { + plugins = plugins[0] + } + return new Processor(plugins) +} + +postcss.plugin = function plugin(name, initializer) { + if (console && console.warn) { + console.warn( + name + + ': postcss.plugin was deprecated. Migration guide:\n' + + 'https://evilmartians.com/chronicles/postcss-8-plugin-migration' + ) + if (process.env.LANG && process.env.LANG.startsWith('cn')) { + // istanbul ignore next + console.warn( + name + + ': 里面 postcss.plugin 被弃用. 迁移指南:\n' + + 'https://www.w3ctech.com/topic/2226' + ) + } + } + function creator(...args) { + let transformer = initializer(...args) + transformer.postcssPlugin = name + transformer.postcssVersion = new Processor().version + return transformer + } + + let cache + Object.defineProperty(creator, 'postcss', { + get() { + if (!cache) cache = creator() + return cache + } + }) + + creator.process = function (css, processOpts, pluginOpts) { + return postcss([creator(pluginOpts)]).process(css, processOpts) + } + + return creator +} + +postcss.stringify = stringify +postcss.parse = parse +postcss.fromJSON = fromJSON +postcss.list = list + +postcss.comment = defaults => new Comment(defaults) +postcss.atRule = defaults => new AtRule(defaults) +postcss.decl = defaults => new Declaration(defaults) +postcss.rule = defaults => new Rule(defaults) +postcss.root = defaults => new Root(defaults) +postcss.document = defaults => new Document(defaults) + +postcss.CssSyntaxError = CssSyntaxError +postcss.Declaration = Declaration +postcss.Container = Container +postcss.Document = Document +postcss.Comment = Comment +postcss.Warning = Warning +postcss.AtRule = AtRule +postcss.Result = Result +postcss.Input = Input +postcss.Rule = Rule +postcss.Root = Root +postcss.Node = Node + +LazyResult.registerPostcss(postcss) + +module.exports = postcss +postcss.default = postcss diff --git a/node_modules/postcss/lib/postcss.mjs b/node_modules/postcss/lib/postcss.mjs new file mode 100644 index 0000000..6ba7d11 --- /dev/null +++ b/node_modules/postcss/lib/postcss.mjs @@ -0,0 +1,29 @@ +import postcss from './postcss.js' + +export default postcss + +export const stringify = postcss.stringify +export const fromJSON = postcss.fromJSON +export const plugin = postcss.plugin +export const parse = postcss.parse +export const list = postcss.list + +export const document = postcss.document +export const comment = postcss.comment +export const atRule = postcss.atRule +export const rule = postcss.rule +export const decl = postcss.decl +export const root = postcss.root + +export const CssSyntaxError = postcss.CssSyntaxError +export const Declaration = postcss.Declaration +export const Container = postcss.Container +export const Document = postcss.Document +export const Comment = postcss.Comment +export const Warning = postcss.Warning +export const AtRule = postcss.AtRule +export const Result = postcss.Result +export const Input = postcss.Input +export const Rule = postcss.Rule +export const Root = postcss.Root +export const Node = postcss.Node diff --git a/node_modules/postcss/lib/previous-map.d.ts b/node_modules/postcss/lib/previous-map.d.ts new file mode 100644 index 0000000..490d885 --- /dev/null +++ b/node_modules/postcss/lib/previous-map.d.ts @@ -0,0 +1,72 @@ +import { SourceMapConsumer } from 'source-map-js' + +import { ProcessOptions } from './postcss.js' + +/** + * Source map information from input CSS. + * For example, source map after Sass compiler. + * + * This class will automatically find source map in input CSS or in file system + * near input file (according `from` option). + * + * ```js + * const root = parse(css, { from: 'a.sass.css' }) + * root.input.map //=> PreviousMap + * ``` + */ +export default class PreviousMap { + /** + * Was source map inlined by data-uri to input CSS. + */ + inline: boolean + + /** + * `sourceMappingURL` content. + */ + annotation?: string + + /** + * Source map file content. + */ + text?: string + + /** + * The directory with source map file, if source map is in separated file. + */ + root?: string + + /** + * The CSS source identifier. Contains `Input#file` if the user + * set the `from` option, or `Input#id` if they did not. + */ + file?: string + + /** + * Path to source map file. + */ + mapFile?: string + + /** + * @param css Input CSS source. + * @param opts Process options. + */ + constructor(css: string, opts?: ProcessOptions) + + /** + * Create a instance of `SourceMapGenerator` class + * from the `source-map` library to work with source map information. + * + * It is lazy method, so it will create object only on first call + * and then it will use cache. + * + * @return Object with source map information. + */ + consumer(): SourceMapConsumer + + /** + * Does source map contains `sourcesContent` with input source text. + * + * @return Is `sourcesContent` present. + */ + withContent(): boolean +} diff --git a/node_modules/postcss/lib/previous-map.js b/node_modules/postcss/lib/previous-map.js new file mode 100644 index 0000000..fb634de --- /dev/null +++ b/node_modules/postcss/lib/previous-map.js @@ -0,0 +1,145 @@ +'use strict' + +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { existsSync, readFileSync } = require('fs') +let { dirname, join } = require('path') + +function fromBase64(str) { + if (Buffer) { + return Buffer.from(str, 'base64').toString() + } else { + // istanbul ignore next + return window.atob(str) + } +} + +class PreviousMap { + constructor(css, opts) { + if (opts.map === false) return + this.loadAnnotation(css) + this.inline = this.startWith(this.annotation, 'data:') + + let prev = opts.map ? opts.map.prev : undefined + let text = this.loadMap(opts.from, prev) + if (!this.mapFile && opts.from) { + this.mapFile = opts.from + } + if (this.mapFile) this.root = dirname(this.mapFile) + if (text) this.text = text + } + + consumer() { + if (!this.consumerCache) { + this.consumerCache = new SourceMapConsumer(this.text) + } + return this.consumerCache + } + + withContent() { + return !!( + this.consumer().sourcesContent && + this.consumer().sourcesContent.length > 0 + ) + } + + startWith(string, start) { + if (!string) return false + return string.substr(0, start.length) === start + } + + getAnnotationURL(sourceMapString) { + return sourceMapString + .match(/\/\*\s*# sourceMappingURL=((?:(?!sourceMappingURL=).)*)\*\//)[1] + .trim() + } + + loadAnnotation(css) { + let annotations = css.match( + /\/\*\s*# sourceMappingURL=(?:(?!sourceMappingURL=).)*\*\//gm + ) + + if (annotations && annotations.length > 0) { + // Locate the last sourceMappingURL to avoid picking up + // sourceMappingURLs from comments, strings, etc. + let lastAnnotation = annotations[annotations.length - 1] + if (lastAnnotation) { + this.annotation = this.getAnnotationURL(lastAnnotation) + } + } + } + + decodeInline(text) { + let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/ + let baseUri = /^data:application\/json;base64,/ + let charsetUri = /^data:application\/json;charset=utf-?8,/ + let uri = /^data:application\/json,/ + + if (charsetUri.test(text) || uri.test(text)) { + return decodeURIComponent(text.substr(RegExp.lastMatch.length)) + } + + if (baseCharsetUri.test(text) || baseUri.test(text)) { + return fromBase64(text.substr(RegExp.lastMatch.length)) + } + + let encoding = text.match(/data:application\/json;([^,]+),/)[1] + throw new Error('Unsupported source map encoding ' + encoding) + } + + loadFile(path) { + this.root = dirname(path) + if (existsSync(path)) { + this.mapFile = path + return readFileSync(path, 'utf-8').toString().trim() + } + } + + loadMap(file, prev) { + if (prev === false) return false + + if (prev) { + if (typeof prev === 'string') { + return prev + } else if (typeof prev === 'function') { + let prevPath = prev(file) + if (prevPath) { + let map = this.loadFile(prevPath) + if (!map) { + throw new Error( + 'Unable to load previous source map: ' + prevPath.toString() + ) + } + return map + } + } else if (prev instanceof SourceMapConsumer) { + return SourceMapGenerator.fromSourceMap(prev).toString() + } else if (prev instanceof SourceMapGenerator) { + return prev.toString() + } else if (this.isMap(prev)) { + return JSON.stringify(prev) + } else { + throw new Error( + 'Unsupported previous source map format: ' + prev.toString() + ) + } + } else if (this.inline) { + return this.decodeInline(this.annotation) + } else if (this.annotation) { + let map = this.annotation + if (file) map = join(dirname(file), map) + return this.loadFile(map) + } + } + + isMap(map) { + if (typeof map !== 'object') return false + return ( + typeof map.mappings === 'string' || + typeof map._mappings === 'string' || + Array.isArray(map.sections) + ) + } +} + +module.exports = PreviousMap +PreviousMap.default = PreviousMap diff --git a/node_modules/postcss/lib/processor.d.ts b/node_modules/postcss/lib/processor.d.ts new file mode 100644 index 0000000..1511f01 --- /dev/null +++ b/node_modules/postcss/lib/processor.d.ts @@ -0,0 +1,101 @@ +import { + AcceptedPlugin, + Plugin, + ProcessOptions, + Transformer, + TransformCallback +} from './postcss.js' +import LazyResult from './lazy-result.js' +import Result from './result.js' +import Root from './root.js' + +/** + * Contains plugins to process CSS. Create one `Processor` instance, + * initialize its plugins, and then use that instance on numerous CSS files. + * + * ```js + * const processor = postcss([autoprefixer, precss]) + * processor.process(css1).then(result => console.log(result.css)) + * processor.process(css2).then(result => console.log(result.css)) + * ``` + */ +export default class Processor { + /** + * Current PostCSS version. + * + * ```js + * if (result.processor.version.split('.')[0] !== '6') { + * throw new Error('This plugin works only with PostCSS 6') + * } + * ``` + */ + version: string + + /** + * Plugins added to this processor. + * + * ```js + * const processor = postcss([autoprefixer, precss]) + * processor.plugins.length //=> 2 + * ``` + */ + plugins: (Plugin | Transformer | TransformCallback)[] + + /** + * @param plugins PostCSS plugins + */ + constructor(plugins?: AcceptedPlugin[]) + + /** + * Adds a plugin to be used as a CSS processor. + * + * PostCSS plugin can be in 4 formats: + * * A plugin in `Plugin` format. + * * A plugin creator function with `pluginCreator.postcss = true`. + * PostCSS will call this function without argument to get plugin. + * * A function. PostCSS will pass the function a @{link Root} + * as the first argument and current `Result` instance + * as the second. + * * Another `Processor` instance. PostCSS will copy plugins + * from that instance into this one. + * + * Plugins can also be added by passing them as arguments when creating + * a `postcss` instance (see [`postcss(plugins)`]). + * + * Asynchronous plugins should return a `Promise` instance. + * + * ```js + * const processor = postcss() + * .use(autoprefixer) + * .use(precss) + * ``` + * + * @param plugin PostCSS plugin or `Processor` with plugins. + * @return {Processes} Current processor to make methods chain. + */ + use(plugin: AcceptedPlugin): this + + /** + * Parses source CSS and returns a `LazyResult` Promise proxy. + * Because some plugins can be asynchronous it doesn’t make + * any transformations. Transformations will be applied + * in the `LazyResult` methods. + * + * ```js + * processor.process(css, { from: 'a.css', to: 'a.out.css' }) + * .then(result => { + * console.log(result.css) + * }) + * ``` + * + * @param css String with input CSS or any object with a `toString()` method, + * like a Buffer. Optionally, senda `Result` instance + * and the processor will take the `Root` from it. + * @param opts Options. + * @return Promise proxy. + */ + process( + css: string | { toString(): string } | Result | LazyResult | Root, + options?: ProcessOptions + ): LazyResult +} diff --git a/node_modules/postcss/lib/processor.js b/node_modules/postcss/lib/processor.js new file mode 100644 index 0000000..74bf892 --- /dev/null +++ b/node_modules/postcss/lib/processor.js @@ -0,0 +1,74 @@ +'use strict' + +let LazyResult = require('./lazy-result') +let Document = require('./document') +let Root = require('./root') + +class Processor { + constructor(plugins = []) { + this.version = '8.3.6' + this.plugins = this.normalize(plugins) + } + + use(plugin) { + this.plugins = this.plugins.concat(this.normalize([plugin])) + return this + } + + process(css, opts = {}) { + if ( + this.plugins.length === 0 && + typeof opts.parser === 'undefined' && + typeof opts.stringifier === 'undefined' && + typeof opts.syntax === 'undefined' && + !opts.hideNothingWarning + ) { + if (process.env.NODE_ENV !== 'production') { + if (typeof console !== 'undefined' && console.warn) { + console.warn( + 'You did not set any plugins, parser, or stringifier. ' + + 'Right now, PostCSS does nothing. Pick plugins for your case ' + + 'on https://www.postcss.parts/ and use them in postcss.config.js.' + ) + } + } + } + return new LazyResult(this, css, opts) + } + + normalize(plugins) { + let normalized = [] + for (let i of plugins) { + if (i.postcss === true) { + i = i() + } else if (i.postcss) { + i = i.postcss + } + + if (typeof i === 'object' && Array.isArray(i.plugins)) { + normalized = normalized.concat(i.plugins) + } else if (typeof i === 'object' && i.postcssPlugin) { + normalized.push(i) + } else if (typeof i === 'function') { + normalized.push(i) + } else if (typeof i === 'object' && (i.parse || i.stringify)) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' + + 'one of the syntax/parser/stringifier options as outlined ' + + 'in your PostCSS runner documentation.' + ) + } + } else { + throw new Error(i + ' is not a PostCSS plugin') + } + } + return normalized + } +} + +module.exports = Processor +Processor.default = Processor + +Root.registerProcessor(Processor) +Document.registerProcessor(Processor) diff --git a/node_modules/postcss/lib/result.d.ts b/node_modules/postcss/lib/result.d.ts new file mode 100644 index 0000000..11e7bf4 --- /dev/null +++ b/node_modules/postcss/lib/result.d.ts @@ -0,0 +1,195 @@ +import { + ProcessOptions, + Plugin, + SourceMap, + TransformCallback, + Root, + Node, + Warning, + WarningOptions +} from './postcss.js' +import Processor from './processor.js' + +export interface Message { + /** + * Message type. + */ + type: string + + /** + * Source PostCSS plugin name. + */ + plugin?: string + + [others: string]: any +} + +export interface ResultOptions extends ProcessOptions { + /** + * The CSS node that was the source of the warning. + */ + node?: Node + + /** + * Name of plugin that created this warning. `Result#warn` will fill it + * automatically with `Plugin#postcssPlugin` value. + */ + plugin?: string +} + +/** + * Provides the result of the PostCSS transformations. + * + * A Result instance is returned by `LazyResult#then` + * or `Root#toResult` methods. + * + * ```js + * postcss([autoprefixer]).process(css).then(result => { + * console.log(result.css) + * }) + * ``` + * + * ```js + * const result2 = postcss.parse(css).toResult() + * ``` + */ +export default class Result { + /** + * The Processor instance used for this transformation. + * + * ```js + * for (const plugin of result.processor.plugins) { + * if (plugin.postcssPlugin === 'postcss-bad') { + * throw 'postcss-good is incompatible with postcss-bad' + * } + * }) + * ``` + */ + processor: Processor + + /** + * Contains messages from plugins (e.g., warnings or custom messages). + * Each message should have type and plugin properties. + * + * ```js + * AtRule: { + * import: (atRule, { result }) { + * const importedFile = parseImport(atRule) + * result.messages.push({ + * type: 'dependency', + * plugin: 'postcss-import', + * file: importedFile, + * parent: result.opts.from + * }) + * } + * } + * ``` + */ + messages: Message[] + + /** + * Root node after all transformations. + * + * ```js + * root.toResult().root === root + * ``` + */ + root: Root + + /** + * Options from the `Processor#process` or `Root#toResult` call + * that produced this Result instance.] + * + * ```js + * root.toResult(opts).opts === opts + * ``` + */ + opts: ResultOptions + + /** + * A CSS string representing of `Result#root`. + * + * ```js + * postcss.parse('a{}').toResult().css //=> "a{}" + * ``` + */ + css: string + + /** + * An instance of `SourceMapGenerator` class from the `source-map` library, + * representing changes to the `Result#root` instance. + * + * ```js + * result.map.toJSON() //=> { version: 3, file: 'a.css', … } + * ``` + * + * ```js + * if (result.map) { + * fs.writeFileSync(result.opts.to + '.map', result.map.toString()) + * } + * ``` + */ + map: SourceMap + + /** + * Last runned PostCSS plugin. + */ + lastPlugin: Plugin | TransformCallback + + /** + * @param processor Processor used for this transformation. + * @param root Root node after all transformations. + * @param opts Options from the `Processor#process` or `Root#toResult`. + */ + constructor(processor: Processor, root: Root, opts: ResultOptions) + + /** + * An alias for the `Result#css` property. + * Use it with syntaxes that generate non-CSS output. + * + * ```js + * result.css === result.content + * ``` + */ + get content(): string + + /** + * Returns for `Result#css` content. + * + * ```js + * result + '' === result.css + * ``` + * + * @return String representing of `Result#root`. + */ + toString(): string + + /** + * Creates an instance of `Warning` and adds it to `Result#messages`. + * + * ```js + * if (decl.important) { + * result.warn('Avoid !important', { node: decl, word: '!important' }) + * } + * ``` + * + * @param text Warning message. + * @param opts Warning options. + * @return Created warning. + */ + warn(message: string, options?: WarningOptions): Warning + + /** + * Returns warnings from plugins. Filters `Warning` instances + * from `Result#messages`. + * + * ```js + * result.warnings().forEach(warn => { + * console.warn(warn.toString()) + * }) + * ``` + * + * @return Warnings from plugins. + */ + warnings(): Warning[] +} diff --git a/node_modules/postcss/lib/result.js b/node_modules/postcss/lib/result.js new file mode 100644 index 0000000..a39751d --- /dev/null +++ b/node_modules/postcss/lib/result.js @@ -0,0 +1,42 @@ +'use strict' + +let Warning = require('./warning') + +class Result { + constructor(processor, root, opts) { + this.processor = processor + this.messages = [] + this.root = root + this.opts = opts + this.css = undefined + this.map = undefined + } + + toString() { + return this.css + } + + warn(text, opts = {}) { + if (!opts.plugin) { + if (this.lastPlugin && this.lastPlugin.postcssPlugin) { + opts.plugin = this.lastPlugin.postcssPlugin + } + } + + let warning = new Warning(text, opts) + this.messages.push(warning) + + return warning + } + + warnings() { + return this.messages.filter(i => i.type === 'warning') + } + + get content() { + return this.css + } +} + +module.exports = Result +Result.default = Result diff --git a/node_modules/postcss/lib/root.d.ts b/node_modules/postcss/lib/root.d.ts new file mode 100644 index 0000000..251b92b --- /dev/null +++ b/node_modules/postcss/lib/root.d.ts @@ -0,0 +1,73 @@ +import Container, { ContainerProps } from './container.js' +import Document from './document.js' +import { ProcessOptions } from './postcss.js' +import Result from './result.js' + +interface RootRaws extends Record { + /** + * The space symbols after the last child to the end of file. + */ + after?: string + + /** + * Non-CSS code before `Root`, when `Root` is inside `Document`. + * + * **Experimental:** some aspects of this node could change within minor + * or patch version releases. + */ + codeBefore?: string + + /** + * Non-CSS code after `Root`, when `Root` is inside `Document`. + * + * **Experimental:** some aspects of this node could change within minor + * or patch version releases. + */ + codeAfter?: string + + /** + * Is the last child has an (optional) semicolon. + */ + semicolon?: boolean +} + +export interface RootProps extends ContainerProps { + /** + * Information used to generate byte-to-byte equal node string + * as it was in the origin input. + * */ + raws?: RootRaws +} + +/** + * Represents a CSS file and contains all its parsed nodes. + * + * ```js + * const root = postcss.parse('a{color:black} b{z-index:2}') + * root.type //=> 'root' + * root.nodes.length //=> 2 + * ``` + */ +export default class Root extends Container { + type: 'root' + parent: Document | undefined + raws: RootRaws + + /** + * Returns a `Result` instance representing the root’s CSS. + * + * ```js + * const root1 = postcss.parse(css1, { from: 'a.css' }) + * const root2 = postcss.parse(css2, { from: 'b.css' }) + * root1.append(root2) + * const result = root1.toResult({ to: 'all.css', map: true }) + * ``` + * + * @param opts Options. + * @return Result with current root’s CSS. + */ + toResult(options?: ProcessOptions): Result + + constructor(defaults?: RootProps) + assign(overrides: object | RootProps): this +} diff --git a/node_modules/postcss/lib/root.js b/node_modules/postcss/lib/root.js new file mode 100644 index 0000000..18e4cea --- /dev/null +++ b/node_modules/postcss/lib/root.js @@ -0,0 +1,59 @@ +'use strict' + +let Container = require('./container') + +let LazyResult, Processor + +class Root extends Container { + constructor(defaults) { + super(defaults) + this.type = 'root' + if (!this.nodes) this.nodes = [] + } + + removeChild(child, ignore) { + let index = this.index(child) + + if (!ignore && index === 0 && this.nodes.length > 1) { + this.nodes[1].raws.before = this.nodes[index].raws.before + } + + return super.removeChild(child) + } + + normalize(child, sample, type) { + let nodes = super.normalize(child) + + if (sample) { + if (type === 'prepend') { + if (this.nodes.length > 1) { + sample.raws.before = this.nodes[1].raws.before + } else { + delete sample.raws.before + } + } else if (this.first !== sample) { + for (let node of nodes) { + node.raws.before = sample.raws.before + } + } + } + + return nodes + } + + toResult(opts = {}) { + let lazy = new LazyResult(new Processor(), this, opts) + return lazy.stringify() + } +} + +Root.registerLazyResult = dependant => { + LazyResult = dependant +} + +Root.registerProcessor = dependant => { + Processor = dependant +} + +module.exports = Root +Root.default = Root diff --git a/node_modules/postcss/lib/rule.d.ts b/node_modules/postcss/lib/rule.d.ts new file mode 100644 index 0000000..75ddf31 --- /dev/null +++ b/node_modules/postcss/lib/rule.d.ts @@ -0,0 +1,104 @@ +import Container, { ContainerProps } from './container.js' + +interface RuleRaws { + /** + * The space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + */ + before?: string + + /** + * The space symbols after the last child of the node to the end of the node. + */ + after?: string + + /** + * The symbols between the selector and `{` for rules. + */ + between?: string + + /** + * Contains `true` if the last child has an (optional) semicolon. + */ + semicolon?: boolean + + /** + * Contains `true` if there is semicolon after rule. + */ + ownSemicolon?: string + + /** + * The rule’s selector with comments. + */ + selector?: { + value: string + raw: string + } +} + +export interface RuleProps extends ContainerProps { + /** Selector or selectors of the rule. */ + selector?: string + /** Selectors of the rule represented as an array of strings. */ + selectors?: string[] + /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ + raws?: RuleRaws +} + +/** + * Represents a CSS rule: a selector followed by a declaration block. + * + * ```js + * Once (root, { Rule }) { + * let a = new Rule({ selector: 'a' }) + * a.append(…) + * root.append(a) + * } + * ``` + * + * ```js + * const root = postcss.parse('a{}') + * const rule = root.first + * rule.type //=> 'rule' + * rule.toString() //=> 'a{}' + * ``` + */ +export default class Rule extends Container { + type: 'rule' + parent: Container | undefined + raws: RuleRaws + + /** + * The rule’s full selector represented as a string. + * + * ```js + * const root = postcss.parse('a, b { }') + * const rule = root.first + * rule.selector //=> 'a, b' + * ``` + */ + selector: string + + /** + * An array containing the rule’s individual selectors. + * Groups of selectors are split at commas. + * + * ```js + * const root = postcss.parse('a, b { }') + * const rule = root.first + * + * rule.selector //=> 'a, b' + * rule.selectors //=> ['a', 'b'] + * + * rule.selectors = ['a', 'strong'] + * rule.selector //=> 'a, strong' + * ``` + */ + selectors: string[] + + constructor(defaults?: RuleProps) + assign(overrides: object | RuleProps): this + clone(overrides?: Partial): this + cloneBefore(overrides?: Partial): this + cloneAfter(overrides?: Partial): this +} diff --git a/node_modules/postcss/lib/rule.js b/node_modules/postcss/lib/rule.js new file mode 100644 index 0000000..a93ab25 --- /dev/null +++ b/node_modules/postcss/lib/rule.js @@ -0,0 +1,27 @@ +'use strict' + +let Container = require('./container') +let list = require('./list') + +class Rule extends Container { + constructor(defaults) { + super(defaults) + this.type = 'rule' + if (!this.nodes) this.nodes = [] + } + + get selectors() { + return list.comma(this.selector) + } + + set selectors(values) { + let match = this.selector ? this.selector.match(/,\s*/) : null + let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen') + this.selector = values.join(sep) + } +} + +module.exports = Rule +Rule.default = Rule + +Container.registerRule(Rule) diff --git a/node_modules/postcss/lib/stringifier.js b/node_modules/postcss/lib/stringifier.js new file mode 100644 index 0000000..81e1251 --- /dev/null +++ b/node_modules/postcss/lib/stringifier.js @@ -0,0 +1,351 @@ +'use strict' + +const DEFAULT_RAW = { + colon: ': ', + indent: ' ', + beforeDecl: '\n', + beforeRule: '\n', + beforeOpen: ' ', + beforeClose: '\n', + beforeComment: '\n', + after: '\n', + emptyBody: '', + commentLeft: ' ', + commentRight: ' ', + semicolon: false +} + +function capitalize(str) { + return str[0].toUpperCase() + str.slice(1) +} + +class Stringifier { + constructor(builder) { + this.builder = builder + } + + stringify(node, semicolon) { + /* istanbul ignore if */ + if (!this[node.type]) { + throw new Error( + 'Unknown AST node type ' + + node.type + + '. ' + + 'Maybe you need to change PostCSS stringifier.' + ) + } + this[node.type](node, semicolon) + } + + document(node) { + this.body(node) + } + + root(node) { + this.body(node) + if (node.raws.after) this.builder(node.raws.after) + } + + comment(node) { + let left = this.raw(node, 'left', 'commentLeft') + let right = this.raw(node, 'right', 'commentRight') + this.builder('/*' + left + node.text + right + '*/', node) + } + + decl(node, semicolon) { + let between = this.raw(node, 'between', 'colon') + let string = node.prop + between + this.rawValue(node, 'value') + + if (node.important) { + string += node.raws.important || ' !important' + } + + if (semicolon) string += ';' + this.builder(string, node) + } + + rule(node) { + this.block(node, this.rawValue(node, 'selector')) + if (node.raws.ownSemicolon) { + this.builder(node.raws.ownSemicolon, node, 'end') + } + } + + atrule(node, semicolon) { + let name = '@' + node.name + let params = node.params ? this.rawValue(node, 'params') : '' + + if (typeof node.raws.afterName !== 'undefined') { + name += node.raws.afterName + } else if (params) { + name += ' ' + } + + if (node.nodes) { + this.block(node, name + params) + } else { + let end = (node.raws.between || '') + (semicolon ? ';' : '') + this.builder(name + params + end, node) + } + } + + body(node) { + let last = node.nodes.length - 1 + while (last > 0) { + if (node.nodes[last].type !== 'comment') break + last -= 1 + } + + let semicolon = this.raw(node, 'semicolon') + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i] + let before = this.raw(child, 'before') + if (before) this.builder(before) + this.stringify(child, last !== i || semicolon) + } + } + + block(node, start) { + let between = this.raw(node, 'between', 'beforeOpen') + this.builder(start + between + '{', node, 'start') + + let after + if (node.nodes && node.nodes.length) { + this.body(node) + after = this.raw(node, 'after') + } else { + after = this.raw(node, 'after', 'emptyBody') + } + + if (after) this.builder(after) + this.builder('}', node, 'end') + } + + raw(node, own, detect) { + let value + if (!detect) detect = own + + // Already had + if (own) { + value = node.raws[own] + if (typeof value !== 'undefined') return value + } + + let parent = node.parent + + if (detect === 'before') { + // Hack for first rule in CSS + if (!parent || (parent.type === 'root' && parent.first === node)) { + return '' + } + + // `root` nodes in `document` should use only their own raws + if (parent && parent.type === 'document') { + return '' + } + } + + // Floating child without parent + if (!parent) return DEFAULT_RAW[detect] + + // Detect style by other nodes + let root = node.root() + if (!root.rawCache) root.rawCache = {} + if (typeof root.rawCache[detect] !== 'undefined') { + return root.rawCache[detect] + } + + if (detect === 'before' || detect === 'after') { + return this.beforeAfter(node, detect) + } else { + let method = 'raw' + capitalize(detect) + if (this[method]) { + value = this[method](root, node) + } else { + root.walk(i => { + value = i.raws[own] + if (typeof value !== 'undefined') return false + }) + } + } + + if (typeof value === 'undefined') value = DEFAULT_RAW[detect] + + root.rawCache[detect] = value + return value + } + + rawSemicolon(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length && i.last.type === 'decl') { + value = i.raws.semicolon + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawEmptyBody(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length === 0) { + value = i.raws.after + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawIndent(root) { + if (root.raws.indent) return root.raws.indent + let value + root.walk(i => { + let p = i.parent + if (p && p !== root && p.parent && p.parent === root) { + if (typeof i.raws.before !== 'undefined') { + let parts = i.raws.before.split('\n') + value = parts[parts.length - 1] + value = value.replace(/\S/g, '') + return false + } + } + }) + return value + } + + rawBeforeComment(root, node) { + let value + root.walkComments(i => { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + }) + if (typeof value === 'undefined') { + value = this.raw(node, null, 'beforeDecl') + } else if (value) { + value = value.replace(/\S/g, '') + } + return value + } + + rawBeforeDecl(root, node) { + let value + root.walkDecls(i => { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + }) + if (typeof value === 'undefined') { + value = this.raw(node, null, 'beforeRule') + } else if (value) { + value = value.replace(/\S/g, '') + } + return value + } + + rawBeforeRule(root) { + let value + root.walk(i => { + if (i.nodes && (i.parent !== root || root.first !== i)) { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + } + }) + if (value) value = value.replace(/\S/g, '') + return value + } + + rawBeforeClose(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length > 0) { + if (typeof i.raws.after !== 'undefined') { + value = i.raws.after + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + } + }) + if (value) value = value.replace(/\S/g, '') + return value + } + + rawBeforeOpen(root) { + let value + root.walk(i => { + if (i.type !== 'decl') { + value = i.raws.between + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawColon(root) { + let value + root.walkDecls(i => { + if (typeof i.raws.between !== 'undefined') { + value = i.raws.between.replace(/[^\s:]/g, '') + return false + } + }) + return value + } + + beforeAfter(node, detect) { + let value + if (node.type === 'decl') { + value = this.raw(node, null, 'beforeDecl') + } else if (node.type === 'comment') { + value = this.raw(node, null, 'beforeComment') + } else if (detect === 'before') { + value = this.raw(node, null, 'beforeRule') + } else { + value = this.raw(node, null, 'beforeClose') + } + + let buf = node.parent + let depth = 0 + while (buf && buf.type !== 'root') { + depth += 1 + buf = buf.parent + } + + if (value.includes('\n')) { + let indent = this.raw(node, null, 'indent') + if (indent.length) { + for (let step = 0; step < depth; step++) value += indent + } + } + + return value + } + + rawValue(node, prop) { + let value = node[prop] + let raw = node.raws[prop] + if (raw && raw.value === value) { + return raw.raw + } + + return value + } +} + +module.exports = Stringifier diff --git a/node_modules/postcss/lib/stringify.d.ts b/node_modules/postcss/lib/stringify.d.ts new file mode 100644 index 0000000..363682f --- /dev/null +++ b/node_modules/postcss/lib/stringify.d.ts @@ -0,0 +1,5 @@ +import { Stringifier } from './postcss.js' + +declare const stringify: Stringifier + +export default stringify diff --git a/node_modules/postcss/lib/stringify.js b/node_modules/postcss/lib/stringify.js new file mode 100644 index 0000000..77bd017 --- /dev/null +++ b/node_modules/postcss/lib/stringify.js @@ -0,0 +1,11 @@ +'use strict' + +let Stringifier = require('./stringifier') + +function stringify(node, builder) { + let str = new Stringifier(builder) + str.stringify(node) +} + +module.exports = stringify +stringify.default = stringify diff --git a/node_modules/postcss/lib/symbols.js b/node_modules/postcss/lib/symbols.js new file mode 100644 index 0000000..a142c26 --- /dev/null +++ b/node_modules/postcss/lib/symbols.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports.isClean = Symbol('isClean') + +module.exports.my = Symbol('my') diff --git a/node_modules/postcss/lib/terminal-highlight.js b/node_modules/postcss/lib/terminal-highlight.js new file mode 100644 index 0000000..60282bd --- /dev/null +++ b/node_modules/postcss/lib/terminal-highlight.js @@ -0,0 +1,70 @@ +'use strict' + +let { cyan, gray, green, yellow, magenta } = require('colorette') + +let tokenizer = require('./tokenize') + +let Input + +function registerInput(dependant) { + Input = dependant +} + +const HIGHLIGHT_THEME = { + 'brackets': cyan, + 'at-word': cyan, + 'comment': gray, + 'string': green, + 'class': yellow, + 'hash': magenta, + 'call': cyan, + '(': cyan, + ')': cyan, + '{': yellow, + '}': yellow, + '[': yellow, + ']': yellow, + ':': yellow, + ';': yellow +} + +function getTokenType([type, value], processor) { + if (type === 'word') { + if (value[0] === '.') { + return 'class' + } + if (value[0] === '#') { + return 'hash' + } + } + + if (!processor.endOfFile()) { + let next = processor.nextToken() + processor.back(next) + if (next[0] === 'brackets' || next[0] === '(') return 'call' + } + + return type +} + +function terminalHighlight(css) { + let processor = tokenizer(new Input(css), { ignoreErrors: true }) + let result = '' + while (!processor.endOfFile()) { + let token = processor.nextToken() + let color = HIGHLIGHT_THEME[getTokenType(token, processor)] + if (color) { + result += token[1] + .split(/\r?\n/) + .map(i => color(i)) + .join('\n') + } else { + result += token[1] + } + } + return result +} + +terminalHighlight.registerInput = registerInput + +module.exports = terminalHighlight diff --git a/node_modules/postcss/lib/tokenize.js b/node_modules/postcss/lib/tokenize.js new file mode 100644 index 0000000..8dac706 --- /dev/null +++ b/node_modules/postcss/lib/tokenize.js @@ -0,0 +1,266 @@ +'use strict' + +const SINGLE_QUOTE = "'".charCodeAt(0) +const DOUBLE_QUOTE = '"'.charCodeAt(0) +const BACKSLASH = '\\'.charCodeAt(0) +const SLASH = '/'.charCodeAt(0) +const NEWLINE = '\n'.charCodeAt(0) +const SPACE = ' '.charCodeAt(0) +const FEED = '\f'.charCodeAt(0) +const TAB = '\t'.charCodeAt(0) +const CR = '\r'.charCodeAt(0) +const OPEN_SQUARE = '['.charCodeAt(0) +const CLOSE_SQUARE = ']'.charCodeAt(0) +const OPEN_PARENTHESES = '('.charCodeAt(0) +const CLOSE_PARENTHESES = ')'.charCodeAt(0) +const OPEN_CURLY = '{'.charCodeAt(0) +const CLOSE_CURLY = '}'.charCodeAt(0) +const SEMICOLON = ';'.charCodeAt(0) +const ASTERISK = '*'.charCodeAt(0) +const COLON = ':'.charCodeAt(0) +const AT = '@'.charCodeAt(0) + +const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g +const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g +const RE_BAD_BRACKET = /.[\n"'(/\\]/ +const RE_HEX_ESCAPE = /[\da-f]/i + +module.exports = function tokenizer(input, options = {}) { + let css = input.css.valueOf() + let ignore = options.ignoreErrors + + let code, next, quote, content, escape + let escaped, escapePos, prev, n, currentToken + + let length = css.length + let pos = 0 + let buffer = [] + let returned = [] + + function position() { + return pos + } + + function unclosed(what) { + throw input.error('Unclosed ' + what, pos) + } + + function endOfFile() { + return returned.length === 0 && pos >= length + } + + function nextToken(opts) { + if (returned.length) return returned.pop() + if (pos >= length) return + + let ignoreUnclosed = opts ? opts.ignoreUnclosed : false + + code = css.charCodeAt(pos) + + switch (code) { + case NEWLINE: + case SPACE: + case TAB: + case CR: + case FEED: { + next = pos + do { + next += 1 + code = css.charCodeAt(next) + } while ( + code === SPACE || + code === NEWLINE || + code === TAB || + code === CR || + code === FEED + ) + + currentToken = ['space', css.slice(pos, next)] + pos = next - 1 + break + } + + case OPEN_SQUARE: + case CLOSE_SQUARE: + case OPEN_CURLY: + case CLOSE_CURLY: + case COLON: + case SEMICOLON: + case CLOSE_PARENTHESES: { + let controlChar = String.fromCharCode(code) + currentToken = [controlChar, controlChar, pos] + break + } + + case OPEN_PARENTHESES: { + prev = buffer.length ? buffer.pop()[1] : '' + n = css.charCodeAt(pos + 1) + if ( + prev === 'url' && + n !== SINGLE_QUOTE && + n !== DOUBLE_QUOTE && + n !== SPACE && + n !== NEWLINE && + n !== TAB && + n !== FEED && + n !== CR + ) { + next = pos + do { + escaped = false + next = css.indexOf(')', next + 1) + if (next === -1) { + if (ignore || ignoreUnclosed) { + next = pos + break + } else { + unclosed('bracket') + } + } + escapePos = next + while (css.charCodeAt(escapePos - 1) === BACKSLASH) { + escapePos -= 1 + escaped = !escaped + } + } while (escaped) + + currentToken = ['brackets', css.slice(pos, next + 1), pos, next] + + pos = next + } else { + next = css.indexOf(')', pos + 1) + content = css.slice(pos, next + 1) + + if (next === -1 || RE_BAD_BRACKET.test(content)) { + currentToken = ['(', '(', pos] + } else { + currentToken = ['brackets', content, pos, next] + pos = next + } + } + + break + } + + case SINGLE_QUOTE: + case DOUBLE_QUOTE: { + quote = code === SINGLE_QUOTE ? "'" : '"' + next = pos + do { + escaped = false + next = css.indexOf(quote, next + 1) + if (next === -1) { + if (ignore || ignoreUnclosed) { + next = pos + 1 + break + } else { + unclosed('string') + } + } + escapePos = next + while (css.charCodeAt(escapePos - 1) === BACKSLASH) { + escapePos -= 1 + escaped = !escaped + } + } while (escaped) + + currentToken = ['string', css.slice(pos, next + 1), pos, next] + pos = next + break + } + + case AT: { + RE_AT_END.lastIndex = pos + 1 + RE_AT_END.test(css) + if (RE_AT_END.lastIndex === 0) { + next = css.length - 1 + } else { + next = RE_AT_END.lastIndex - 2 + } + + currentToken = ['at-word', css.slice(pos, next + 1), pos, next] + + pos = next + break + } + + case BACKSLASH: { + next = pos + escape = true + while (css.charCodeAt(next + 1) === BACKSLASH) { + next += 1 + escape = !escape + } + code = css.charCodeAt(next + 1) + if ( + escape && + code !== SLASH && + code !== SPACE && + code !== NEWLINE && + code !== TAB && + code !== CR && + code !== FEED + ) { + next += 1 + if (RE_HEX_ESCAPE.test(css.charAt(next))) { + while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) { + next += 1 + } + if (css.charCodeAt(next + 1) === SPACE) { + next += 1 + } + } + } + + currentToken = ['word', css.slice(pos, next + 1), pos, next] + + pos = next + break + } + + default: { + if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) { + next = css.indexOf('*/', pos + 2) + 1 + if (next === 0) { + if (ignore || ignoreUnclosed) { + next = css.length + } else { + unclosed('comment') + } + } + + currentToken = ['comment', css.slice(pos, next + 1), pos, next] + pos = next + } else { + RE_WORD_END.lastIndex = pos + 1 + RE_WORD_END.test(css) + if (RE_WORD_END.lastIndex === 0) { + next = css.length - 1 + } else { + next = RE_WORD_END.lastIndex - 2 + } + + currentToken = ['word', css.slice(pos, next + 1), pos, next] + buffer.push(currentToken) + pos = next + } + + break + } + } + + pos++ + return currentToken + } + + function back(token) { + returned.push(token) + } + + return { + back, + nextToken, + endOfFile, + position + } +} diff --git a/node_modules/postcss/lib/warn-once.js b/node_modules/postcss/lib/warn-once.js new file mode 100644 index 0000000..6896b75 --- /dev/null +++ b/node_modules/postcss/lib/warn-once.js @@ -0,0 +1,12 @@ +'use strict' + +let printed = {} + +module.exports = function warnOnce(message) { + if (printed[message]) return + printed[message] = true + + if (typeof console !== 'undefined' && console.warn) { + console.warn(message) + } +} diff --git a/node_modules/postcss/lib/warning.d.ts b/node_modules/postcss/lib/warning.d.ts new file mode 100644 index 0000000..a285367 --- /dev/null +++ b/node_modules/postcss/lib/warning.d.ts @@ -0,0 +1,104 @@ +import Node from './node.js' + +export interface WarningOptions { + /** + * CSS node that caused the warning. + */ + node?: Node + + /** + * Word in CSS source that caused the warning. + */ + word?: string + + /** + * Index in CSS node string that caused the warning. + */ + index?: number + + /** + * Name of the plugin that created this warning. `Result#warn` fills + * this property automatically. + */ + plugin?: string +} + +/** + * Represents a plugin’s warning. It can be created using `Node#warn`. + * + * ```js + * if (decl.important) { + * decl.warn(result, 'Avoid !important', { word: '!important' }) + * } + * ``` + */ +export default class Warning { + /** + * Type to filter warnings from `Result#messages`. + * Always equal to `"warning"`. + */ + type: 'warning' + + /** + * The warning message. + * + * ```js + * warning.text //=> 'Try to avoid !important' + * ``` + */ + text: string + + /** + * The name of the plugin that created this warning. + * When you call `Node#warn` it will fill this property automatically. + * + * ```js + * warning.plugin //=> 'postcss-important' + * ``` + */ + plugin: string + + /** + * Contains the CSS node that caused the warning. + * + * ```js + * warning.node.toString() //=> 'color: white !important' + * ``` + */ + node: Node + + /** + * Line in the input file with this warning’s source. + * + * ```js + * warning.line //=> 5 + * ``` + */ + line: number + + /** + * Column in the input file with this warning’s source. + * + * ```js + * warning.column //=> 6 + * ``` + */ + column: number + + /** + * @param text Warning message. + * @param opts Warning options. + */ + constructor(text: string, opts?: WarningOptions) + + /** + * Returns a warning position and message. + * + * ```js + * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important' + * ``` + * + * @return Warning position and message. + */ + toString(): string +} diff --git a/node_modules/postcss/lib/warning.js b/node_modules/postcss/lib/warning.js new file mode 100644 index 0000000..cdb0281 --- /dev/null +++ b/node_modules/postcss/lib/warning.js @@ -0,0 +1,35 @@ +'use strict' + +class Warning { + constructor(text, opts = {}) { + this.type = 'warning' + this.text = text + + if (opts.node && opts.node.source) { + let pos = opts.node.positionBy(opts) + this.line = pos.line + this.column = pos.column + } + + for (let opt in opts) this[opt] = opts[opt] + } + + toString() { + if (this.node) { + return this.node.error(this.text, { + plugin: this.plugin, + index: this.index, + word: this.word + }).message + } + + if (this.plugin) { + return this.plugin + ': ' + this.text + } + + return this.text + } +} + +module.exports = Warning +Warning.default = Warning diff --git a/node_modules/postcss/package.json b/node_modules/postcss/package.json new file mode 100644 index 0000000..df26cbc --- /dev/null +++ b/node_modules/postcss/package.json @@ -0,0 +1,76 @@ +{ + "name": "postcss", + "version": "8.3.6", + "description": "Tool for transforming styles with JS plugins", + "engines": { + "node": "^10 || ^12 || >=14" + }, + "exports": { + ".": { + "require": "./lib/postcss.js", + "import": "./lib/postcss.mjs", + "types": "./lib/postcss.d.ts" + }, + "./lib/at-rule": "./lib/at-rule.js", + "./lib/comment": "./lib/comment.js", + "./lib/container": "./lib/container.js", + "./lib/css-syntax-error": "./lib/css-syntax-error.js", + "./lib/declaration": "./lib/declaration.js", + "./lib/fromJSON": "./lib/fromJSON.js", + "./lib/input": "./lib/input.js", + "./lib/lazy-result": "./lib/lazy-result.js", + "./lib/list": "./lib/list.js", + "./lib/map-generator": "./lib/map-generator.js", + "./lib/node": "./lib/node.js", + "./lib/parse": "./lib/parse.js", + "./lib/parser": "./lib/parser.js", + "./lib/postcss": "./lib/postcss.js", + "./lib/previous-map": "./lib/previous-map.js", + "./lib/processor": "./lib/processor.js", + "./lib/result": "./lib/result.js", + "./lib/root": "./lib/root.js", + "./lib/rule": "./lib/rule.js", + "./lib/stringifier": "./lib/stringifier.js", + "./lib/stringify": "./lib/stringify.js", + "./lib/symbols": "./lib/symbols.js", + "./lib/terminal-highlight": "./lib/terminal-highlight.js", + "./lib/tokenize": "./lib/tokenize.js", + "./lib/warn-once": "./lib/warn-once.js", + "./lib/warning": "./lib/warning.js", + "./package.json": "./package.json" + }, + "main": "./lib/postcss.js", + "types": "./lib/postcss.d.ts", + "keywords": [ + "css", + "postcss", + "rework", + "preprocessor", + "parser", + "source map", + "transform", + "manipulation", + "transpiler" + ], + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + "author": "Andrey Sitnik ", + "license": "MIT", + "homepage": "https://postcss.org/", + "repository": "postcss/postcss", + "dependencies": { + "colorette": "^1.2.2", + "nanoid": "^3.1.23", + "source-map-js": "^0.6.2" + }, + "browser": { + "./lib/terminal-highlight": false, + "source-map-js": false, + "colorette": false, + "path": false, + "url": false, + "fs": false + } +} diff --git a/node_modules/resolve/.editorconfig b/node_modules/resolve/.editorconfig new file mode 100644 index 0000000..d63f0bb --- /dev/null +++ b/node_modules/resolve/.editorconfig @@ -0,0 +1,37 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 200 + +[*.js] +block_comment_start = /* +block_comment = * +block_comment_end = */ + +[*.yml] +indent_size = 1 + +[package.json] +indent_style = tab + +[lib/core.json] +indent_style = tab + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[{*.json,Makefile}] +max_line_length = off + +[test/{dotdot,resolver,module_dir,multirepo,node_path,pathfilter,precedence}/**/*] +indent_style = off +indent_size = off +max_line_length = off +insert_final_newline = off diff --git a/node_modules/resolve/.eslintignore b/node_modules/resolve/.eslintignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/resolve/.eslintignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/resolve/.eslintrc b/node_modules/resolve/.eslintrc new file mode 100644 index 0000000..a22863c --- /dev/null +++ b/node_modules/resolve/.eslintrc @@ -0,0 +1,39 @@ +{ + "extends": "@ljharb", + "root": true, + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "indent": [2, 4], + "strict": 0, + "complexity": 0, + "consistent-return": 0, + "curly": 0, + "dot-notation": [2, { "allowKeywords": true }], + "func-name-matching": 0, + "func-style": 0, + "global-require": 0, + "id-length": [2, { "min": 1, "max": 30 }], + "max-lines-per-function": 0, + "max-nested-callbacks": 0, + "max-params": 0, + "max-statements-per-line": [2, { "max": 2 }], + "max-statements": 0, + "no-magic-numbers": 0, + "no-console": 0, + "no-shadow": 0, + "no-unused-vars": [2, { "vars": "all", "args": "none" }], + "no-use-before-define": 0, + "object-curly-newline": 0, + "operator-linebreak": [2, "before"], + "sort-keys": 0, + }, + "overrides": [ + { + "files": "test/resolver/nested_symlinks/mylib/*.js", + "rules": { + "no-throw-literal": 0, + }, + }, + ], +} diff --git a/node_modules/resolve/LICENSE b/node_modules/resolve/LICENSE new file mode 100644 index 0000000..ff4fce2 --- /dev/null +++ b/node_modules/resolve/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012 James Halliday + +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/resolve/SECURITY.md b/node_modules/resolve/SECURITY.md new file mode 100644 index 0000000..82e4285 --- /dev/null +++ b/node_modules/resolve/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/node_modules/resolve/appveyor.yml b/node_modules/resolve/appveyor.yml new file mode 100644 index 0000000..747fbdb --- /dev/null +++ b/node_modules/resolve/appveyor.yml @@ -0,0 +1,74 @@ +version: 1.0.{build} +skip_branch_with_pr: true +build: off + +environment: + matrix: + #- nodejs_version: "15" + - nodejs_version: "14" + - nodejs_version: "13" + - nodejs_version: "12" + - nodejs_version: "11" + - nodejs_version: "10" + - nodejs_version: "9" + - nodejs_version: "8" + - nodejs_version: "7" + - nodejs_version: "6" + - nodejs_version: "5" + - nodejs_version: "4" + - nodejs_version: "3" + - nodejs_version: "2" + - nodejs_version: "1" + - nodejs_version: "0.12" + - nodejs_version: "0.10" + - nodejs_version: "0.8" + - nodejs_version: "0.6" +matrix: + # fast_finish: true + allow_failures: + - nodejs_version: "5" # due to windows npm bug, registry-side + - nodejs_version: "0.8" + # platform: x86 # x64 has started failing on the registry side, around early November 2020 + - nodejs_version: "0.6" + +platform: + - x86 + - x64 + +# Install scripts. (runs after repo cloning) +install: + # Fix symlinks in working copy (see https://github.com/appveyor/ci/issues/650#issuecomment-186592582) / https://github.com/charleskorn/batect/commit/d08986802ec43086902958c4ee7e57ff3e71dbef + - git config core.symlinks true + - git reset --hard + # Get the latest stable version of Node.js or io.js + - ps: if ($env:nodejs_version -ne '0.6') { Install-Product node $env:nodejs_version $env:platform } + - ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) $env:platform + - IF %nodejs_version% EQU 0.6 npm config set strict-ssl false && npm -g install npm@1.3 + - IF %nodejs_version% EQU 0.8 npm config set strict-ssl false && npm -g install npm@1.4.28 && npm install -g npm@4.5 + - IF %nodejs_version% EQU 1 npm -g install npm@2.9 + - IF %nodejs_version% EQU 2 npm -g install npm@4 + - IF %nodejs_version% EQU 3 npm -g install npm@4 + - IF %nodejs_version% EQU 4 npm -g install npm@5.3 + - IF %nodejs_version% EQU 5 npm -g install npm@5.3 + - IF %nodejs_version% EQU 6 npm -g install npm@6.9 + - IF %nodejs_version% EQU 7 npm -g install npm@6 + - IF %nodejs_version% EQU 8 npm -g install npm@6 + - IF %nodejs_version% EQU 9 npm -g install npm@6.9 + - IF %nodejs_version% EQU 10 npm -g install npm@7 + - IF %nodejs_version% EQU 11 npm -g install npm@7 + - IF %nodejs_version% EQU 12 npm -g install npm@7 + - IF %nodejs_version% EQU 13 npm -g install npm@7 + - IF %nodejs_version% EQU 14 npm -g install npm@7 + - IF %nodejs_version% EQU 15 npm -g install npm@7 + - set PATH=%APPDATA%\npm;%PATH% + #- IF %nodejs_version% NEQ 0.6 AND %nodejs_version% NEQ 0.8 npm -g install npm + # install modules + - npm install + +# Post-install test scripts. +test_script: + # Output useful info for debugging. + - node --version + - npm --version + # run tests + - npm run tests-only diff --git a/node_modules/resolve/example/async.js b/node_modules/resolve/example/async.js new file mode 100644 index 0000000..20e65dc --- /dev/null +++ b/node_modules/resolve/example/async.js @@ -0,0 +1,5 @@ +var resolve = require('../'); +resolve('tap', { basedir: __dirname }, function (err, res) { + if (err) console.error(err); + else console.log(res); +}); diff --git a/node_modules/resolve/example/sync.js b/node_modules/resolve/example/sync.js new file mode 100644 index 0000000..54b2cc1 --- /dev/null +++ b/node_modules/resolve/example/sync.js @@ -0,0 +1,3 @@ +var resolve = require('../'); +var res = resolve.sync('tap', { basedir: __dirname }); +console.log(res); diff --git a/node_modules/resolve/index.js b/node_modules/resolve/index.js new file mode 100644 index 0000000..125d814 --- /dev/null +++ b/node_modules/resolve/index.js @@ -0,0 +1,6 @@ +var async = require('./lib/async'); +async.core = require('./lib/core'); +async.isCore = require('./lib/is-core'); +async.sync = require('./lib/sync'); + +module.exports = async; diff --git a/node_modules/resolve/lib/async.js b/node_modules/resolve/lib/async.js new file mode 100644 index 0000000..02e80ac --- /dev/null +++ b/node_modules/resolve/lib/async.js @@ -0,0 +1,320 @@ +var fs = require('fs'); +var path = require('path'); +var caller = require('./caller'); +var nodeModulesPaths = require('./node-modules-paths'); +var normalizeOptions = require('./normalize-options'); +var isCore = require('is-core-module'); + +var realpathFS = fs.realpath && typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; + +var defaultIsFile = function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultIsDir = function isDirectory(dir, cb) { + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultRealpath = function realpath(x, cb) { + realpathFS(x, function (realpathErr, realPath) { + if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr); + else cb(null, realpathErr ? x : realPath); + }); +}; + +var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { + if (opts && opts.preserveSymlinks === false) { + realpath(x, cb); + } else { + cb(null, x); + } +}; + +var defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) { + readFile(pkgfile, function (readFileErr, body) { + if (readFileErr) cb(readFileErr); + else { + try { + var pkg = JSON.parse(body); + cb(null, pkg); + } catch (jsonErr) { + cb(null); + } + } + }); +}; + +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); + } + return dirs; +}; + +module.exports = function resolve(x, options, callback) { + var cb = callback; + var opts = options; + if (typeof options === 'function') { + cb = opts; + opts = {}; + } + if (typeof x !== 'string') { + var err = new TypeError('Path must be a string.'); + return process.nextTick(function () { + cb(err); + }); + } + + opts = normalizeOptions(x, opts); + + var isFile = opts.isFile || defaultIsFile; + var isDirectory = opts.isDirectory || defaultIsDir; + var readFile = opts.readFile || fs.readFile; + var realpath = opts.realpath || defaultRealpath; + var readPackage = opts.readPackage || defaultReadPackage; + if (opts.readFile && opts.readPackage) { + var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.'); + return process.nextTick(function () { + cb(conflictErr); + }); + } + var packageIterator = opts.packageIterator; + + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; + + opts.paths = opts.paths || []; + + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = path.resolve(basedir); + + maybeRealpath( + realpath, + absoluteStart, + opts, + function (err, realStart) { + if (err) cb(err); + else init(realStart); + } + ); + + var res; + function init(basedir) { + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + res = path.resolve(basedir, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + if ((/\/$/).test(x) && res === basedir) { + loadAsDirectory(res, opts.package, onfile); + } else loadAsFile(res, opts.package, onfile); + } else if (includeCoreModules && isCore(x)) { + return cb(null, x); + } else loadNodeModules(x, basedir, function (err, n, pkg) { + if (err) cb(err); + else if (n) { + return maybeRealpath(realpath, n, opts, function (err, realN) { + if (err) { + cb(err); + } else { + cb(null, realN, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function onfile(err, m, pkg) { + if (err) cb(err); + else if (m) cb(null, m, pkg); + else loadAsDirectory(res, function (err, d, pkg) { + if (err) cb(err); + else if (d) { + maybeRealpath(realpath, d, opts, function (err, realD) { + if (err) { + cb(err); + } else { + cb(null, realD, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function loadAsFile(x, thePackage, callback) { + var loadAsFilePackage = thePackage; + var cb = callback; + if (typeof loadAsFilePackage === 'function') { + cb = loadAsFilePackage; + loadAsFilePackage = undefined; + } + + var exts = [''].concat(extensions); + load(exts, x, loadAsFilePackage); + + function load(exts, x, loadPackage) { + if (exts.length === 0) return cb(null, undefined, loadPackage); + var file = x + exts[0]; + + var pkg = loadPackage; + if (pkg) onpkg(null, pkg); + else loadpkg(path.dirname(file), onpkg); + + function onpkg(err, pkg_, dir) { + pkg = pkg_; + if (err) return cb(err); + if (dir && pkg && opts.pathFilter) { + var rfile = path.relative(dir, file); + var rel = rfile.slice(0, rfile.length - exts[0].length); + var r = opts.pathFilter(pkg, x, rel); + if (r) return load( + [''].concat(extensions.slice()), + path.resolve(dir, r), + pkg + ); + } + isFile(file, onex); + } + function onex(err, ex) { + if (err) return cb(err); + if (ex) return cb(null, file, pkg); + load(exts.slice(1), x, pkg); + } + } + } + + function loadpkg(dir, cb) { + if (dir === '' || dir === '/') return cb(null); + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return cb(null); + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); + + maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return loadpkg(path.dirname(dir), cb); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + // on err, ex is false + if (!ex) return loadpkg(path.dirname(dir), cb); + + readPackage(readFile, pkgfile, function (err, pkgParam) { + if (err) cb(err); + + var pkg = pkgParam; + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + cb(null, pkg, dir); + }); + }); + }); + } + + function loadAsDirectory(x, loadAsDirectoryPackage, callback) { + var cb = callback; + var fpkg = loadAsDirectoryPackage; + if (typeof fpkg === 'function') { + cb = fpkg; + fpkg = opts.package; + } + + maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return cb(unwrapErr); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + if (err) return cb(err); + if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); + + readPackage(readFile, pkgfile, function (err, pkgParam) { + if (err) return cb(err); + + var pkg = pkgParam; + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + return cb(mainError); + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); + + var dir = path.resolve(x, pkg.main); + loadAsDirectory(dir, pkg, function (err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + loadAsFile(path.join(x, 'index'), pkg, cb); + }); + }); + return; + } + + loadAsFile(path.join(x, '/index'), pkg, cb); + }); + }); + }); + } + + function processDirs(cb, dirs) { + if (dirs.length === 0) return cb(null, undefined); + var dir = dirs[0]; + + isDirectory(path.dirname(dir), isdir); + + function isdir(err, isdir) { + if (err) return cb(err); + if (!isdir) return processDirs(cb, dirs.slice(1)); + loadAsFile(dir, opts.package, onfile); + } + + function onfile(err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + loadAsDirectory(dir, opts.package, ondir); + } + + function ondir(err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + processDirs(cb, dirs.slice(1)); + } + } + function loadNodeModules(x, start, cb) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + processDirs( + cb, + packageIterator ? packageIterator(x, start, thunk, opts) : thunk() + ); + } +}; diff --git a/node_modules/resolve/lib/caller.js b/node_modules/resolve/lib/caller.js new file mode 100644 index 0000000..b14a280 --- /dev/null +++ b/node_modules/resolve/lib/caller.js @@ -0,0 +1,8 @@ +module.exports = function () { + // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + var origPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = (new Error()).stack; + Error.prepareStackTrace = origPrepareStackTrace; + return stack[2].getFileName(); +}; diff --git a/node_modules/resolve/lib/core.js b/node_modules/resolve/lib/core.js new file mode 100644 index 0000000..c417d23 --- /dev/null +++ b/node_modules/resolve/lib/core.js @@ -0,0 +1,53 @@ +var current = (process.versions && process.versions.node && process.versions.node.split('.')) || []; + +function specifierIncluded(specifier) { + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + + for (var i = 0; i < 3; ++i) { + var cur = parseInt(current[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } else if (op === '>=') { + return cur >= ver; + } else { + return false; + } + } + return op === '>='; +} + +function matchesRange(range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { return false; } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(specifiers[i])) { return false; } + } + return true; +} + +function versionIncluded(specifierValue) { + if (typeof specifierValue === 'boolean') { return specifierValue; } + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(specifierValue[i])) { return true; } + } + return false; + } + return matchesRange(specifierValue); +} + +var data = require('./core.json'); + +var core = {}; +for (var mod in data) { // eslint-disable-line no-restricted-syntax + if (Object.prototype.hasOwnProperty.call(data, mod)) { + core[mod] = versionIncluded(data[mod]); + } +} +module.exports = core; diff --git a/node_modules/resolve/lib/core.json b/node_modules/resolve/lib/core.json new file mode 100644 index 0000000..0238b61 --- /dev/null +++ b/node_modules/resolve/lib/core.json @@ -0,0 +1,83 @@ +{ + "assert": true, + "assert/strict": ">= 15", + "async_hooks": ">= 8", + "buffer_ieee754": "< 0.9.7", + "buffer": true, + "child_process": true, + "cluster": true, + "console": true, + "constants": true, + "crypto": true, + "_debug_agent": ">= 1 && < 8", + "_debugger": "< 8", + "dgram": true, + "diagnostics_channel": ">= 15.1", + "dns": true, + "dns/promises": ">= 15", + "domain": ">= 0.7.12", + "events": true, + "freelist": "< 6", + "fs": true, + "fs/promises": [">= 10 && < 10.1", ">= 14"], + "_http_agent": ">= 0.11.1", + "_http_client": ">= 0.11.1", + "_http_common": ">= 0.11.1", + "_http_incoming": ">= 0.11.1", + "_http_outgoing": ">= 0.11.1", + "_http_server": ">= 0.11.1", + "http": true, + "http2": ">= 8.8", + "https": true, + "inspector": ">= 8.0.0", + "_linklist": "< 8", + "module": true, + "net": true, + "node-inspect/lib/_inspect": ">= 7.6.0 && < 12", + "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12", + "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12", + "os": true, + "path": true, + "path/posix": ">= 15.3", + "path/win32": ">= 15.3", + "perf_hooks": ">= 8.5", + "process": ">= 1", + "punycode": true, + "querystring": true, + "readline": true, + "repl": true, + "smalloc": ">= 0.11.5 && < 3", + "_stream_duplex": ">= 0.9.4", + "_stream_transform": ">= 0.9.4", + "_stream_wrap": ">= 1.4.1", + "_stream_passthrough": ">= 0.9.4", + "_stream_readable": ">= 0.9.4", + "_stream_writable": ">= 0.9.4", + "stream": true, + "stream/promises": ">= 15", + "string_decoder": true, + "sys": [">= 0.6 && < 0.7", ">= 0.8"], + "timers": true, + "timers/promises": ">= 15", + "_tls_common": ">= 0.11.13", + "_tls_legacy": ">= 0.11.3 && < 10", + "_tls_wrap": ">= 0.11.3", + "tls": true, + "trace_events": ">= 10", + "tty": true, + "url": true, + "util": true, + "util/types": ">= 15.3", + "v8/tools/arguments": ">= 10 && < 12", + "v8/tools/codemap": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"], + "v8/tools/consarray": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"], + "v8/tools/csvparser": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"], + "v8/tools/logreader": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"], + "v8/tools/profile_view": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"], + "v8/tools/splaytree": [">= 4.4.0 && < 5", ">= 5.2.0 && < 12"], + "v8": ">= 1", + "vm": true, + "wasi": ">= 13.4 && < 13.5", + "worker_threads": ">= 11.7", + "zlib": true +} diff --git a/node_modules/resolve/lib/is-core.js b/node_modules/resolve/lib/is-core.js new file mode 100644 index 0000000..537f5c7 --- /dev/null +++ b/node_modules/resolve/lib/is-core.js @@ -0,0 +1,5 @@ +var isCoreModule = require('is-core-module'); + +module.exports = function isCore(x) { + return isCoreModule(x); +}; diff --git a/node_modules/resolve/lib/node-modules-paths.js b/node_modules/resolve/lib/node-modules-paths.js new file mode 100644 index 0000000..2b43813 --- /dev/null +++ b/node_modules/resolve/lib/node-modules-paths.js @@ -0,0 +1,42 @@ +var path = require('path'); +var parse = path.parse || require('path-parse'); + +var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { + var prefix = '/'; + if ((/^([A-Za-z]:)/).test(absoluteStart)) { + prefix = ''; + } else if ((/^\\\\/).test(absoluteStart)) { + prefix = '\\\\'; + } + + var paths = [absoluteStart]; + var parsed = parse(absoluteStart); + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = parse(parsed.dir); + } + + return paths.reduce(function (dirs, aPath) { + return dirs.concat(modules.map(function (moduleDir) { + return path.resolve(prefix, aPath, moduleDir); + })); + }, []); +}; + +module.exports = function nodeModulesPaths(start, opts, request) { + var modules = opts && opts.moduleDirectory + ? [].concat(opts.moduleDirectory) + : ['node_modules']; + + if (opts && typeof opts.paths === 'function') { + return opts.paths( + request, + start, + function () { return getNodeModulesDirs(start, modules); }, + opts + ); + } + + var dirs = getNodeModulesDirs(start, modules); + return opts && opts.paths ? dirs.concat(opts.paths) : dirs; +}; diff --git a/node_modules/resolve/lib/normalize-options.js b/node_modules/resolve/lib/normalize-options.js new file mode 100644 index 0000000..4b56904 --- /dev/null +++ b/node_modules/resolve/lib/normalize-options.js @@ -0,0 +1,10 @@ +module.exports = function (x, opts) { + /** + * This file is purposefully a passthrough. It's expected that third-party + * environments will override it at runtime in order to inject special logic + * into `resolve` (by manipulating the options). One such example is the PnP + * code path in Yarn. + */ + + return opts || {}; +}; diff --git a/node_modules/resolve/lib/sync.js b/node_modules/resolve/lib/sync.js new file mode 100644 index 0000000..ef9bd80 --- /dev/null +++ b/node_modules/resolve/lib/sync.js @@ -0,0 +1,199 @@ +var isCore = require('is-core-module'); +var fs = require('fs'); +var path = require('path'); +var caller = require('./caller'); +var nodeModulesPaths = require('./node-modules-paths'); +var normalizeOptions = require('./normalize-options'); + +var realpathFS = fs.realpathSync && typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; + +var defaultIsFile = function isFile(file) { + try { + var stat = fs.statSync(file); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isFile() || stat.isFIFO(); +}; + +var defaultIsDir = function isDirectory(dir) { + try { + var stat = fs.statSync(dir); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isDirectory(); +}; + +var defaultRealpathSync = function realpathSync(x) { + try { + return realpathFS(x); + } catch (realpathErr) { + if (realpathErr.code !== 'ENOENT') { + throw realpathErr; + } + } + return x; +}; + +var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { + if (opts && opts.preserveSymlinks === false) { + return realpathSync(x); + } + return x; +}; + +var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) { + var body = readFileSync(pkgfile); + try { + var pkg = JSON.parse(body); + return pkg; + } catch (jsonErr) {} +}; + +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); + } + return dirs; +}; + +module.exports = function resolveSync(x, options) { + if (typeof x !== 'string') { + throw new TypeError('Path must be a string.'); + } + var opts = normalizeOptions(x, options); + + var isFile = opts.isFile || defaultIsFile; + var readFileSync = opts.readFileSync || fs.readFileSync; + var isDirectory = opts.isDirectory || defaultIsDir; + var realpathSync = opts.realpathSync || defaultRealpathSync; + var readPackageSync = opts.readPackageSync || defaultReadPackageSync; + if (opts.readFileSync && opts.readPackageSync) { + throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.'); + } + var packageIterator = opts.packageIterator; + + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; + + opts.paths = opts.paths || []; + + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = maybeRealpathSync(realpathSync, path.resolve(basedir), opts); + + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + var res = path.resolve(absoluteStart, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + var m = loadAsFileSync(res) || loadAsDirectorySync(res); + if (m) return maybeRealpathSync(realpathSync, m, opts); + } else if (includeCoreModules && isCore(x)) { + return x; + } else { + var n = loadNodeModulesSync(x, absoluteStart); + if (n) return maybeRealpathSync(realpathSync, n, opts); + } + + var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + err.code = 'MODULE_NOT_FOUND'; + throw err; + + function loadAsFileSync(x) { + var pkg = loadpkg(path.dirname(x)); + + if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { + var rfile = path.relative(pkg.dir, x); + var r = opts.pathFilter(pkg.pkg, x, rfile); + if (r) { + x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign + } + } + + if (isFile(x)) { + return x; + } + + for (var i = 0; i < extensions.length; i++) { + var file = x + extensions[i]; + if (isFile(file)) { + return file; + } + } + } + + function loadpkg(dir) { + if (dir === '' || dir === '/') return; + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return; + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; + + var pkgfile = path.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json'); + + if (!isFile(pkgfile)) { + return loadpkg(path.dirname(dir)); + } + + var pkg = readPackageSync(readFileSync, pkgfile); + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment + } + + return { pkg: pkg, dir: dir }; + } + + function loadAsDirectorySync(x) { + var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); + if (isFile(pkgfile)) { + try { + var pkg = readPackageSync(readFileSync, pkgfile); + } catch (e) {} + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + throw mainError; + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + try { + var m = loadAsFileSync(path.resolve(x, pkg.main)); + if (m) return m; + var n = loadAsDirectorySync(path.resolve(x, pkg.main)); + if (n) return n; + } catch (e) {} + } + } + + return loadAsFileSync(path.join(x, '/index')); + } + + function loadNodeModulesSync(x, start) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); + + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + if (isDirectory(path.dirname(dir))) { + var m = loadAsFileSync(dir); + if (m) return m; + var n = loadAsDirectorySync(dir); + if (n) return n; + } + } + } +}; diff --git a/node_modules/resolve/package.json b/node_modules/resolve/package.json new file mode 100644 index 0000000..52a78a2 --- /dev/null +++ b/node_modules/resolve/package.json @@ -0,0 +1,51 @@ +{ + "name": "resolve", + "description": "resolve like require.resolve() on behalf of files asynchronously and synchronously", + "version": "1.20.0", + "repository": { + "type": "git", + "url": "git://github.com/browserify/resolve.git" + }, + "main": "index.js", + "keywords": [ + "resolve", + "require", + "node", + "module" + ], + "scripts": { + "prepublish": "safe-publish-latest && cp node_modules/is-core-module/core.json ./lib/ ||:", + "prelint": "eclint check '**/*'", + "lint": "eslint --ext=js,mjs .", + "pretests-only": "cd ./test/resolver/nested_symlinks && node mylib/sync && node mylib/async", + "tests-only": "tape test/*.js", + "pretest": "npm run lint", + "test": "npm run --silent tests-only", + "posttest": "npm run test:multirepo && aud --production", + "test:multirepo": "cd ./test/resolver/multirepo && npm install && npm test" + }, + "devDependencies": { + "@ljharb/eslint-config": "^17.5.1", + "array.prototype.map": "^1.0.3", + "aud": "^1.1.4", + "eclint": "^2.8.1", + "eslint": "^7.19.0", + "object-keys": "^1.1.1", + "safe-publish-latest": "^1.1.4", + "tap": "0.4.13", + "tape": "^5.1.1" + }, + "license": "MIT", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "dependencies": { + "is-core-module": "^2.2.0", + "path-parse": "^1.0.6" + } +} diff --git a/node_modules/resolve/readme.markdown b/node_modules/resolve/readme.markdown new file mode 100644 index 0000000..7c9f2dc --- /dev/null +++ b/node_modules/resolve/readme.markdown @@ -0,0 +1,279 @@ +# resolve + +implements the [node `require.resolve()` +algorithm](https://nodejs.org/api/modules.html#modules_all_together) +such that you can `require.resolve()` on behalf of a file asynchronously and +synchronously + +[![build status](https://secure.travis-ci.org/browserify/resolve.png)](http://travis-ci.org/browserify/resolve) + +# example + +asynchronously resolve: + +```js +var resolve = require('resolve'); +resolve('tap', { basedir: __dirname }, function (err, res) { + if (err) console.error(err); + else console.log(res); +}); +``` + +``` +$ node example/async.js +/home/substack/projects/node-resolve/node_modules/tap/lib/main.js +``` + +synchronously resolve: + +```js +var resolve = require('resolve'); +var res = resolve.sync('tap', { basedir: __dirname }); +console.log(res); +``` + +``` +$ node example/sync.js +/home/substack/projects/node-resolve/node_modules/tap/lib/main.js +``` + +# methods + +```js +var resolve = require('resolve'); +``` + +For both the synchronous and asynchronous methods, errors may have any of the following `err.code` values: + +- `MODULE_NOT_FOUND`: the given path string (`id`) could not be resolved to a module +- `INVALID_BASEDIR`: the specified `opts.basedir` doesn't exist, or is not a directory +- `INVALID_PACKAGE_MAIN`: a `package.json` was encountered with an invalid `main` property (eg. not a string) + +## resolve(id, opts={}, cb) + +Asynchronously resolve the module path string `id` into `cb(err, res [, pkg])`, where `pkg` (if defined) is the data from `package.json`. + +options are: + +* opts.basedir - directory to begin resolving from + +* opts.package - `package.json` data applicable to the module being loaded + +* opts.extensions - array of file extensions to search in order + +* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search + +* opts.readFile - how to read files asynchronously + +* opts.isFile - function to asynchronously test whether a file exists + +* opts.isDirectory - function to asynchronously test whether a directory exists + +* opts.realpath - function to asynchronously resolve a potential symlink to its real path + +* `opts.readPackage(readFile, pkgfile, cb)` - function to asynchronously read and parse a package.json file + * readFile - the passed `opts.readFile` or `fs.readFile` if not specified + * pkgfile - path to package.json + * cb - callback + +* `opts.packageFilter(pkg, pkgfile, dir)` - transform the parsed package.json contents before looking at the "main" field + * pkg - package data + * pkgfile - path to package.json + * dir - directory for package.json + +* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package + * pkg - package data + * path - the path being resolved + * relativePath - the path relative from the package.json location + * returns - a relative path that will be joined from the package.json location + +* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this) + + For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function + * request - the import specifier being resolved + * start - lookup path + * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this) + * request - the import specifier being resolved + * start - lookup path + * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"` + +* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving. +This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag. +**Note:** this property is currently `true` by default but it will be changed to +`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*. + +default `opts` values: + +```js +{ + paths: [], + basedir: __dirname, + extensions: ['.js'], + includeCoreModules: true, + readFile: fs.readFile, + isFile: function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }, + isDirectory: function isDirectory(dir, cb) { + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }, + realpath: function realpath(file, cb) { + var realpath = typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; + realpath(file, function (realPathErr, realPath) { + if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr); + else cb(null, realPathErr ? file : realPath); + }); + }, + readPackage: function defaultReadPackage(readFile, pkgfile, cb) { + readFile(pkgfile, function (readFileErr, body) { + if (readFileErr) cb(readFileErr); + else { + try { + var pkg = JSON.parse(body); + cb(null, pkg); + } catch (jsonErr) { + cb(null); + } + } + }); + }, + moduleDirectory: 'node_modules', + preserveSymlinks: true +} +``` + +## resolve.sync(id, opts) + +Synchronously resolve the module path string `id`, returning the result and +throwing an error when `id` can't be resolved. + +options are: + +* opts.basedir - directory to begin resolving from + +* opts.extensions - array of file extensions to search in order + +* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search + +* opts.readFileSync - how to read files synchronously + +* opts.isFile - function to synchronously test whether a file exists + +* opts.isDirectory - function to synchronously test whether a directory exists + +* opts.realpathSync - function to synchronously resolve a potential symlink to its real path + +* `opts.readPackageSync(readFileSync, pkgfile)` - function to synchronously read and parse a package.json file + * readFileSync - the passed `opts.readFileSync` or `fs.readFileSync` if not specified + * pkgfile - path to package.json + +* `opts.packageFilter(pkg, dir)` - transform the parsed package.json contents before looking at the "main" field + * pkg - package data + * dir - directory for package.json (Note: the second argument will change to "pkgfile" in v2) + +* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package + * pkg - package data + * path - the path being resolved + * relativePath - the path relative from the package.json location + * returns - a relative path that will be joined from the package.json location + +* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this) + + For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function + * request - the import specifier being resolved + * start - lookup path + * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this) + * request - the import specifier being resolved + * start - lookup path + * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"` + +* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving. +This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag. +**Note:** this property is currently `true` by default but it will be changed to +`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*. + +default `opts` values: + +```js +{ + paths: [], + basedir: __dirname, + extensions: ['.js'], + includeCoreModules: true, + readFileSync: fs.readFileSync, + isFile: function isFile(file) { + try { + var stat = fs.statSync(file); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isFile() || stat.isFIFO(); + }, + isDirectory: function isDirectory(dir) { + try { + var stat = fs.statSync(dir); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isDirectory(); + }, + realpathSync: function realpathSync(file) { + try { + var realpath = typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; + return realpath(file); + } catch (realPathErr) { + if (realPathErr.code !== 'ENOENT') { + throw realPathErr; + } + } + return file; + }, + readPackageSync: function defaultReadPackageSync(readFileSync, pkgfile) { + var body = readFileSync(pkgfile); + try { + var pkg = JSON.parse(body); + return pkg; + } catch (jsonErr) {} + }, + moduleDirectory: 'node_modules', + preserveSymlinks: true +} +``` + +# install + +With [npm](https://npmjs.org) do: + +```sh +npm install resolve +``` + +# license + +MIT diff --git a/node_modules/resolve/test/.eslintrc b/node_modules/resolve/test/.eslintrc new file mode 100644 index 0000000..ddd262d --- /dev/null +++ b/node_modules/resolve/test/.eslintrc @@ -0,0 +1,5 @@ +{ + "rules": { + "max-lines": 0 + } +} diff --git a/node_modules/resolve/test/core.js b/node_modules/resolve/test/core.js new file mode 100644 index 0000000..7a3ccb1 --- /dev/null +++ b/node_modules/resolve/test/core.js @@ -0,0 +1,81 @@ +var test = require('tape'); +var keys = require('object-keys'); +var resolve = require('../'); + +test('core modules', function (t) { + t.test('isCore()', function (st) { + st.ok(resolve.isCore('fs')); + st.ok(resolve.isCore('net')); + st.ok(resolve.isCore('http')); + + st.ok(!resolve.isCore('seq')); + st.ok(!resolve.isCore('../')); + + st.ok(!resolve.isCore('toString')); + + st.end(); + }); + + t.test('core list', function (st) { + var cores = keys(resolve.core); + st.plan(cores.length); + + for (var i = 0; i < cores.length; ++i) { + var mod = cores[i]; + var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func + console.log(mod, resolve.core, resolve.core[mod]); + if (resolve.core[mod]) { + st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw'); + } else { + st.throws(requireFunc, mod + ' not supported; requiring throws'); + } + } + + st.end(); + }); + + t.test('core via repl module', { skip: !resolve.core.repl }, function (st) { + var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle + if (!libs) { + st.skip('module.builtinModules does not exist'); + return st.end(); + } + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + st.ok(resolve.core[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + } + st.end(); + }); + + t.test('core via builtinModules list', { skip: !resolve.core.module }, function (st) { + var libs = require('module').builtinModules; + if (!libs) { + st.skip('module.builtinModules does not exist'); + return st.end(); + } + var blacklist = [ + '_debug_agent', + 'v8/tools/tickprocessor-driver', + 'v8/tools/SourceMap', + 'v8/tools/tickprocessor', + 'v8/tools/profile' + ]; + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + if (blacklist.indexOf(mod) === -1) { + st.ok(resolve.core[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + } + } + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/resolve/test/dotdot.js b/node_modules/resolve/test/dotdot.js new file mode 100644 index 0000000..3080665 --- /dev/null +++ b/node_modules/resolve/test/dotdot.js @@ -0,0 +1,29 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('dotdot', function (t) { + t.plan(4); + var dir = path.join(__dirname, '/dotdot/abc'); + + resolve('..', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'dotdot/index.js')); + }); + + resolve('.', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('dotdot sync', function (t) { + t.plan(2); + var dir = path.join(__dirname, '/dotdot/abc'); + + var a = resolve.sync('..', { basedir: dir }); + t.equal(a, path.join(__dirname, 'dotdot/index.js')); + + var b = resolve.sync('.', { basedir: dir }); + t.equal(b, path.join(dir, 'index.js')); +}); diff --git a/node_modules/resolve/test/dotdot/abc/index.js b/node_modules/resolve/test/dotdot/abc/index.js new file mode 100644 index 0000000..67f2534 --- /dev/null +++ b/node_modules/resolve/test/dotdot/abc/index.js @@ -0,0 +1,2 @@ +var x = require('..'); +console.log(x); diff --git a/node_modules/resolve/test/dotdot/index.js b/node_modules/resolve/test/dotdot/index.js new file mode 100644 index 0000000..643f9fc --- /dev/null +++ b/node_modules/resolve/test/dotdot/index.js @@ -0,0 +1 @@ +module.exports = 'whatever'; diff --git a/node_modules/resolve/test/faulty_basedir.js b/node_modules/resolve/test/faulty_basedir.js new file mode 100644 index 0000000..5f2141a --- /dev/null +++ b/node_modules/resolve/test/faulty_basedir.js @@ -0,0 +1,29 @@ +var test = require('tape'); +var path = require('path'); +var resolve = require('../'); + +test('faulty basedir must produce error in windows', { skip: process.platform !== 'win32' }, function (t) { + t.plan(1); + + var resolverDir = 'C:\\a\\b\\c\\d'; + + resolve('tape/lib/test.js', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(!!err, true); + }); +}); + +test('non-existent basedir should not throw when preserveSymlinks is false', function (t) { + t.plan(2); + + var opts = { + basedir: path.join(path.sep, 'unreal', 'path', 'that', 'does', 'not', 'exist'), + preserveSymlinks: false + }; + + var module = './dotdot/abc'; + + resolve(module, opts, function (err, res) { + t.equal(err.code, 'MODULE_NOT_FOUND'); + t.equal(res, undefined); + }); +}); diff --git a/node_modules/resolve/test/filter.js b/node_modules/resolve/test/filter.js new file mode 100644 index 0000000..8f8cccd --- /dev/null +++ b/node_modules/resolve/test/filter.js @@ -0,0 +1,34 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('filter', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + var packageFilterArgs; + resolve('./baz', { + basedir: dir, + packageFilter: function (pkg, pkgfile) { + pkg.main = 'doom'; // eslint-disable-line no-param-reassign + packageFilterArgs = [pkg, pkgfile]; + return pkg; + } + }, function (err, res, pkg) { + if (err) t.fail(err); + + t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works'); + + var packageData = packageFilterArgs[0]; + t.equal(pkg, packageData, 'first packageFilter argument is "pkg"'); + t.equal(packageData.main, 'doom', 'package "main" was altered'); + + var packageFile = packageFilterArgs[1]; + t.equal( + packageFile, + path.join(dir, 'baz/package.json'), + 'second packageFilter argument is "pkgfile"' + ); + + t.end(); + }); +}); diff --git a/node_modules/resolve/test/filter_sync.js b/node_modules/resolve/test/filter_sync.js new file mode 100644 index 0000000..8a43b98 --- /dev/null +++ b/node_modules/resolve/test/filter_sync.js @@ -0,0 +1,33 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('filter', function (t) { + var dir = path.join(__dirname, 'resolver'); + var packageFilterArgs; + var res = resolve.sync('./baz', { + basedir: dir, + // NOTE: in v2.x, this will be `pkg, pkgfile, dir`, but must remain "broken" here in v1.x for compatibility + packageFilter: function (pkg, /*pkgfile,*/ dir) { // eslint-disable-line spaced-comment + pkg.main = 'doom'; // eslint-disable-line no-param-reassign + packageFilterArgs = 'is 1.x' ? [pkg, dir] : [pkg, pkgfile, dir]; // eslint-disable-line no-constant-condition, no-undef + return pkg; + } + }); + + t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works'); + + var packageData = packageFilterArgs[0]; + t.equal(packageData.main, 'doom', 'package "main" was altered'); + + if (!'is 1.x') { // eslint-disable-line no-constant-condition + var packageFile = packageFilterArgs[1]; + t.equal(packageFile, path.join(dir, 'baz', 'package.json'), 'package.json path is correct'); + } + + var packageDir = packageFilterArgs['is 1.x' ? 1 : 2]; // eslint-disable-line no-constant-condition + // eslint-disable-next-line no-constant-condition + t.equal(packageDir, path.join(dir, 'baz'), ('is 1.x' ? 'second' : 'third') + ' packageFilter argument is "dir"'); + + t.end(); +}); diff --git a/node_modules/resolve/test/mock.js b/node_modules/resolve/test/mock.js new file mode 100644 index 0000000..6116275 --- /dev/null +++ b/node_modules/resolve/test/mock.js @@ -0,0 +1,315 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('mock', function (t) { + t.plan(8); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('../baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('mock from package', function (t) { + t.plan(8); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, file)); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[file]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg && pkg.main, 'bar'); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg && pkg.main, 'bar'); + }); + + resolve('baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('../baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('mock package', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('bar', opts('/foo'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + t.equal(pkg && pkg.main, './baz.js'); + }); +}); + +test('mock package from package', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('bar', opts('/foo'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + t.equal(pkg && pkg.main, './baz.js'); + }); +}); + +test('symlinked', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + dirs[path.resolve('/foo/bar/symlinked')] = true; + + function opts(basedir) { + return { + preserveSymlinks: false, + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + var resolved = path.resolve(file); + + if (resolved.indexOf('symlinked') >= 0) { + cb(null, resolved); + return; + } + + var ext = path.extname(resolved); + + if (ext) { + var dir = path.dirname(resolved); + var base = path.basename(resolved); + cb(null, path.join(dir, 'symlinked', base)); + } else { + cb(null, path.join(resolved, 'symlinked')); + } + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/symlinked/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/symlinked/baz.js')); + t.equal(pkg, undefined); + }); +}); + +test('readPackage', function (t) { + t.plan(3); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop'; + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + t.test('with readFile', function (st) { + st.plan(3); + + resolve('bar', opts('/foo'), function (err, res, pkg) { + st.error(err); + st.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + st.equal(pkg && pkg.main, './baz.js'); + }); + }); + + var readPackage = function (readFile, file, cb) { + var barPackage = path.join('bar', 'package.json'); + if (file.slice(-barPackage.length) === barPackage) { + cb(null, { main: './something-else.js' }); + } else { + cb(null, JSON.parse(files[path.resolve(file)])); + } + }; + + t.test('with readPackage', function (st) { + st.plan(3); + + var options = opts('/foo'); + delete options.readFile; + options.readPackage = readPackage; + resolve('bar', options, function (err, res, pkg) { + st.error(err); + st.equal(res, path.resolve('/foo/node_modules/bar/something-else.js')); + st.equal(pkg && pkg.main, './something-else.js'); + }); + }); + + t.test('with readFile and readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + options.readPackage = readPackage; + resolve('bar', options, function (err) { + st.throws(function () { throw err; }, TypeError, 'errors when both readFile and readPackage are provided'); + }); + }); +}); diff --git a/node_modules/resolve/test/mock_sync.js b/node_modules/resolve/test/mock_sync.js new file mode 100644 index 0000000..0e3a60d --- /dev/null +++ b/node_modules/resolve/test/mock_sync.js @@ -0,0 +1,216 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('mock', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + + t.equal( + resolve.sync('./baz', opts('/foo/bar')), + path.resolve('/foo/bar/baz.js') + ); + + t.equal( + resolve.sync('./baz.js', opts('/foo/bar')), + path.resolve('/foo/bar/baz.js') + ); + + t.throws(function () { + resolve.sync('baz', opts('/foo/bar')); + }); + + t.throws(function () { + resolve.sync('../baz', opts('/foo/bar')); + }); +}); + +test('mock package', function (t) { + t.plan(1); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + + t.equal( + resolve.sync('bar', opts('/foo')), + path.resolve('/foo/node_modules/bar/baz.js') + ); +}); + +test('symlinked', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + dirs[path.resolve('/foo/bar/symlinked')] = true; + + function opts(basedir) { + return { + preserveSymlinks: false, + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + var resolved = path.resolve(file); + + if (resolved.indexOf('symlinked') >= 0) { + return resolved; + } + + var ext = path.extname(resolved); + + if (ext) { + var dir = path.dirname(resolved); + var base = path.basename(resolved); + return path.join(dir, 'symlinked', base); + } else { + return path.join(resolved, 'symlinked'); + } + } + }; + } + + t.equal( + resolve.sync('./baz', opts('/foo/bar')), + path.resolve('/foo/bar/symlinked/baz.js') + ); + + t.equal( + resolve.sync('./baz.js', opts('/foo/bar')), + path.resolve('/foo/bar/symlinked/baz.js') + ); +}); + +test('readPackageSync', function (t) { + t.plan(3); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop'; + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir, useReadPackage) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: useReadPackage ? null : function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + t.test('with readFile', function (st) { + st.plan(1); + + st.equal( + resolve.sync('bar', opts('/foo')), + path.resolve('/foo/node_modules/bar/baz.js') + ); + }); + + var readPackageSync = function (readFileSync, file) { + if (file.indexOf(path.join('bar', 'package.json')) >= 0) { + return { main: './something-else.js' }; + } else { + return JSON.parse(files[path.resolve(file)]); + } + }; + + t.test('with readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + delete options.readFileSync; + options.readPackageSync = readPackageSync; + + st.equal( + resolve.sync('bar', options), + path.resolve('/foo/node_modules/bar/something-else.js') + ); + }); + + t.test('with readFile and readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + options.readPackageSync = readPackageSync; + st.throws( + function () { resolve.sync('bar', options); }, + TypeError, + 'errors when both readFile and readPackage are provided' + ); + }); +}); + diff --git a/node_modules/resolve/test/module_dir.js b/node_modules/resolve/test/module_dir.js new file mode 100644 index 0000000..b50e5bb --- /dev/null +++ b/node_modules/resolve/test/module_dir.js @@ -0,0 +1,56 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('moduleDirectory strings', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'module_dir'); + var xopts = { + basedir: dir, + moduleDirectory: 'xmodules' + }; + resolve('aaa', xopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/xmodules/aaa/index.js')); + }); + + var yopts = { + basedir: dir, + moduleDirectory: 'ymodules' + }; + resolve('aaa', yopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/ymodules/aaa/index.js')); + }); +}); + +test('moduleDirectory array', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'module_dir'); + var aopts = { + basedir: dir, + moduleDirectory: ['xmodules', 'ymodules', 'zmodules'] + }; + resolve('aaa', aopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/xmodules/aaa/index.js')); + }); + + var bopts = { + basedir: dir, + moduleDirectory: ['zmodules', 'ymodules', 'xmodules'] + }; + resolve('aaa', bopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/ymodules/aaa/index.js')); + }); + + var copts = { + basedir: dir, + moduleDirectory: ['xmodules', 'ymodules', 'zmodules'] + }; + resolve('bbb', copts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/zmodules/bbb/main.js')); + }); +}); diff --git a/node_modules/resolve/test/module_dir/xmodules/aaa/index.js b/node_modules/resolve/test/module_dir/xmodules/aaa/index.js new file mode 100644 index 0000000..dd7cf7b --- /dev/null +++ b/node_modules/resolve/test/module_dir/xmodules/aaa/index.js @@ -0,0 +1 @@ +module.exports = function (x) { return x * 100; }; diff --git a/node_modules/resolve/test/module_dir/ymodules/aaa/index.js b/node_modules/resolve/test/module_dir/ymodules/aaa/index.js new file mode 100644 index 0000000..ef2d4d4 --- /dev/null +++ b/node_modules/resolve/test/module_dir/ymodules/aaa/index.js @@ -0,0 +1 @@ +module.exports = function (x) { return x + 100; }; diff --git a/node_modules/resolve/test/module_dir/zmodules/bbb/main.js b/node_modules/resolve/test/module_dir/zmodules/bbb/main.js new file mode 100644 index 0000000..e8ba629 --- /dev/null +++ b/node_modules/resolve/test/module_dir/zmodules/bbb/main.js @@ -0,0 +1 @@ +module.exports = function (n) { return n * 111; }; diff --git a/node_modules/resolve/test/module_dir/zmodules/bbb/package.json b/node_modules/resolve/test/module_dir/zmodules/bbb/package.json new file mode 100644 index 0000000..c13b8cf --- /dev/null +++ b/node_modules/resolve/test/module_dir/zmodules/bbb/package.json @@ -0,0 +1,3 @@ +{ + "main": "main.js" +} diff --git a/node_modules/resolve/test/node-modules-paths.js b/node_modules/resolve/test/node-modules-paths.js new file mode 100644 index 0000000..675441d --- /dev/null +++ b/node_modules/resolve/test/node-modules-paths.js @@ -0,0 +1,143 @@ +var test = require('tape'); +var path = require('path'); +var parse = path.parse || require('path-parse'); +var keys = require('object-keys'); + +var nodeModulesPaths = require('../lib/node-modules-paths'); + +var verifyDirs = function verifyDirs(t, start, dirs, moduleDirectories, paths) { + var moduleDirs = [].concat(moduleDirectories || 'node_modules'); + if (paths) { + for (var k = 0; k < paths.length; ++k) { + moduleDirs.push(path.basename(paths[k])); + } + } + + var foundModuleDirs = {}; + var uniqueDirs = {}; + var parsedDirs = {}; + for (var i = 0; i < dirs.length; ++i) { + var parsed = parse(dirs[i]); + if (!foundModuleDirs[parsed.base]) { foundModuleDirs[parsed.base] = 0; } + foundModuleDirs[parsed.base] += 1; + parsedDirs[parsed.dir] = true; + uniqueDirs[dirs[i]] = true; + } + t.equal(keys(parsedDirs).length >= start.split(path.sep).length, true, 'there are >= dirs than "start" has'); + var foundModuleDirNames = keys(foundModuleDirs); + t.deepEqual(foundModuleDirNames, moduleDirs, 'all desired module dirs were found'); + t.equal(keys(uniqueDirs).length, dirs.length, 'all dirs provided were unique'); + + var counts = {}; + for (var j = 0; j < foundModuleDirNames.length; ++j) { + counts[foundModuleDirs[j]] = true; + } + t.equal(keys(counts).length, 1, 'all found module directories had the same count'); +}; + +test('node-modules-paths', function (t) { + t.test('no options', function (t) { + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start); + + verifyDirs(t, start, dirs); + + t.end(); + }); + + t.test('empty options', function (t) { + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, {}); + + verifyDirs(t, start, dirs); + + t.end(); + }); + + t.test('with paths=array option', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var dirs = nodeModulesPaths(start, { paths: paths }); + + verifyDirs(t, start, dirs, null, paths); + + t.end(); + }); + + t.test('with paths=function option', function (t) { + var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) { + return getNodeModulesDirs().concat(path.join(absoluteStart, 'not node modules', request)); + }; + + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, { paths: paths }, 'pkg'); + + verifyDirs(t, start, dirs, null, [path.join(start, 'not node modules', 'pkg')]); + + t.end(); + }); + + t.test('with paths=function skipping node modules resolution', function (t) { + var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) { + return []; + }; + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, { paths: paths }); + t.deepEqual(dirs, [], 'no node_modules was computed'); + t.end(); + }); + + t.test('with moduleDirectory option', function (t) { + var start = path.join(__dirname, 'resolver'); + var moduleDirectory = 'not node modules'; + var dirs = nodeModulesPaths(start, { moduleDirectory: moduleDirectory }); + + verifyDirs(t, start, dirs, moduleDirectory); + + t.end(); + }); + + t.test('with 1 moduleDirectory and paths options', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var moduleDirectory = 'not node modules'; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectory }); + + verifyDirs(t, start, dirs, moduleDirectory, paths); + + t.end(); + }); + + t.test('with 1+ moduleDirectory and paths options', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var moduleDirectories = ['not node modules', 'other modules']; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + verifyDirs(t, start, dirs, moduleDirectories, paths); + + t.end(); + }); + + t.test('combine paths correctly on Windows', function (t) { + var start = 'C:\\Users\\username\\myProject\\src'; + var paths = []; + var moduleDirectories = ['node_modules', start]; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir'); + + t.end(); + }); + + t.test('combine paths correctly on non-Windows', { skip: process.platform === 'win32' }, function (t) { + var start = '/Users/username/git/myProject/src'; + var paths = []; + var moduleDirectories = ['node_modules', '/Users/username/git/myProject/src']; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir'); + + t.end(); + }); +}); diff --git a/node_modules/resolve/test/node_path.js b/node_modules/resolve/test/node_path.js new file mode 100644 index 0000000..d06aa4e --- /dev/null +++ b/node_modules/resolve/test/node_path.js @@ -0,0 +1,70 @@ +var fs = require('fs'); +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('$NODE_PATH', function (t) { + t.plan(8); + + var isDir = function (dir, cb) { + if (dir === '/node_path' || dir === 'node_path/x') { + return cb(null, true); + } + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }; + + resolve('aaa', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/x/aaa/index.js'), 'aaa resolves'); + }); + + resolve('bbb', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/y/bbb/index.js'), 'bbb resolves'); + }); + + resolve('ccc', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/x/ccc/index.js'), 'ccc resolves'); + }); + + // ensure that relative paths still resolve against the regular `node_modules` correctly + resolve('tap', { + paths: [ + 'node_path' + ], + basedir: path.join(__dirname, 'node_path/x'), + isDirectory: isDir + }, function (err, res) { + var root = require('tap/package.json').main; + t.error(err); + t.equal(res, path.resolve(__dirname, '..', 'node_modules/tap', root), 'tap resolves'); + }); +}); diff --git a/node_modules/resolve/test/node_path/x/aaa/index.js b/node_modules/resolve/test/node_path/x/aaa/index.js new file mode 100644 index 0000000..ad70d0b --- /dev/null +++ b/node_modules/resolve/test/node_path/x/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'A'; diff --git a/node_modules/resolve/test/node_path/x/ccc/index.js b/node_modules/resolve/test/node_path/x/ccc/index.js new file mode 100644 index 0000000..a64132e --- /dev/null +++ b/node_modules/resolve/test/node_path/x/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'C'; diff --git a/node_modules/resolve/test/node_path/y/bbb/index.js b/node_modules/resolve/test/node_path/y/bbb/index.js new file mode 100644 index 0000000..4d0f32e --- /dev/null +++ b/node_modules/resolve/test/node_path/y/bbb/index.js @@ -0,0 +1 @@ +module.exports = 'B'; diff --git a/node_modules/resolve/test/node_path/y/ccc/index.js b/node_modules/resolve/test/node_path/y/ccc/index.js new file mode 100644 index 0000000..793315e --- /dev/null +++ b/node_modules/resolve/test/node_path/y/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'CY'; diff --git a/node_modules/resolve/test/nonstring.js b/node_modules/resolve/test/nonstring.js new file mode 100644 index 0000000..ef63c40 --- /dev/null +++ b/node_modules/resolve/test/nonstring.js @@ -0,0 +1,9 @@ +var test = require('tape'); +var resolve = require('../'); + +test('nonstring', function (t) { + t.plan(1); + resolve(555, function (err, res, pkg) { + t.ok(err); + }); +}); diff --git a/node_modules/resolve/test/pathfilter.js b/node_modules/resolve/test/pathfilter.js new file mode 100644 index 0000000..16519ae --- /dev/null +++ b/node_modules/resolve/test/pathfilter.js @@ -0,0 +1,75 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +var resolverDir = path.join(__dirname, '/pathfilter/deep_ref'); + +var pathFilterFactory = function (t) { + return function (pkg, x, remainder) { + t.equal(pkg.version, '1.2.3'); + t.equal(x, path.join(resolverDir, 'node_modules/deep/ref')); + t.equal(remainder, 'ref'); + return 'alt'; + }; +}; + +test('#62: deep module references and the pathFilter', function (t) { + t.test('deep/ref.js', function (st) { + st.plan(3); + + resolve('deep/ref', { basedir: resolverDir }, function (err, res, pkg) { + if (err) st.fail(err); + + st.equal(pkg.version, '1.2.3'); + st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js')); + }); + + var res = resolve.sync('deep/ref', { basedir: resolverDir }); + st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js')); + }); + + t.test('deep/deeper/ref', function (st) { + st.plan(4); + + resolve( + 'deep/deeper/ref', + { basedir: resolverDir }, + function (err, res, pkg) { + if (err) t.fail(err); + st.notEqual(pkg, undefined); + st.equal(pkg.version, '1.2.3'); + st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js')); + } + ); + + var res = resolve.sync( + 'deep/deeper/ref', + { basedir: resolverDir } + ); + st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js')); + }); + + t.test('deep/ref alt', function (st) { + st.plan(8); + + var pathFilter = pathFilterFactory(st); + + var res = resolve.sync( + 'deep/ref', + { basedir: resolverDir, pathFilter: pathFilter } + ); + st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js')); + + resolve( + 'deep/ref', + { basedir: resolverDir, pathFilter: pathFilter }, + function (err, res, pkg) { + if (err) st.fail(err); + st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js')); + st.end(); + } + ); + }); + + t.end(); +}); diff --git a/node_modules/resolve/test/pathfilter/deep_ref/main.js b/node_modules/resolve/test/pathfilter/deep_ref/main.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/precedence.js b/node_modules/resolve/test/precedence.js new file mode 100644 index 0000000..2febb59 --- /dev/null +++ b/node_modules/resolve/test/precedence.js @@ -0,0 +1,23 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('precedence', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'precedence/aaa'); + + resolve('./', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg.name, 'resolve'); + }); +}); + +test('./ should not load ${dir}.js', function (t) { // eslint-disable-line no-template-curly-in-string + t.plan(1); + var dir = path.join(__dirname, 'precedence/bbb'); + + resolve('./', { basedir: dir }, function (err, res, pkg) { + t.ok(err); + }); +}); diff --git a/node_modules/resolve/test/precedence/aaa.js b/node_modules/resolve/test/precedence/aaa.js new file mode 100644 index 0000000..b83a3e7 --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa.js @@ -0,0 +1 @@ +module.exports = 'wtf'; diff --git a/node_modules/resolve/test/precedence/aaa/index.js b/node_modules/resolve/test/precedence/aaa/index.js new file mode 100644 index 0000000..e0f8f6a --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'okok'; diff --git a/node_modules/resolve/test/precedence/aaa/main.js b/node_modules/resolve/test/precedence/aaa/main.js new file mode 100644 index 0000000..93542a9 --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa/main.js @@ -0,0 +1 @@ +console.log(require('./')); diff --git a/node_modules/resolve/test/precedence/bbb.js b/node_modules/resolve/test/precedence/bbb.js new file mode 100644 index 0000000..2298f47 --- /dev/null +++ b/node_modules/resolve/test/precedence/bbb.js @@ -0,0 +1 @@ +module.exports = '>_<'; diff --git a/node_modules/resolve/test/precedence/bbb/main.js b/node_modules/resolve/test/precedence/bbb/main.js new file mode 100644 index 0000000..716b81d --- /dev/null +++ b/node_modules/resolve/test/precedence/bbb/main.js @@ -0,0 +1 @@ +console.log(require('./')); // should throw diff --git a/node_modules/resolve/test/resolver.js b/node_modules/resolve/test/resolver.js new file mode 100644 index 0000000..aa36ee1 --- /dev/null +++ b/node_modules/resolve/test/resolver.js @@ -0,0 +1,450 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('async foo', function (t) { + t.plan(12); + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo.js', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.main, 'resolver'); + }); + + resolve('./foo.js', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg.main, 'resolver'); + }); + + resolve('./foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + }); + + resolve('foo', { basedir: dir }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.join(dir, 'baz.js') + "'"); + }); +}); + +test('bar', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'resolver'); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar', 'package': { main: 'bar' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg.main, 'bar'); + }); +}); + +test('baz', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + + resolve('./baz', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); + + resolve('./baz', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); +}); + +test('biz', function (t) { + t.plan(24); + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + resolve('./grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('./grux', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'biz'); + }); + + resolve('./garply', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('./garply', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('tiv', { basedir: dir + '/grux' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/grux', 'package': { main: 'grux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, 'grux'); + }); + + resolve('tiv', { basedir: dir + '/garply' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/garply', 'package': { main: './lib' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('grux', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('grux', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'tiv'); + }); + + resolve('garply', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('garply', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); +}); + +test('quux', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/quux'); + + resolve('./foo', { basedir: dir, 'package': { main: 'quux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo/index.js')); + t.equal(pkg.main, 'quux'); + }); +}); + +test('normalize', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + resolve('../grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg, undefined); + }); +}); + +test('cup', function (t) { + t.plan(5); + var dir = path.join(__dirname, 'resolver'); + + resolve('./cup', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup.coffee', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup', { basedir: dir, extensions: ['.js'] }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('./cup', { basedir: dir, extensions: ['.js'], filename: path.join(dir, 'cupboard.js') }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.join(dir, 'cupboard.js') + "'"); + }); +}); + +test('mug', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'resolver'); + + resolve('./mug', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'mug.js')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.coffee', '.js'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, '/mug.coffee')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + t.equal(res, path.join(dir, '/mug.js')); + }); +}); + +test('other path', function (t) { + t.plan(6); + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + resolve('root', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/root.js')); + }); + + resolve('lib/other-lib', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/lib/other-lib.js')); + }); + + resolve('root', { basedir: dir }, function (err, res) { + t.equal(err.message, "Cannot find module 'root' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('zzz', { basedir: dir, paths: [otherDir] }, function (err, res) { + t.equal(err.message, "Cannot find module 'zzz' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('path iterator', function (t) { + t.plan(2); + + var resolverDir = path.join(__dirname, 'resolver'); + + var exactIterator = function (x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + }; + + resolve('baz', { packageIterator: exactIterator }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'baz/quux.js')); + t.equal(pkg && pkg.name, 'baz'); + }); +}); + +test('incorrect main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + resolve('./incorrect_main', { basedir: resolverDir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('without basedir', function (t) { + t.plan(1); + + var dir = path.join(__dirname, 'resolver/without_basedir'); + var tester = require(path.join(dir, 'main.js')); + + tester(t, function (err, res, pkg) { + if (err) { + t.fail(err); + } else { + t.equal(res, path.join(dir, 'node_modules/mymodule.js')); + } + }); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo.js')); + }); + + resolve('./foo/', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); + + resolve('.', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('async: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.plan(1); + resolve('./' + testFile, function (err, res, pkg) { + if (err) t.fail(err); + st.equal(res, __filename, 'sanity check'); + }); + }); + + t.test('with a fake directory', function (st) { + st.plan(4); + + resolve('./' + testFile + '/blah', function (err, res, pkg) { + st.ok(err, 'there is an error'); + st.notOk(res, 'no result'); + + st.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + err && err.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + st.end(); + }); + }); + + t.end(); +}); + +test('async dot main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('async dot slash main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_slash_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_slash_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('not a directory', function (t) { + t.plan(6); + var path = './foo'; + resolve(path, { basedir: __filename }, function (err, res, pkg) { + t.ok(err, 'a non-directory errors'); + t.equal(arguments.length, 1); + t.equal(res, undefined); + t.equal(pkg, undefined); + + t.equal(err && err.message, 'Cannot find module \'' + path + '\' from \'' + __filename + '\''); + t.equal(err && err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('browser field in package.json', function (t) { + t.plan(3); + + var dir = path.join(__dirname, 'resolver'); + resolve( + './browser_field', + { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }, + function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.equal(pkg && pkg.main, 'b'); + t.equal(pkg && pkg.browser, undefined); + } + ); +}); diff --git a/node_modules/resolve/test/resolver/baz/doom.js b/node_modules/resolve/test/resolver/baz/doom.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/baz/package.json b/node_modules/resolve/test/resolver/baz/package.json new file mode 100644 index 0000000..2f77720 --- /dev/null +++ b/node_modules/resolve/test/resolver/baz/package.json @@ -0,0 +1,4 @@ +{ + "name": "baz", + "main": "quux.js" +} diff --git a/node_modules/resolve/test/resolver/baz/quux.js b/node_modules/resolve/test/resolver/baz/quux.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/baz/quux.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/browser_field/a.js b/node_modules/resolve/test/resolver/browser_field/a.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/browser_field/b.js b/node_modules/resolve/test/resolver/browser_field/b.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/browser_field/package.json b/node_modules/resolve/test/resolver/browser_field/package.json new file mode 100644 index 0000000..bf406f0 --- /dev/null +++ b/node_modules/resolve/test/resolver/browser_field/package.json @@ -0,0 +1,5 @@ +{ + "name": "browser_field", + "main": "a", + "browser": "b" +} diff --git a/node_modules/resolve/test/resolver/cup.coffee b/node_modules/resolve/test/resolver/cup.coffee new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/node_modules/resolve/test/resolver/cup.coffee @@ -0,0 +1 @@ + diff --git a/node_modules/resolve/test/resolver/dot_main/index.js b/node_modules/resolve/test/resolver/dot_main/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_main/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/dot_main/package.json b/node_modules/resolve/test/resolver/dot_main/package.json new file mode 100644 index 0000000..d7f4fc8 --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "." +} diff --git a/node_modules/resolve/test/resolver/dot_slash_main/index.js b/node_modules/resolve/test/resolver/dot_slash_main/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_slash_main/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/dot_slash_main/package.json b/node_modules/resolve/test/resolver/dot_slash_main/package.json new file mode 100644 index 0000000..f51287b --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_slash_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "./" +} diff --git a/node_modules/resolve/test/resolver/foo.js b/node_modules/resolve/test/resolver/foo.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/foo.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/incorrect_main/index.js b/node_modules/resolve/test/resolver/incorrect_main/index.js new file mode 100644 index 0000000..bc1fb0a --- /dev/null +++ b/node_modules/resolve/test/resolver/incorrect_main/index.js @@ -0,0 +1,2 @@ +// this is the actual main file 'index.js', not 'wrong.js' like the package.json would indicate +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/incorrect_main/package.json b/node_modules/resolve/test/resolver/incorrect_main/package.json new file mode 100644 index 0000000..b718804 --- /dev/null +++ b/node_modules/resolve/test/resolver/incorrect_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "wrong.js" +} diff --git a/node_modules/resolve/test/resolver/invalid_main/package.json b/node_modules/resolve/test/resolver/invalid_main/package.json new file mode 100644 index 0000000..0cf8279 --- /dev/null +++ b/node_modules/resolve/test/resolver/invalid_main/package.json @@ -0,0 +1,7 @@ +{ + "name": "invalid main", + "main": [ + "why is this a thing", + "srsly omg wtf" + ] +} diff --git a/node_modules/resolve/test/resolver/mug.coffee b/node_modules/resolve/test/resolver/mug.coffee new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/mug.js b/node_modules/resolve/test/resolver/mug.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/multirepo/lerna.json b/node_modules/resolve/test/resolver/multirepo/lerna.json new file mode 100644 index 0000000..d6707ca --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/lerna.json @@ -0,0 +1,6 @@ +{ + "packages": [ + "packages/*" + ], + "version": "0.0.0" +} diff --git a/node_modules/resolve/test/resolver/multirepo/package.json b/node_modules/resolve/test/resolver/multirepo/package.json new file mode 100644 index 0000000..8508f9d --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/package.json @@ -0,0 +1,20 @@ +{ + "name": "monorepo-symlink-test", + "private": true, + "version": "0.0.0", + "description": "", + "main": "index.js", + "scripts": { + "postinstall": "lerna bootstrap", + "test": "node packages/package-a" + }, + "author": "", + "license": "MIT", + "dependencies": { + "jquery": "^3.3.1", + "resolve": "../../../" + }, + "devDependencies": { + "lerna": "^3.4.3" + } +} diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js b/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js new file mode 100644 index 0000000..8875a32 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var assert = require('assert'); +var path = require('path'); +var resolve = require('resolve'); + +var basedir = __dirname + '/node_modules/@my-scope/package-b'; + +var expected = path.join(__dirname, '../../node_modules/jquery/dist/jquery.js'); + +/* + * preserveSymlinks === false + * will search NPM package from + * - packages/package-b/node_modules + * - packages/node_modules + * - node_modules + */ +assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: false }), expected); +assert.equal(resolve.sync('../../node_modules/jquery', { basedir: basedir, preserveSymlinks: false }), expected); + +/* + * preserveSymlinks === true + * will search NPM package from + * - packages/package-a/node_modules/@my-scope/packages/package-b/node_modules + * - packages/package-a/node_modules/@my-scope/packages/node_modules + * - packages/package-a/node_modules/@my-scope/node_modules + * - packages/package-a/node_modules/node_modules + * - packages/package-a/node_modules + * - packages/node_modules + * - node_modules + */ +assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: true }), expected); +assert.equal(resolve.sync('../../../../../node_modules/jquery', { basedir: basedir, preserveSymlinks: true }), expected); + +console.log(' * all monorepo paths successfully resolved through symlinks'); diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json b/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json new file mode 100644 index 0000000..204de51 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json @@ -0,0 +1,14 @@ +{ + "name": "@my-scope/package-a", + "version": "0.0.0", + "private": true, + "description": "", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "echo \"Error: run tests from root\" && exit 1" + }, + "dependencies": { + "@my-scope/package-b": "^0.0.0" + } +} diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-b/index.js b/node_modules/resolve/test/resolver/multirepo/packages/package-b/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json b/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json new file mode 100644 index 0000000..f57c3b5 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json @@ -0,0 +1,14 @@ +{ + "name": "@my-scope/package-b", + "private": true, + "version": "0.0.0", + "description": "", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "echo \"Error: run tests from root\" && exit 1" + }, + "dependencies": { + "@my-scope/package-a": "^0.0.0" + } +} diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js b/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js new file mode 100644 index 0000000..9b4846a --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js @@ -0,0 +1,26 @@ +var a = require.resolve('buffer/').replace(process.cwd(), '$CWD'); +var b; +var c; + +var test = function test() { + console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false')); + console.log(b, ': preserveSymlinks true'); + console.log(c, ': preserveSymlinks false'); + + if (a !== b && a !== c) { + throw 'async: no match'; + } + console.log('async: success! a matched either b or c\n'); +}; + +require('resolve')('buffer/', { preserveSymlinks: true }, function (err, result) { + if (err) { throw err; } + b = result.replace(process.cwd(), '$CWD'); + if (b && c) { test(); } +}); +require('resolve')('buffer/', { preserveSymlinks: false }, function (err, result) { + if (err) { throw err; } + c = result.replace(process.cwd(), '$CWD'); + if (b && c) { test(); } +}); + diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json b/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json new file mode 100644 index 0000000..acfe9e9 --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json @@ -0,0 +1,15 @@ +{ + "name": "mylib", + "version": "0.0.0", + "description": "", + "private": true, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "buffer": "*" + } +} diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js b/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js new file mode 100644 index 0000000..3283efc --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js @@ -0,0 +1,12 @@ +var a = require.resolve('buffer/').replace(process.cwd(), '$CWD'); +var b = require('resolve').sync('buffer/', { preserveSymlinks: true }).replace(process.cwd(), '$CWD'); +var c = require('resolve').sync('buffer/', { preserveSymlinks: false }).replace(process.cwd(), '$CWD'); + +console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false')); +console.log(b, ': preserveSymlinks true'); +console.log(c, ': preserveSymlinks false'); + +if (a !== b && a !== c) { + throw 'sync: no match'; +} +console.log('sync: success! a matched either b or c\n'); diff --git a/node_modules/resolve/test/resolver/other_path/lib/other-lib.js b/node_modules/resolve/test/resolver/other_path/lib/other-lib.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/other_path/root.js b/node_modules/resolve/test/resolver/other_path/root.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/quux/foo/index.js b/node_modules/resolve/test/resolver/quux/foo/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/quux/foo/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/same_names/foo.js b/node_modules/resolve/test/resolver/same_names/foo.js new file mode 100644 index 0000000..888cae3 --- /dev/null +++ b/node_modules/resolve/test/resolver/same_names/foo.js @@ -0,0 +1 @@ +module.exports = 42; diff --git a/node_modules/resolve/test/resolver/same_names/foo/index.js b/node_modules/resolve/test/resolver/same_names/foo/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/same_names/foo/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/symlinked/_/node_modules/foo.js b/node_modules/resolve/test/resolver/symlinked/_/node_modules/foo.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/symlinked/_/symlink_target/.gitkeep b/node_modules/resolve/test/resolver/symlinked/_/symlink_target/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/symlinked/package/bar.js b/node_modules/resolve/test/resolver/symlinked/package/bar.js new file mode 100644 index 0000000..cb1c2c0 --- /dev/null +++ b/node_modules/resolve/test/resolver/symlinked/package/bar.js @@ -0,0 +1 @@ +module.exports = 'bar'; diff --git a/node_modules/resolve/test/resolver/symlinked/package/package.json b/node_modules/resolve/test/resolver/symlinked/package/package.json new file mode 100644 index 0000000..8e1b585 --- /dev/null +++ b/node_modules/resolve/test/resolver/symlinked/package/package.json @@ -0,0 +1,3 @@ +{ + "main": "bar.js" +} \ No newline at end of file diff --git a/node_modules/resolve/test/resolver/without_basedir/main.js b/node_modules/resolve/test/resolver/without_basedir/main.js new file mode 100644 index 0000000..5b31975 --- /dev/null +++ b/node_modules/resolve/test/resolver/without_basedir/main.js @@ -0,0 +1,5 @@ +var resolve = require('../../../'); + +module.exports = function (t, cb) { + resolve('mymodule', null, cb); +}; diff --git a/node_modules/resolve/test/resolver_sync.js b/node_modules/resolve/test/resolver_sync.js new file mode 100644 index 0000000..3082c96 --- /dev/null +++ b/node_modules/resolve/test/resolver_sync.js @@ -0,0 +1,358 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('foo', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./foo', { basedir: dir }), + path.join(dir, 'foo.js') + ); + + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + path.join(dir, 'foo.js') + ); + + t.equal( + resolve.sync('./foo.js', { basedir: dir, filename: path.join(dir, 'bar.js') }), + path.join(dir, 'foo.js') + ); + + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }); + + // Test that filename is reported as the "from" value when passed. + t.throws( + function () { + resolve.sync('foo', { basedir: dir, filename: path.join(dir, 'bar.js') }); + }, + { + name: 'Error', + message: "Cannot find module 'foo' from '" + path.join(dir, 'bar.js') + "'" + } + ); + + t.end(); +}); + +test('bar', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('foo', { basedir: path.join(dir, 'bar') }), + path.join(dir, 'bar/node_modules/foo/index.js') + ); + t.end(); +}); + +test('baz', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./baz', { basedir: dir }), + path.join(dir, 'baz/quux.js') + ); + t.end(); +}); + +test('biz', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + t.equal( + resolve.sync('./grux', { basedir: dir }), + path.join(dir, 'grux/index.js') + ); + + t.equal( + resolve.sync('tiv', { basedir: path.join(dir, 'grux') }), + path.join(dir, 'tiv/index.js') + ); + + t.equal( + resolve.sync('grux', { basedir: path.join(dir, 'tiv') }), + path.join(dir, 'grux/index.js') + ); + t.end(); +}); + +test('normalize', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + t.equal( + resolve.sync('../grux', { basedir: dir }), + path.join(dir, 'index.js') + ); + t.end(); +}); + +test('cup', function (t) { + var dir = path.join(__dirname, 'resolver'); + t.equal( + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'cup.coffee') + ); + + t.equal( + resolve.sync('./cup.coffee', { basedir: dir }), + path.join(dir, 'cup.coffee') + ); + + t.throws(function () { + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js'] + }); + }); + + t.end(); +}); + +test('mug', function (t) { + var dir = path.join(__dirname, 'resolver'); + t.equal( + resolve.sync('./mug', { basedir: dir }), + path.join(dir, 'mug.js') + ); + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.coffee', '.js'] + }), + path.join(dir, 'mug.coffee') + ); + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'mug.js') + ); + + t.end(); +}); + +test('other path', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + t.equal( + resolve.sync('root', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/root.js') + ); + + t.equal( + resolve.sync('lib/other-lib', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/lib/other-lib.js') + ); + + t.throws(function () { + resolve.sync('root', { basedir: dir }); + }); + + t.throws(function () { + resolve.sync('zzz', { + basedir: dir, + paths: [otherDir] + }); + }); + + t.end(); +}); + +test('path iterator', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + var exactIterator = function (x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + }; + + t.equal( + resolve.sync('baz', { packageIterator: exactIterator }), + path.join(resolverDir, 'baz/quux.js') + ); + + t.end(); +}); + +test('incorrect main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + path.join(dir, 'index.js') + ); + + t.end(); +}); + +var stubStatSync = function stubStatSync(fn) { + var fs = require('fs'); + var statSync = fs.statSync; + try { + fs.statSync = function () { + throw new EvalError('Unknown Error'); + }; + return fn(); + } finally { + fs.statSync = statSync; + } +}; + +test('#79 - re-throw non ENOENT errors from stat', function (t) { + var dir = path.join(__dirname, 'resolver'); + + stubStatSync(function () { + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }, /Unknown Error/); + }); + + t.end(); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./foo', { basedir: path.join(dir, 'same_names') }), + path.join(dir, 'same_names/foo.js') + ); + t.equal( + resolve.sync('./foo/', { basedir: path.join(dir, 'same_names') }), + path.join(dir, 'same_names/foo/index.js') + ); + t.end(); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./', { basedir: path.join(dir, 'same_names/foo') }), + path.join(dir, 'same_names/foo/index.js') + ); + t.equal( + resolve.sync('.', { basedir: path.join(dir, 'same_names/foo') }), + path.join(dir, 'same_names/foo/index.js') + ); + t.end(); +}); + +test('sync: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.equal( + resolve.sync('./' + testFile), + __filename, + 'sanity check' + ); + st.end(); + }); + + t.test('with a fake directory', function (st) { + function run() { return resolve.sync('./' + testFile + '/blah'); } + + st.throws(run, 'throws an error'); + + try { + run(); + } catch (e) { + st.equal(e.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + e.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + } + + st.end(); + }); + + t.end(); +}); + +test('sync dot main', function (t) { + var start = new Date(); + t.equal(resolve.sync('./resolver/dot_main'), path.join(__dirname, 'resolver/dot_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); +}); + +test('sync dot slash main', function (t) { + var start = new Date(); + t.equal(resolve.sync('./resolver/dot_slash_main'), path.join(__dirname, 'resolver/dot_slash_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); +}); + +test('not a directory', function (t) { + var path = './foo'; + try { + resolve.sync(path, { basedir: __filename }); + t.fail(); + } catch (err) { + t.ok(err, 'a non-directory errors'); + t.equal(err && err.message, 'Cannot find module \'' + path + "' from '" + __filename + "'"); + t.equal(err && err.code, 'MODULE_NOT_FOUND'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('browser field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + var res = resolve.sync('./browser_field', { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.end(); +}); diff --git a/node_modules/resolve/test/shadowed_core.js b/node_modules/resolve/test/shadowed_core.js new file mode 100644 index 0000000..3a5f4fc --- /dev/null +++ b/node_modules/resolve/test/shadowed_core.js @@ -0,0 +1,54 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('shadowed core modules still return core module', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, 'util'); + }); +}); + +test('shadowed core modules still return core module [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, 'util'); +}); + +test('shadowed core modules return shadow when appending `/`', function (t) { + t.plan(2); + + resolve('util/', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow when appending `/` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util/', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false`', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); diff --git a/node_modules/resolve/test/shadowed_core/node_modules/util/index.js b/node_modules/resolve/test/shadowed_core/node_modules/util/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/subdirs.js b/node_modules/resolve/test/subdirs.js new file mode 100644 index 0000000..b7b8450 --- /dev/null +++ b/node_modules/resolve/test/subdirs.js @@ -0,0 +1,13 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('subdirs', function (t) { + t.plan(2); + + var dir = path.join(__dirname, '/subdirs'); + resolve('a/b/c/x.json', { basedir: dir }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(dir, 'node_modules/a/b/c/x.json')); + }); +}); diff --git a/node_modules/resolve/test/symlinks.js b/node_modules/resolve/test/symlinks.js new file mode 100644 index 0000000..35f881a --- /dev/null +++ b/node_modules/resolve/test/symlinks.js @@ -0,0 +1,176 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); +var map = require('array.prototype.map'); +var resolve = require('../'); + +var symlinkDir = path.join(__dirname, 'resolver', 'symlinked', 'symlink'); +var packageDir = path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'package'); +var modADir = path.join(__dirname, 'symlinks', 'source', 'node_modules', 'mod-a'); +var symlinkModADir = path.join(__dirname, 'symlinks', 'dest', 'node_modules', 'mod-a'); +try { + fs.unlinkSync(symlinkDir); +} catch (err) {} +try { + fs.unlinkSync(packageDir); +} catch (err) {} +try { + fs.unlinkSync(modADir); +} catch (err) {} +try { + fs.unlinkSync(symlinkModADir); +} catch (err) {} + +try { + fs.symlinkSync('./_/symlink_target', symlinkDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, 'resolver', 'symlinked', '_', 'symlink_target') + '\\', symlinkDir, 'junction'); +} +try { + fs.symlinkSync('../../package', packageDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'package') + '\\', packageDir, 'junction'); +} +try { + fs.symlinkSync('../../source/node_modules/mod-a', symlinkModADir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'source', 'node_modules', 'mod-a') + '\\', symlinkModADir, 'junction'); +} + +test('symlink', function (t) { + t.plan(2); + + resolve('foo', { basedir: symlinkDir, preserveSymlinks: false }, function (err, res, pkg) { + t.error(err); + t.equal(res, path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js')); + }); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.plan(4); + + resolve('foo', { basedir: symlinkDir }, function (err, res, pkg) { + t.ok(err, 'there is an error'); + t.notOk(res, 'no result'); + + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + t.equal( + err && err.message, + 'Cannot find module \'foo\' from \'' + symlinkDir + '\'', + 'can not find nonexistent module' + ); + }); +}); + +test('sync symlink', function (t) { + var start = new Date(); + t.doesNotThrow(function () { + t.equal( + resolve.sync('foo', { basedir: symlinkDir, preserveSymlinks: false }), + path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js') + ); + }); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.throws(function () { + resolve.sync('foo', { basedir: symlinkDir }); + }, /Cannot find module 'foo'/); + t.end(); +}); + +test('sync symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + var fn = resolve.sync('package', { basedir: basedir, preserveSymlinks: false }); + + t.equal(fn, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + t.end(); +}); + +test('async symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + t.plan(2); + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + resolve('package', { basedir: basedir, preserveSymlinks: false }, function (err, result) { + t.notOk(err, 'no error'); + t.equal(result, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + }); +}); + +test('packageFilter', function (t) { + function relative(x) { + return path.relative(__dirname, x); + } + + function testPackageFilter(preserveSymlinks) { + return function (st) { + st.plan('is 1.x' ? 3 : 5); // eslint-disable-line no-constant-condition + + var destMain = 'symlinks/dest/node_modules/mod-a/index.js'; + var destPkg = 'symlinks/dest/node_modules/mod-a/package.json'; + var sourceMain = 'symlinks/source/node_modules/mod-a/index.js'; + var sourcePkg = 'symlinks/source/node_modules/mod-a/package.json'; + var destDir = path.join(__dirname, 'symlinks', 'dest'); + + /* eslint multiline-comment-style: 0 */ + /* v2.x will restore these tests + var packageFilterPath = []; + var actualPath = resolve.sync('mod-a', { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile, dir) { + packageFilterPath.push(pkgfile); + } + }); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'sync: actual path is correct' + ); + st.deepEqual( + map(packageFilterPath, relative), + map(preserveSymlinks ? [destPkg, destPkg] : [sourcePkg, sourcePkg], path.normalize), + 'sync: packageFilter pkgfile arg is correct' + ); + */ + + var asyncPackageFilterPath = []; + resolve( + 'mod-a', + { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile) { + asyncPackageFilterPath.push(pkgfile); + } + }, + function (err, actualPath) { + st.error(err, 'no error'); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'async: actual path is correct' + ); + st.deepEqual( + map(asyncPackageFilterPath, relative), + map( + preserveSymlinks ? [destPkg, destPkg, destPkg] : [sourcePkg, sourcePkg, sourcePkg], + path.normalize + ), + 'async: packageFilter pkgfile arg is correct' + ); + } + ); + }; + } + + t.test('preserveSymlinks: false', testPackageFilter(false)); + + t.test('preserveSymlinks: true', testPackageFilter(true)); + + t.end(); +}); diff --git a/node_modules/rollup/CHANGELOG.md b/node_modules/rollup/CHANGELOG.md new file mode 100644 index 0000000..6e1197b --- /dev/null +++ b/node_modules/rollup/CHANGELOG.md @@ -0,0 +1,5954 @@ +# rollup changelog + +## 2.56.3 + +_2021-08-23_ + +### Bug Fixes + +- Make sure moduleInfo contains complete information about imported ids in the moduleParsed hook (#4208) + +### Pull Requests + +- [#4208](https://github.com/rollup/rollup/pull/4208): `ModuleInfo.importedIds` will return null if `resolvedIds[source]` is undefined (@FoxDaxian and @lukastaegert) + +## 2.56.2 + +_2021-08-10_ + +### Bug Fixes + +- Check if after simplification, an object pattern would become an expression statement or arrow function return value (#4204) + +### Pull Requests + +- [#4204](https://github.com/rollup/rollup/pull/4204): Do not create invalid code when simplifying object pattern assignments (@lukastaegert) + +## 2.56.1 + +_2021-08-08_ + +### Bug Fixes + +- Fix rendering of SystemJS export declarations initialized with a simplifiable expression (#4202) + +### Pull Requests + +- [#4202](https://github.com/rollup/rollup/pull/4202): Fix incorrect rendering of export declarations in SystemJS (@lukastaegert) + +## 2.56.0 + +_2021-08-05_ + +### Features + +- Create more efficient code for SystemJS exports (#4199) +- Extend `maxParallelFileReads` option to also throttle plugin load hooks (#4200) + +### Bug Fixes + +- Return correct value for postfix update expressions of exported variables (#4194) + +### Pull Requests + +- [#4199](https://github.com/rollup/rollup/pull/4199): Refine SystemJS export rendering (@lukastaegert) +- [#4200](https://github.com/rollup/rollup/pull/4200): Restrict parallel execution of load hook (@schummar) + +## 2.55.1 + +_2021-07-29_ + +### Bug Fixes + +- Improve CLI warning message for unused external imports (#4194) + +### Pull Requests + +- [#4194](https://github.com/rollup/rollup/pull/4194): Align batch warning for UNUSED_EXTERNAL_IMPORT to individual warning (@benmccann) + +## 2.55.0 + +_2021-07-28_ + +### Features + +- Support default export live-bindings when generating ESM output (#4182) + +### Bug Fixes + +- Always write `["default"]` as computed property when used as named export (#4182) +- Do not mask default export TDZ errors (#4182) + +### Pull Requests + +- [#4182](https://github.com/rollup/rollup/pull/4182): Use mutable bindings for default exports (@lukastaegert) + +## 2.54.0 + +_2021-07-25_ + +### Features + +- Extend UMD import.meta.url polyfill to support web workers (#4186) + +### Bug Fixes + +- Resolve an issue where certain uses of classes could lead to an infinite recursion (#4189) + +### Pull Requests + +- [#4186](https://github.com/rollup/rollup/pull/4186): Fix UMD import.meta.url inside web workers (@ceifa) +- [#4188](https://github.com/rollup/rollup/pull/4188): Fix typo in renderHelpers.ts (@eltociear) +- [#4189](https://github.com/rollup/rollup/pull/4189): Move long path recursion prevention to MemberExpression (@lukastaegert) +- [#4190](https://github.com/rollup/rollup/pull/4190): Stop recommending node-builtins (@curran) + +## 2.53.3 + +_2021-07-21_ + +### Bug Fixes + +- Solve an issue that could lead to severe memory issues and crashes when there are a lot of hoisted variables (#4183) + +### Pull Requests + +- [#4183](https://github.com/rollup/rollup/pull/4183): Avoid memory issues with hoisted variables (@lukastaegert) + +## 2.53.2 + +_2021-07-15_ + +### Bug Fixes + +- Identify additional TDZ situations in functions that are run more than once (#4177) +- Fix a scoping issue when a variable inside a catch scope matches the scope parameter's name (#4178) + +### Pull Requests + +- [#4177](https://github.com/rollup/rollup/pull/4177): Fix additional let/var init bugs (@kzc) +- [#4178](https://github.com/rollup/rollup/pull/4178): Correctly create outside variable when shadowed by catch parameter (@lukastaegert) + +## 2.53.1 + +_2021-07-11_ + +### Bug Fixes + +- Do not omit namespace reexports when `treeshake` is `false` (#4175) + +### Pull Requests + +- [#4175](https://github.com/rollup/rollup/pull/4175): Generate namespace objects when not tree-shaking (@lukastaegert) + +## 2.53.0 + +_2021-07-09_ + +### Features + +- Add `maxParallelFileReads` option to limit read operations with a default of 20 (#4170) + +### Pull Requests + +- [#4170](https://github.com/rollup/rollup/pull/4170): Limit parallel file reads to prevent "EMFILE: too many open files" error (@schummar) + +## 2.52.8 + +_2021-07-07_ + +### Bug Fixes + +- Automatically handle many use `var` before declaration and TDZ access scenarios correctly without the need for `treeshake.correctVarValueBeforeDeclaration` (#4148) + +### Pull Requests + +- [#4148](https://github.com/rollup/rollup/pull/4148): Fix var/const/let variable use before declaration (@kzc and @lukastaegert) + +## 2.52.7 + +_2021-07-02_ + +### Bug Fixes + +- Fix an issue where reassignments where not tracked through async function returns (#4163) + +### Pull Requests + +- [#4163](https://github.com/rollup/rollup/pull/4163): Deoptimize return values of async functions (@lukastaegert) + +## 2.52.6 + +_2021-07-01_ + +### Bug Fixes + +- Fix an issue where reassignments where not tracked through an await expression (#4162) + +### Pull Requests + +- [#4162](https://github.com/rollup/rollup/pull/4162): doptimize awaited expressions (@lukastaegert) + +## 2.52.5 + +_2021-07-01_ + +### Bug Fixes + +- Properly display parser errors not tied to a code location (#4160) + +### Pull Requests + +- [#4160](https://github.com/rollup/rollup/pull/4160): fix: max stack call error is caught on locate (@semoal) + +## 2.52.4 + +_2021-06-30_ + +### Bug Fixes + +- Fix an error when external namespaces are reexported across several files (#4159) + +### Pull Requests + +- [#4159](https://github.com/rollup/rollup/pull/4159): Properly handle double reexports from external namespaces (@lukastaegert) + +## 2.52.3 + +_2021-06-25_ + +### Bug Fixes + +- Fix an issue where code was wrongly removed when using vars in nested scopes (#4149) + +### Pull Requests + +- [#4149](https://github.com/rollup/rollup/pull/4149): Make sure the initializer of hoisted variables is deoptimized (@lukastaegert) + +## 2.52.2 + +_2021-06-21_ + +### Bug Fixes + +- Support falsy plugins in types (#4144) +- Do not require return value in renderChunkHook type (#4144) + +### Pull Requests + +- [#4144](https://github.com/rollup/rollup/pull/4144): Use TypeScript config and improve some types (@lukastaegert) + +## 2.52.1 + +_2021-06-17_ + +### Bug Fixes + +- Fix a memory leak in watch mode (#4142) + +### Pull Requests + +- [#4142](https://github.com/rollup/rollup/pull/4142): Make array and object prototype singletons immutable for now (@lukastaegert) + +## 2.52.0 + +_2021-06-16_ + +### Features + +- Add `--configPlugin` CLI option to apply plugins to the config file for e.g. TypeScript configs (#3835) +- Add "safest" and "smallest" presets to tree-shaking options for easier configuration (#4131) +- Add `treeshake.correctVarValueBeforeDeclaration` option to deoptimize `var` declarations (#4139) + +### Pull Requests + +- [#3835](https://github.com/rollup/rollup/pull/3835): Add typescript config support (@TheRealSyler) +- [#4131](https://github.com/rollup/rollup/pull/4131): Add presets to the tree-shaking options (@lukastaegert) +- [#4139](https://github.com/rollup/rollup/pull/4139): Add option to deoptimize var declarations for tree-shaking (@lukastaegert) +- [#4141](https://github.com/rollup/rollup/pull/4141): Update dependencies (@lukastaegert) + +## 2.51.2 + +_2021-06-11_ + +### Bug Fixes + +- Include modules imported from no-treeshake modules even if they would be empty (#4138) + +### Pull Requests + +- [#4138](https://github.com/rollup/rollup/pull/4138): Include all dependencies from modules with no-treeshake (@lukastaegert) + +## 2.51.1 + +_2021-06-08_ + +### Bug Fixes + +- Fix error when using `defineConfig` (#4134) + +### Pull Requests + +- [#4134](https://github.com/rollup/rollup/pull/4134): export `rollup.defineConfig` at runtime (@mshrtsr) + +## 2.51.0 + +_2021-06-06_ + +### Features + +- Add a helper for IntelliSense support in config files (#4127) + +### Bug Fixes + +- Improve performance when generating source maps (#4122) + +### Pull Requests + +- [#4122](https://github.com/rollup/rollup/pull/4122): User Map to optimize performance (@izevo) +- [#4127](https://github.com/rollup/rollup/pull/4127): Export defineConfig defines the auxiliary function of the configuration (@rxliuli) + +## 2.50.6 + +_2021-06-03_ + +### Bug Fixes + +- Do not consider the object spread operator as side effect when `propertyReadSideEffects` are false (#4119) +- Detect side effects when returning thenables from async arrow functions (#4120) + +### Pull Requests + +- [#4119](https://github.com/rollup/rollup/pull/4119): Respect propertyReadSideEffects in spread elements (@lukastaegert) +- [#4120](https://github.com/rollup/rollup/pull/4120): Detect async arrow thenable side effects (@lukastaegert) + +## 2.50.5 + +_2021-05-30_ + +### Bug Fixes + +- Detect side effects when accessing thenables (#4115) + +### Pull Requests + +- [#4114](https://github.com/rollup/rollup/pull/4114): use `colorette` instead of `turbocolor` (@ryuever) +- [#4115](https://github.com/rollup/rollup/pull/4115): Tracks side effects of thenables (@lukastaegert) + +## 2.50.4 + +_2021-05-29_ + +### Bug Fixes + +- Fix a situation where tree-shaking would stop including nodes prematurely (#4111) +- Track mutations and accessor side effects when using `__proto__` in an object literal (#4112) +- Check for getter effects when spreading an object (#4113) + +### Pull Requests + +- [#4111](https://github.com/rollup/rollup/pull/4111): Always request a new tree-shaking pass when deoptimizations of a node are first included (@lukastaegert) +- [#4112](https://github.com/rollup/rollup/pull/4112): Actually set the prototype when using a **proto** property (@lukastaegert) +- [#4113](https://github.com/rollup/rollup/pull/4113): Track access side effects when using object spread operator (@lukastaegert) + +## 2.50.3 + +_2021-05-28_ + +### Bug Fixes + +- Wrap parentheses around leading elements in simplified sequence expressions if this would otherwise lead to invalid code (#4110) +- Do not associate block soped variables in catch clauses with the clause parameter (#4108) +- Do not associate hoisted variables in catch clauses with outside variables if they match the parameter (#4108) +- Use correct "this" context for tagged template literal member expressions in simplified sequences (#4110) + +### Pull Requests + +- [#4108](https://github.com/rollup/rollup/pull/4108): Correctly handle catch declarations (@lukastaegert) +- [#4110](https://github.com/rollup/rollup/pull/4110): Invalid sequence expression simplification (@lukastaegert) + +## 2.50.2 + +_2021-05-27_ + +### Bug Fixes + +- Avoid unnecessary side effects when using methods like `.filter` and `.map` (#4103) +- Avoid crash when a module with moduleSideEffects no-treeshake imports a tree-shaken module (#4104) + +### Pull Requests + +- [#4103](https://github.com/rollup/rollup/pull/4103): Do not track side-effect-free array methods as side effects (@lukastaegert) +- [#4104](https://github.com/rollup/rollup/pull/4104): Fix crash when using inlineDynamicImports with no-treeshake (@lukastaegert) + +## 2.50.1 + +_2021-05-26_ + +### Bug Fixes + +- Do not associate pure annotations in simplified expressions with wrong elements (#4095) +- Prevent invalid code when simplified conditionals start with an IIFE function expression (#4099) + +### Pull Requests + +- [#4095](https://github.com/rollup/rollup/pull/4095): Correctly associate pure annotations and remove invalid ones (@lukastaegert) +- [#4099](https://github.com/rollup/rollup/pull/4099): Wrap leading function expression iifes in conditionals (@lukastaegert) + +## 2.50.0 + +_2021-05-25_ + +### Features + +- Only include last elements of comma expressions if they are used or have side effects (#4087) + +### Bug Fixes + +- Prevent a crash that could occur when calling object methods (#4091) + +### Pull Requests + +- [#4085](https://github.com/rollup/rollup/pull/4085): Switch to ESLint (@lukastaegert) +- [#4087](https://github.com/rollup/rollup/pull/4087): Drop unused last sequence element (@lukastaegert) +- [#4091](https://github.com/rollup/rollup/pull/4091): Prevent crash for recursive "this" deoptimization (@lukastaegert) + +## 2.49.0 + +_2021-05-23_ + +### Features + +- Detect side-effect-free static class methods and properties (#4018) +- Detect side-effect-free array elements (#4018) +- Do not apply deoptimizations from dead code (#4018) + +### Bug Fixes + +- Handle side effect detection for getters and setters added in untracked code (#4018) +- Track "this" mutations for methods, getters and setters (#4018) + +### Pull Requests + +- [#4018](https://github.com/rollup/rollup/pull/4018): Class method effects (@marijnh and @lukastaegert) + +## 2.48.0 + +_2021-05-15_ + +### Features + +- Add replacement to conditionally insert asset extensions in `entryFileNames` when preserving modules (#4077) + +### Bug Fixes + +- Fix crash when dynamically assigning to namespace members (#4070) +- Do not associate pure annotations in front of a semi-colon or comma with succeeding code (#4068) + +### Pull Requests + +- [#4068](https://github.com/rollup/rollup/pull/4068): ignore invalid trailing pure annotations (@kzc) +- [#4070](https://github.com/rollup/rollup/pull/4070): undefined `deoptimizePath` when the first element is empty string (@si3nloong) +- [#4071](https://github.com/rollup/rollup/pull/4071): add node.js v16 support (@dnalborczyk) +- [#4077](https://github.com/rollup/rollup/pull/4077): Add assetExtname replacement in entryFileNames (@BPScott) +- [#4080](https://github.com/rollup/rollup/pull/4080): Added Rollup logo in README.md (@priyanshurav) +- [#4081](https://github.com/rollup/rollup/pull/4081): fix comment regarding invalid annotation handling (@kzc) + +## 2.47.0 + +_2021-05-04_ + +### Features + +- Warn about ambiguous imports from combined external namespace reexports (#4064) +- In case of combined namespace reexports, always prefer local exports over external namespaces (#4064) +- Treat conflicting names in local namespace reexports as undefined (#4064) + +### Pull Requests + +- [#4064](https://github.com/rollup/rollup/pull/4064): Prefer locally defined exports and reexports over external namespaces (@lukastaegert) + +## 2.46.0 + +_2021-04-29_ + +### Features + +- Add option to disable file name sanitation (#4058) +- Add information about importers to unused external import warning (#4054) + +### Pull Requests + +- [#4042](https://github.com/rollup/rollup/pull/4042): Use Github actions only (@lukastaegert) +- [#4045](https://github.com/rollup/rollup/pull/4045): Fix REPL artefact branch reference (@lukastaegert) +- [#4046](https://github.com/rollup/rollup/pull/4046): Use codecov action for coverage (@lukastaegert) +- [#4054](https://github.com/rollup/rollup/pull/4054): Add to `UNUSED_EXTERNAL_IMPORT` warning information about the origin of the problem (@cawa-93) +- [#4058](https://github.com/rollup/rollup/pull/4058): Add sanitizeFileName option (@guybedford) + +## 2.45.2 + +_2021-04-13_ + +### Bug Fixes + +- Do not user a dynamic entry file name for naming a manual chunk (#4040) + +### Pull Requests + +- [#4040](https://github.com/rollup/rollup/pull/4040): Prioritize manual chunk name over dynamic entry id (@lukastaegert) + +## 2.45.1 + +_2021-04-10_ + +### Bug Fixes + +- Handle falsy return values from async plugin options hooks (#4039) + +### Pull Requests + +- [#4039](https://github.com/rollup/rollup/pull/4039): Do not fail when returning null or undefined from an async options hook (@lukastaegert) + +## 2.45.0 + +_2021-04-09_ + +### Features + +- Support private class instance methods and accessors (#4034) + +### Pull Requests + +- [#4034](https://github.com/rollup/rollup/pull/4034): feat: add support for private class methods (@dnalborczyk) + +## 2.44.0 + +_2021-03-29_ + +### Features + +- Add a new option `makeAbsoluteExternalsRelative` to opt out of renormalizing absolute external ids to relative ids (#4021) +- Extend the `resolveId` plugin hook to allow forcing or preventing renormalization of absolute external ids (#4021) +- Make the rendered code of individual modules available in the generated bundle (#4028) + +### Bug Fixes + +- Handle objects with `__proto__` properties correctly (#4019) + +### Pull Requests + +- [#4019](https://github.com/rollup/rollup/pull/4019): Deoptimize ObjectExpression when a `__proto__` property is present (@marijnh) +- [#4021](https://github.com/rollup/rollup/pull/4021): Improve absolute path handling (@lukastaegert) +- [#4026](https://github.com/rollup/rollup/pull/4026): chore: fix vscode launch config (change tdd to bdd) (@jameslahm) +- [#4027](https://github.com/rollup/rollup/pull/4027): Post comment for PRs from forks (@lukastaegert) +- [#4028](https://github.com/rollup/rollup/pull/4028): Expose rendered module code to generateBundle hook (@btd) + +## 2.43.1 + +_2021-03-28_ + +### Bug Fixes + +- Prevent infinite recursions in certain scenarios when calling object properties (#4025) + +### Pull Requests + +- [#4025](https://github.com/rollup/rollup/pull/4025): Handle recursive this mutation detection (@lukastaegert) + +## 2.43.0 + +_2021-03-27_ + +### Features + +- Track side effects of function properties in objects for better tree-shaking (#4011) + +### Pull Requests + +- [#4011](https://github.com/rollup/rollup/pull/4011): Disable pessimistic object deoptimization for calls when the called function doesn't ref this (@marijnh) +- [#4012](https://github.com/rollup/rollup/pull/4012): fix `sourcemap` reference in docs (@tjenkinson) +- [#4015](https://github.com/rollup/rollup/pull/4015): Use SIGTERM instead of SIGINT to kill test child processes in tests (@marijnh) + +## 2.42.4 + +_2021-03-24_ + +### Bug Fixes + +- Do not discard plugin return values when using perf option (#4010) + +### Pull Requests + +- [#4010](https://github.com/rollup/rollup/pull/4010): Return hook result inside promise with async timer end (@SuperOleg39) + +## 2.42.3 + +_2021-03-22_ + +### Bug Fixes + +- Do not ignore `#__PURE__` comments in front of optional chaining expressions (#4007) + +### Pull Requests + +- [#4007](https://github.com/rollup/rollup/pull/4007): Tree-shake pure call expressions with optional chaining (@lukastaegert) + +## 2.42.2 + +_2021-03-22_ + +### Bug Fixes + +- Use correct import.meta.url in relative imports from transpiled config files (#4005) + +### Pull Requests + +- [#4005](https://github.com/rollup/rollup/pull/4005): Use correct import.meta.url in config files (@lukastaegert) + +## 2.42.1 + +_2021-03-20_ + +### Bug Fixes + +- Do not produce unhandled Promise rejections when plugins throw while using the `perf` option (#4004) + +### Pull Requests + +- [#4004](https://github.com/rollup/rollup/pull/4004): Fixed unhandled promise rejections (@gluck) + +## 2.42.0 + +_2021-03-19_ + +### Features + +- Prevent infinite loops when several plugins are using `this.resolve` in their resolveId hook (#4000) + +### Pull Requests + +- [#4000](https://github.com/rollup/rollup/pull/4000): Break infinite loops in this.resolve (@lukastaegert) + +## 2.41.5 + +_2021-03-18_ + +### Bug Fixes + +- Make sure unused property accesses of external namespaces can be tree-shaken (#4001) + +### Pull Requests + +- [#4001](https://github.com/rollup/rollup/pull/4001): Do not count accessing members of an external namespace as side-effects (@lukastaegert) + +## 2.41.4 + +_2021-03-16_ + +### Bug Fixes + +- Do not replace external namespace imports with individual named imports to avoid changing behaviour with regard to missing exports (#3999) + +### Pull Requests + +- [#3999](https://github.com/rollup/rollup/pull/3999): Allow to safely probe external namespaces (@lukastaegert) + +## 2.41.3 + +_2021-03-16_ + +### Bug Fixes + +- Always retain arguments passed to empty object pattern parameters (#3998) + +### Pull Requests + +- [#3998](https://github.com/rollup/rollup/pull/3998): Do not create invalid code if a function argument is an empty object pattern (@lukastaegert) + +## 2.41.3 + +_2021-03-16_ + +### Bug Fixes + +- Always retain arguments passed to empty object pattern parameters (#3998) + +### Pull Requests + +- [#3998](https://github.com/rollup/rollup/pull/3998): Do not create invalid code if a function argument is an empty object pattern (@lukastaegert) + +## 2.41.2 + +_2021-03-12_ + +### Bug Fixes + +- Also remove sourcemaps comments if plugins return a pre-made ast (#3987) + +### Pull Requests + +- [#3987](https://github.com/rollup/rollup/pull/3987): Change removal of sourcemap comment (@yannayl) + +## 2.41.1 + +_2021-03-11_ + +### Pull Requests + +- [#3990](https://github.com/rollup/rollup/pull/3990): Add browser sourcemap and remove log (@lukastaegert) + +## 2.41.0 + +_2021-03-09_ + +### Features + +- Add option to `treeshake.propertyReadSideEffects` to keep all property accesses (#3985) + +### Bug Fixes + +- Also respect pure comment annotations when a plugin provides an AST in the transform hook provided they use this.parse (#3981) + +### Pull Requests + +- [#3981](https://github.com/rollup/rollup/pull/3981): Move pure comment annotation to Graph.contextParse (@yannayl) +- [#3985](https://github.com/rollup/rollup/pull/3985): implement --treeshake.propertyReadSideEffects=always to handle getters with side effects (@kzc) + +## 2.40.0 + +_2021-02-26_ + +### Features + +- Make sure that entry point variable names take precedence over variable names in dependencies when deconflicting (#3977) + +### Bug Fixes + +- Replace `:` in generated file names to prevent invalid files on Windows (#3972) + +### Pull Requests + +- [#3972](https://github.com/rollup/rollup/pull/3972): Don't allow `:` in file names (@lukastaegert) +- [#3976](https://github.com/rollup/rollup/pull/3976): Add soft breaks to guide to improve mobile experience (@lukastaegert) +- [#3977](https://github.com/rollup/rollup/pull/3977): Reverse module deconflicting order (@lukastaegert) + +## 2.39.1 + +_2021-02-23_ + +### Bug Fixes + +- Make sure local variables named Symbol, Object or Promise do not conflict with code generated by Rollup (#3971) + +### Pull Requests + +- [#3964](https://github.com/rollup/rollup/pull/3964): Remove extra word (@jamonholmgren) +- [#3971](https://github.com/rollup/rollup/pull/3971): Avoid conflicts with local variables named Symbol, Object, Promise (@lukastaegert) + +## 2.39.0 + +_2021-02-12_ + +### Features + +- Add "validate" option to verify generated chunks are valid JavaScript (#3952) + +### Bug Fixes + +- Always add exports properties for uninitialized named exports (#3957) +- Allow using an external namespace reexport together with named exports (#3959) +- Avoid invalid generated code in certain scenarios with SystemJS exports (#3960) + +### Pull Requests + +- [#3952](https://github.com/rollup/rollup/pull/3952): implement `validate` output option and `--validate` CLI option (@kzc) +- [#3956](https://github.com/rollup/rollup/pull/3956): Update dependencies, fix fsevents issue (@lukastaegert) +- [#3957](https://github.com/rollup/rollup/pull/3957): Make sure uninitialised exports turn up via .hasOwnProperty for non-ES formats (@lukastaegert) +- [#3959](https://github.com/rollup/rollup/pull/3959): Allow overriding individual exports of reexported external namespaces (@lukastaegert) +- [#3960](https://github.com/rollup/rollup/pull/3960): Make sure system exports are valid JavaScript (@lukastaegert) + +## 2.38.5 + +_2021-02-05_ + +### Bug Fixes + +- Prevent invalid code when simplifying assignments and delcarations (#3951) +- Prevent behaviour-changing line-breaks when simplifying assignments in return statements (#3951) +- Slightly improve white-space rendering when simplifying certain expressions (#3951) + +### Pull Requests + +- [#3951](https://github.com/rollup/rollup/pull/3951): Wrap simplified assignments if necessary (@lukastaegert) + +## 2.38.4 + +_2021-02-02_ + +### Bug Fixes + +- Do not change logic when tree-shaking declarations in if statements or loops (#3947) + +### Pull Requests + +- [#3947](https://github.com/rollup/rollup/pull/3947): Do not tear apart declarations in loop or if bodies (@lukastaegert) + +## 2.38.3 + +_2021-02-01_ + +### Bug Fixes + +- Prevent an unexpected live-binding when default exporting a synthetic named export (#3946) + +### Pull Requests + +- [#3945](https://github.com/rollup/rollup/pull/3945): Upgrade chokidar and fsevents for Apple M1 compatibility (@threepointone) +- [#3946](https://github.com/rollup/rollup/pull/3946): Make sure default exports snapshot synthetic named exports (@lukastaegert) + +## 2.38.2 + +_2021-01-31_ + +### Bug Fixes + +- Do not generate invalid code for partially tree-shaken declarations in for loops (#3943) +- Always include function bodies of functions in side-effect-free modules (#3944) + +### Pull Requests + +- [#3943](https://github.com/rollup/rollup/pull/3943): Do not partially tree-shake unused declarations in for loops (@lukastaegert) +- [#3944](https://github.com/rollup/rollup/pull/3944): Correctly include functions with side effects from side-effect-free modules (@lukastaegert) + +## 2.38.1 + +_2021-01-28_ + +### Bug Fixes + +- Fix internal error when resolving a missing entry point in the browser build (#3935) + +### Pull Requests + +- [#3935](https://github.com/rollup/rollup/pull/3935): fix: remove isolated resolve() for compat with browser distribution (@cmorten and @lukastaegert) +- [#3936](https://github.com/rollup/rollup/pull/3936): Ensure test after() callback is always executed (@Benjamin-Dobell) +- [#3937](https://github.com/rollup/rollup/pull/3937): Modernize references to other software (@ludofischer) + +## 2.38.0 + +_2021-01-22_ + +### Features + +- Entirely remove declared variables that only have an initializer side effect (#3933) + +### Pull Requests + +- [#3933](https://github.com/rollup/rollup/pull/3933): Tree-shake unused declarations while keeping initializer side-effects (@lukastaegert) + +## 2.37.1 + +_2021-01-20_ + +### Pull Requests + +- [#3929](https://github.com/rollup/rollup/pull/3929): Deduplicate acorn import (@lukastaegert) + +## 2.37.0 + +_2021-01-19_ + +### Features + +- Always check modules for side effects that only indirectly reexport a used variable (#3840) +- Warn if a circular dependency would cause wrong execution order when preserving modules (#3840) + +### Bug Fixes + +- Allow consuming synthetic exports via modules that reexport a namespace (#3894) +- Do not crash for circular default reexports (#3840) +- Do not crash for circular synthetic namespaces (#3840) +- Improve circular dependency execution order in certain scenarios (#3840) + +### Pull Requests + +- [#3840](https://github.com/rollup/rollup/pull/3840): Improve circular dependency execution order (@lukastaegert) +- [#3894](https://github.com/rollup/rollup/pull/3894): Always respect synthetic namespaces in namespace reexport (@lukastaegert) + +## 2.36.2 + +_2021-01-16_ + +### Bug Fixes + +- Fix an issue where invalid code was generated for unused assignments with side effects (#3926) + +### Pull Requests + +- [#3926](https://github.com/rollup/rollup/pull/3926): Correctly simplify assignments with parentheses (@lukastaegert) + +## 2.36.1 + +_2021-01-06_ + +### Bug Fixes + +- Solve issues that result in invalid code when partially removing assignments (#3921) + +### Pull Requests + +- [#3921](https://github.com/rollup/rollup/pull/3921): Prevent invalid code when removing assignment target of side-effectful object expression (@lukastaegert) + +## 2.36.0 + +_2021-01-05_ + +### Features + +- Support partial tree-shaking of chained assignments and unused assignment targets (#3919) + +### Pull Requests + +- [#3919](https://github.com/rollup/rollup/pull/3919): Treeshake chained assignment expressions (@lukastaegert) + +## 2.35.1 + +_2020-12-14_ + +### Bug Fixes + +- Allow closing the bundle when watching in case of generate errors by adding the bundle to the error event (#3909) +- Automatically close all bundles on generate errors when watching and using the CLI (#3909) +- Try to create remaining bundles when watching and one of them throws (#3909) + +### Pull Requests + +- [#3909](https://github.com/rollup/rollup/pull/3909): Forward bundle through watch error events (@lukastaegert) + +## 2.35.0 + +_2020-12-14_ + +### Features + +- Add `closeBundle` hook that is triggered by `bundle.close()` in the JS API (#3883) + +### Pull Requests + +- [#3883](https://github.com/rollup/rollup/pull/3883): Revert pattern to folder export (@intrnl) + +## 2.34.2 + +_2020-12-06_ + +### Bug Fixes + +- Revert pattern export change (#3898) + +### Pull Requests + +- [#3898](https://github.com/rollup/rollup/pull/3898): Revert pattern to folder export (@lukastaegert) + +## 2.34.1 + +_2020-12-03_ + +### Bug Fixes + +- Avoid Node deprecation warning by using a pattern export for nested Rollup files (#3896) + +### Pull Requests + +- [#3887](https://github.com/rollup/rollup/pull/3887): Run memory leak test on all systems (@lukastaegert) +- [#3892](https://github.com/rollup/rollup/pull/3892): Add pull_request to windows github actions (@shellscape) +- [#3893](https://github.com/rollup/rollup/pull/3893): Update dependencies (@lukastaegert) +- [#3896](https://github.com/rollup/rollup/pull/3896): Replace deprecated folder package export with pattern export (@lukastaegert) + +## 2.34.0 + +_2020-11-29_ + +### Features + +- Support RequireJS comaptible AMD ids in code-splitting builds via amd.autoId (#3867) +- Allow adding an AMD id base path (#3867) + +### Bug Fixes + +- Warn when using an constant AMD id in a code-splitting build (#3867) + +### Pull Requests + +- [#3867](https://github.com/rollup/rollup/pull/3867): Implement amd.autoId/amd.basePath options (@tjenkinson) + +## 2.33.3 + +_2020-11-18_ + +### Bug Fixes + +- Do not use `.js` extension when importing AMD files from a UMD bundle (#3872) + +### Pull Requests + +- [#3861](https://github.com/rollup/rollup/pull/3861): Update chat/support links (@shellscape) +- [#3872](https://github.com/rollup/rollup/pull/3872): Also removeExtensionFromRelativeAmdId in UMD finaliser (@tjenkinson) + +## 2.33.2 + +_2020-11-14_ + +### Bug Fixes + +- Fix an issue where statements were ignored after a conditional return in a labeled statement (#3871) + +### Pull Requests + +- [#3871](https://github.com/rollup/rollup/pull/3871): Correctly track label usage in try statements (@Amareis) + +## 2.33.1 + +_2020-11-02_ + +### Bug Fixes + +- Add `syntheticNamedExports` to `this.getModuleInfo` to align with documentation (#3847) + +### Pull Requests + +- [#3847](https://github.com/rollup/rollup/pull/3847): Expose syntheticNamedExports to ModuleInfo (@Amareis) +- [#3852](https://github.com/rollup/rollup/pull/3852): Fix typo on docs (@jpsc) + +## 2.33.0 + +_2020-11-01_ + +### Features + +- Add parameter to "watchChange" hook to denote if a change was an addition, update or deletion (#3841) +- Add "closeWatcher" hook to allow plugins to clean up resources when the watcher is closed (#3841) +- Add "this.getWatchFiles" function to plugin context to get the current set of watched files (#3841) + +### Pull Requests + +- [#3841](https://github.com/rollup/rollup/pull/3841): Improved watcher hooks (@Amareis) +- [#3848](https://github.com/rollup/rollup/pull/3848): Add options hook to asyncpluginhooks (@intrnl) + +## 2.32.1 + +_2020-10-21_ + +### Bug Fixes + +- Print warning location for plugin warnings if only `loc` is supplied (#3824) + +### Pull Requests + +- [#3824](https://github.com/rollup/rollup/pull/3824): plugin warnings not showing warning.loc (@luciotato) + +## 2.32.0 + +_2020-10-16_ + +### Features + +- Extend `preserveEntrySignatures` with a value `"exports-only"` to allow extension only if an entry does not have exports (#3823) + +### Pull Requests + +- [#3823](https://github.com/rollup/rollup/pull/3823): Add "exports-only" option to preserveSignature (@lukastaegert) + +## 2.31.0 + +_2020-10-15_ + +### Features + +- When using the `output.moduleToStringTag` option, also add the tag to entries with exports and simulated external namespaces (#3822) +- Add the `__esModule` interop marker to IIFE global variables unless `output.esModule` is turned off (#3822) + +### Pull Requests + +- [#3822](https://github.com/rollup/rollup/pull/3822): Add module toStringTag to entries and interop namespaces (@lukastaegert) + +## 2.30.0 + +_2020-10-13_ + +### Features + +- Add `moduleParsed` hook that is called for each module once code and AST are available (#3813) +- Include code and AST in `this.getModuleInfo` (#3813) + +### Bug Fixes + +- Provide the original Acorn AST instead of the internal one when resolving dynamic imports that contain non-trivial expressions (#3813) + +### Pull Requests + +- [#3813](https://github.com/rollup/rollup/pull/3813): Add moduleParsed plugin hook (@lukastaegert) +- [#3815](https://github.com/rollup/rollup/pull/3815): Docs: wile => while (@tjenkinson) +- [#3817](https://github.com/rollup/rollup/pull/3817): Docs: fix code snippet (@codefrau) +- [#3818](https://github.com/rollup/rollup/pull/3818): Update documentation on configuring Babel, removing the section on passing '{"modules": false}' as that is no longer needed since Babel 7 (@Robin-Hoodie) + +## 2.29.0 + +_2020-10-08_ + +### Features + +- Allow passing custom options to other plugins via `this.resolve` (#3807) +- Allow attaching custom meta information to modules when resolving, loading or transforming (#3807) +- Do not throw but return `null` when using `this.getModuleInfo` for an unknown id (#3807) + +### Bug Fixes + +- Trigger build in watch mode when files are added to a watched directory (#3812) +- Make `code` optional when transforming modules (#3807) + +### Pull Requests + +- [#3807](https://github.com/rollup/rollup/pull/3807): Implement new APIs for inter-plugin communication (@lukastaegert) +- [#3808](https://github.com/rollup/rollup/pull/3808): Document that the default value of --format is 'es' (@jameshfisher) +- [#3812](https://github.com/rollup/rollup/pull/3812): Watch: listen for new files added to a directory (@dmitrage) + +## 2.28.2 + +_2020-09-24_ + +### Bug Fixes + +- Fix a source of possible variable name conflicts when using preserveModules with SystemJS (#3796) + +### Pull Requests + +- [#3792](https://github.com/rollup/rollup/pull/3792): add documentation for output.PreserveModulesRoot (@davidroeca) +- [#3796](https://github.com/rollup/rollup/pull/3796): Fix SystemJS default variable conflict (@lukastaegert) + +## 2.28.1 + +_2020-09-21_ + +### Bug Fixes + +- Fix a path slash issue when using the preserveModulesRoot option on Windows (#3791) + +### Pull Requests + +- [#3791](https://github.com/rollup/rollup/pull/3791): Fix preserveModulesRoot path on Windows (@lukastaegert) + +## 2.28.0 + +_2020-09-21_ + +### Features + +- Add an option to treat modules at a given path as located at root when preserving modules (#3786) + +### Pull Requests + +- [#3786](https://github.com/rollup/rollup/pull/3786): Add preserveModulesRoot config option (@davidroeca) + +## 2.27.1 + +_2020-09-17_ + +### Bug Fixes + +- Do not fail when using ES module imports in symlinked config files (#3783) + +### Pull Requests + +- [#3783](https://github.com/rollup/rollup/pull/3783): Handle loading symlinked config files (@lukastaegert) + +## 2.27.0 + +_2020-09-16_ + +### Features + +- Support specifying a file extension when reading from stdin (#3775) + +### Bug Fixes + +- Do not break logic if a branch with hoisted variables is tree-shaken in an else-if statement (#3782) + +### Pull Requests + +- [#3770](https://github.com/rollup/rollup/pull/3770): Docs: Exception for babel plugin and commonjs plugin (@jsk7) +- [#3775](https://github.com/rollup/rollup/pull/3775): add ability to specify stdin file extension via --stdin=ext (@kzc) +- [#3782](https://github.com/rollup/rollup/pull/3782): Handle hoisted variables in dead branches of nested if statements (@lukastaegert) + +## 2.26.11 + +_2020-09-08_ + +### Bug Fixes + +- Do not fail for unknown nodes as if statement branches (#3769) + +### Pull Requests + +- [#3769](https://github.com/rollup/rollup/pull/3769): Handle debugger statements as if-statement branches (@lukastaegert) + +## 2.26.10 + +_2020-09-04_ + +### Bug Fixes + +- Do not create invalid code when simplifying expressions in return statements that contain line comments (#3762) + +### Pull Requests + +- [#3757](https://github.com/rollup/rollup/pull/3757): Fix api docs loadconfigfile (@maxwell8888) +- [#3762](https://github.com/rollup/rollup/pull/3762): Handle line-comments when removing line-breaks to prevent ASI (@lukastaegert) + +## 2.26.9 + +_2020-09-01_ + +### Bug Fixes + +- Add regular expression support to watch include/exclude types (#3754) + +### Pull Requests + +- [#3754](https://github.com/rollup/rollup/pull/3754): Add RegExp to the include and exclude fields of the WatcherOptions type (@dagda1) +- [#3756](https://github.com/rollup/rollup/pull/3756): Update FAQ: I think it was meant "external" instead of "other-entry.js" (@madacol) + +## 2.26.8 + +_2020-08-29_ + +### Bug Fixes + +- Make sure that both unresolved and resolved ids are passed to the `external` option in all cases (#3753) + +### Pull Requests + +- [#3753](https://github.com/rollup/rollup/pull/3753): Also pass resolved ids to external if they use the object for (@lukastaegert) + +## 2.26.7 + +_2020-08-28_ + +### Bug Fixes + +- Avoid invalid code when rendering hoisted variable declarations from dead branches (#3752) +- Mark the `options` parameter of `this.parse` as optional for TypeScript plugins (#3750) + +### Pull Requests + +- [#3750](https://github.com/rollup/rollup/pull/3750): Make `options` of `PluginContext#parse` optional (@intrnl) +- [#3752](https://github.com/rollup/rollup/pull/3752): Extract hoisted variables from dead branches (@lukastaegert) + +## 2.26.6 + +_2020-08-27_ + +### Bug Fixes + +- Avoid conflicts between the namespace of synthetic named exports and local variables (#3747) + +### Pull Requests + +- [#3747](https://github.com/rollup/rollup/pull/3747): Properly deconflict synthetic named exports (@lukastaegert) + +## 2.26.5 + +_2020-08-22_ + +### Bug Fixes + +- Use correctly deconflicted variable names for reexported namespaces in ES formats (#3742) + +### Pull Requests + +- [#3742](https://github.com/rollup/rollup/pull/3742): Avoid variable name conflict when reexporting several namespaces from a chunk (@lukastaegert) + +## 2.26.4 + +_2020-08-19_ + +### Bug Fixes + +- Fix a situation where invalid code was rendered when dynamically importing a module with synthetic named exports when preserving modules (#3738) +- Create a proper namespace object when in a non-es format, a namespace is imported from a chunk with `default` export mode (#3738) +- Use the same variable when in a chunk, a namespace is both imported and reexported as a binding (#3738) +- Do not include the synthetic namespace in static entry points unless it is actually used (#3738) +- Make sure the chunking of one output does not interfere with the namespace objects of another output (#3738) + +### Pull Requests + +- [#3738](https://github.com/rollup/rollup/pull/3738): Improve synthetic entry handling (@lukastaegert) + +## 2.26.3 + +_2020-08-16_ + +### Bug Fixes + +- Fix a situation where line-breaks in a nested simplified conditional expression could result in broken code (#3734) + +### Pull Requests + +- [#3734](https://github.com/rollup/rollup/pull/3734): Prevent ASI when simplifying a nested logical expression (@lukastaegert) + +## 2.26.2 + +_2020-08-16_ + +### Bug Fixes + +- Fix a situation where line-breaks in a simplified conditional expression could result in broken code (#3732) + +### Pull Requests + +- [#3732](https://github.com/rollup/rollup/pull/3732): Prevent unintended ASI for nested conditionals (@lukastaegert) + +## 2.26.1 + +_2020-08-16_ + +### Bug Fixes + +- Correctly render external namespace imports when only generating SystemJS output (#3731) + +### Pull Requests + +- [#3731](https://github.com/rollup/rollup/pull/3731): Render system namespace import (@sastan and @lukastaegert) + +## 2.26.0 + +_2020-08-15_ + +### Features + +- Add a new entry `importedBindings` to the bundle information to list bindings per dependency (#3722) + +### Bug Fixes + +- Do not render an invalid UMD wrapper when no bindings are imported from a dependency (#3724) +- Avoid situations where removing the `else` branch from an `if` statement might catch the `else` branch from another one (#3725) + +### Pull Requests + +- [#3722](https://github.com/rollup/rollup/pull/3722): Add import specifiers to bundle information (@lukastaegert) +- [#3724](https://github.com/rollup/rollup/pull/3724): Fix missing variables for UMD and IIFE builds (@lukastaegert) +- [#3725](https://github.com/rollup/rollup/pull/3725): Do not entirely remove else branch if another else branch might accidentally be referenced (@lukastaegert) + +## 2.25.0 + +_2020-08-14_ + +### Features + +- Add `--failAfterWarnings` CLI flag that will complete builds with warnings but return an error at the end (#3712) + +### Pull Requests + +- [#3712](https://github.com/rollup/rollup/pull/3712): Implement `--failAfterWarnings` flag (@tjenkinson) + +## 2.24.0 + +_2020-08-13_ + +### Features + +- Allow defining interop per dependency via a function (#3710) +- Support interop "auto" as a more compatible version of "true" (#3710) +- Support interop "default" and "esModule" to avoid unnecessary interop helpers (#3710) +- Support interop "defaultOnly" for simplified helpers and Node ESM interop compatible output (#3710) +- Respect interop option for external dynamic imports (#3710) +- Support live-bindings for external default imports in non-ES formats unless "externalLiveBindings" is "false" (#3710) +- Use shared default interop helpers for AMD, UMD and IIFE formats (#3710) +- Avoid unnecessarily deconflicted module variables in non-ES formats (#3710) +- Freeze generated interop namespace objects (#3710) +- Always mark interop helpers as pure (#3710) +- Avoid default export interop if there is already an interop namespace object (#3710) +- Sort all `require` statements to the top in CommonJS output for easier back-transpilation to ES modules by other tools (#3710) + +### Bug Fixes + +- Handle accessing `super` in static class fields (#3720) +- Deconflict the names of helper variables introduced for interop (#3710) +- Generate proper namespace objects for static namespace imports in non-ES formats (#3710) +- Do not add unused interop helpers when using the renderDynamicImport hook (#3710) + +### Pull Requests + +- [#3710](https://github.com/rollup/rollup/pull/3710): Rework interop handling (@lukastaegert) +- [#3720](https://github.com/rollup/rollup/pull/3720): Handle super in static class fields (@lukastaegert) + +## 2.23.1 + +_2020-08-07_ + +### Bug Fixes + +- Fix an issue where dynamically importing an entry point could return a malformed namespace for CJS and AMD formats (#3709) + +### Pull Requests + +- [#3709](https://github.com/rollup/rollup/pull/3709): Properly construct namespace when dynamically importing chunks with facades in default export mode (@lukastaegert) + +## 2.23.0 + +_2020-07-23_ + +### Features + +- Handle environments with only globalThis in UMD output (#3691) + +### Pull Requests + +- [#3691](https://github.com/rollup/rollup/pull/3691): Check for globalThis in UMD wrapper (@lukastaegert) + +## 2.22.2 + +_2020-07-21_ + +### Bug Fixes + +- Always generate correct exports when an implicit entry is reexporting from another module (#3688) + +### Pull Requests + +- [#3688](https://github.com/rollup/rollup/pull/3688): Include all relevant modules to generate reexports for implicit dependencies (@lukastaegert) + +## 2.22.1 + +_2020-07-18_ + +### Bug Fixes + +- Remove unused arguments when calling a conditional expression (#3680) + +### Pull Requests + +- [#3680](https://github.com/rollup/rollup/pull/3680): Allow tree-shaking of arguments of functions that are returned by conditional expressions (@lukastaegert) + +## 2.22.0 + +_2020-07-18_ + +### Features + +- Allow resolving synthetic named exports via an arbitrary export name (#3657) +- Display a warning when the user does not explicitly select an export mode and would generate a chunk with default export mode when targeting CommonJS (#3657) + +### Pull Requests + +- [#3657](https://github.com/rollup/rollup/pull/3657): Add basic support for using a non-default export for syntheticNamedExports (@lukastaegert) +- [#3659](https://github.com/rollup/rollup/pull/3659): Warn when implicitly using default export mode (@lukastaegert) + +## 2.21.0 + +_2020-07-07_ + +### Features + +- Allow plugins to disable tree-shaking for individual modules to ensure even empty modules are associated with chunks (#3663) + +### Pull Requests + +- [#3663](https://github.com/rollup/rollup/pull/3663): Disable treeshaking per module (@lukastaegert) + +## 2.20.0 + +_2020-07-06_ + +### Features + +- Support using a function to generate different chunk and asset naming patterns per chunk or asset (#3658) +- Add `referencedFiles` property to the chunk info in generateBundle to list referenced assets (#3661) + +### Pull Requests + +- [#3658](https://github.com/rollup/rollup/pull/3658): Add ability to use a function that returns a pattern string in all places where you could use a pattern string before (@frank-dspeed) +- [#3661](https://github.com/rollup/rollup/pull/3661): Add referenced files to bundle (@lukastaegert) + +## 2.19.0 + +_2020-07-05_ + +### Features + +- Allow plugins to return a Promise in the options hook (#3660) + +### Pull Requests + +- [#3660](https://github.com/rollup/rollup/pull/3660): Make options hooks async (@TomerAberbach) + +## 2.18.2 + +_2020-07-02_ + +### Bug Fixes + +- Do not remove spread element args when the corresponding positional parameter is unused (#3652) + +### Pull Requests + +- [#3652](https://github.com/rollup/rollup/pull/3652): Do not tree-shake arguments that contain a spread element (@lukastaegert) + +## 2.18.1 + +_2020-06-26_ + +### Bug Fixes + +- Make sure synthetic exports are present when a module is imported dynamically (#3648) +- Strip the `rollup-plugin-` prefix off the plugin name when looking for the plugin export in a CLI plugin without a default export (#3647) +- Convert plugin names with dashes to camel case when looking for the plugin export in a CLI plugin without a default export (#3647) + +### Pull Requests + +- [#3647](https://github.com/rollup/rollup/pull/3647): Strip rollup-plugin prefix to find named plugin exports, throw when export cannot be found (@lukastaegert) +- [#3648](https://github.com/rollup/rollup/pull/3648): Always create a dynamic namespace object when a module with synthetic named exports is imported dynamically (@lukastaegert) + +## 2.18.0 + +_2020-06-22_ + +### Features + +- `inlineDynamicImports`, `manualChunks` and `preserveModules` can now be used as output options (#3645) +- Use sourcemaps for certain warnings that reference source code locations (#3645) + +### Bug Fixes + +- `this.getFileName` will now always return the correct file name for chunks when multiple outputs are created (#3645) + +### Pull Requests + +- [#3645](https://github.com/rollup/rollup/pull/3645): Per output chunking (@lukastaegert) + +## 2.17.1 + +_2020-06-19_ + +### Bug Fixes + +- Properly resolve accessing properties of namespace members again (#3643) + +### Pull Requests + +- [#3643](https://github.com/rollup/rollup/pull/3643): Fix accessing nested properties of namespaces (@lukastaegert) + +## 2.17.0 + +_2020-06-17_ + +### Features + +- When importing Rollup via package.exports, always fall back to the browser ESM build for non-Node environments (#3634) +- Create more efficient code when handling namespace mutations (#3637) + +### Bug Fixes + +- Fix a severe performance regression when the same module is imported by a lot of modules (#3641) +- Properly escape special characters in imports (#3638) + +### Pull Requests + +- [#3634](https://github.com/rollup/rollup/pull/3634): Set browser build in exports (@guybedford) +- [#3637](https://github.com/rollup/rollup/pull/3637): Do not include the whole namespace when illegally mutating a namespace (@lukastaegert) +- [#3638](https://github.com/rollup/rollup/pull/3638): Support backslash escaping, retain exact newline escaping (@guybedford) +- [#3641](https://github.com/rollup/rollup/pull/3641): Fix performance regression when a file is imported by many importers (@lukastaegert) + +## 2.16.1 + +_2020-06-13_ + +### Bug Fixes + +- Do not produce invalid code when an external or chunk id contain quotes or line-breaks (#3632) +- Do not fail but emit a warning when mutating a namespace object (#3633) + +### Pull Requests + +- [#3632](https://github.com/rollup/rollup/pull/3632): Handle single quote escaping in ids (@guybedford) +- [#3633](https://github.com/rollup/rollup/pull/3633): Turn namespace assignment error into a warning (@guybedford) + +## 2.16.0 + +_2020-06-12_ + +### Features + +- Add support for numeric separators (#3626) +- Switch to finalized ESTree optional chaining AST (#3628) + +### Pull Requests + +- [#3626](https://github.com/rollup/rollup/pull/3626): Support numeric separator (@TrySound) +- [#3628](https://github.com/rollup/rollup/pull/3628): Acorn 7.3.0 upgrade (@guybedford) +- [#3631](https://github.com/rollup/rollup/pull/3631): Improve discoverability of `manualChunks` for code splitting (@zlamma) + +## 2.15.0 + +_2020-06-08_ + +### Features + +- Allow to skip watching some configs via `watch: false` (#3620) +- Provide the resolved sourcemap path to `sourcemapPathTransform` (#3617) + +### Pull Requests + +- [#3617](https://github.com/rollup/rollup/pull/3617): Update sourcemapPathTransform to also take the path to the sourcemap file as a second argument (@dgoldstein0) +- [#3620](https://github.com/rollup/rollup/pull/3620): Rollup watch only one config in exported array (@luwol03) + +## 2.14.0 + +_2020-06-07_ + +### Features + +- Make `this.meta.watchMode` available for plugins to detect watch mode (#3616) + +### Bug Fixes + +- Handle exporting the same binding with different names in SystemJS (#3575) + +### Pull Requests + +- [#3575](https://github.com/rollup/rollup/pull/3575): Handle some cases of duplicate export bindings (@joeljeske) +- [#3616](https://github.com/rollup/rollup/pull/3616): Make watch mode available in plugins (@lukastaegert) + +## 2.13.1 + +_2020-06-04_ + +### Bug Fixes + +- Prevent conflicts in SystemJS when `module` is used as a top-level variable (#3614) + +### Pull Requests + +- [#3614](https://github.com/rollup/rollup/pull/3614): Handle system reserved identifier dedupes (@guybedford) + +## 2.13.0 + +_2020-06-03_ + +### Features + +- Allow to specify that an emitted chunk is only loaded after a given module has loaded to improve chunking (#3606) + +### Pull Requests + +- [#3606](https://github.com/rollup/rollup/pull/3606): Enable specifying implicit dependencies when emitting chunks (@lukastaegert) + +## 2.12.1 + +_2020-06-02_ + +### Bug Fixes + +- Render valid imports when chunk names correspond to directory names in virtual setups (#3609) + +### Pull Requests + +- [#3609](https://github.com/rollup/rollup/pull/3609): Handle imports from chunks with names that correspond to parent directory names of other chunks (@guybedford) + +## 2.12.0 + +_2020-05-31_ + +### Features + +- Add an option `--waitForBundleInput` to let the build wait until all entry point files are available before starting (#3577) + +### Pull Requests + +- [#3577](https://github.com/rollup/rollup/pull/3577): Wait for bundle input option (@Heerschop) + +## 2.11.2 + +_2020-05-28_ + +### Bug Fixes + +- Include side-effects in the second argument of `Array.from` (#3604) + +### Pull Requests + +- [#3604](https://github.com/rollup/rollup/pull/3604): Mark `Array.from` as side-effectful, use two-argument Array.from when mapping Sets (@lukastaegert) + +## 2.11.1 + +_2020-05-28_ + +### Bug Fixes + +- Also include side-effects in files that are marked as side-effect-free if they contain an included default export that is reexported (#3602) + +### Pull Requests + +- [#3602](https://github.com/rollup/rollup/pull/3602): Handle side-effects next to side-effect-free default exports in case the default export is reexported (@lukastaegert) + +## 2.11.0 + +_2020-05-27_ + +### Features + +- Add basic support for optional chaining (#3582) +- Provide a normalized set of options with proper default values to `buildStart` and `renderStart` (#3597) +- Do not count adding properties to the prototype of an unused class as a side-effect (#3598) +- Support providing `null` for empty setters in SystemJS via option (#3592) + +### Bug Fixes + +- Do not fail when using a `/*#__PURE__*/` annotation inside a class field (#3599) +- Allow using `--watch` and `--treeshake` together with sub-options such as `--watch.clearScreen` on the command line (#3597) + +### Pull Requests + +- [#3582](https://github.com/rollup/rollup/pull/3582): Support optional chaining via acorn fork(@guybedford) +- [#3592](https://github.com/rollup/rollup/pull/3592): System format optional setters(@guybedford) +- [#3597](https://github.com/rollup/rollup/pull/3597): Provide normalized options (@lukastaegert) +- [#3598](https://github.com/rollup/rollup/pull/3598): Treeshake prototype modifications in classes (@lukastaegert) +- [#3599](https://github.com/rollup/rollup/pull/3599): Retain pure annotations in class fields (@lukastaegert) +- [#3601](https://github.com/rollup/rollup/pull/3601): Fix white-space in docs (@tu4mo) + +## 2.10.9 + +_2020-05-24_ + +### Bug Fixes + +- Prevent invalid exports when facades are created (#3590) + +### Pull Requests + +- [#3590](https://github.com/rollup/rollup/pull/3590): Prevent unneeded exports when entry facades are created and ensure all exported variables in facades are imported (@lukastaegert) + +## 2.10.8 + +_2020-05-23_ + +### Bug Fixes + +- Fix issues when synthetic named exports are reexported as default exports (#3586) + +### Pull Requests + +- [#3584](https://github.com/rollup/rollup/pull/3584): Clarify documentation for `output.paths` (@jacksteamdev) +- [#3585](https://github.com/rollup/rollup/pull/3585): Target Node.js v14 instead of v13 in Windows tests (@mangs) +- [#3586](https://github.com/rollup/rollup/pull/3586): Handle default reexports of synthetic named exports over several stages (@lukastaegert) + +## 2.10.7 + +_2020-05-22_ + +### Bug Fixes + +- Handle modules re-exporting namespaces without further own code (#3576) + +### Pull Requests + +- [#3576](https://github.com/rollup/rollup/pull/3576): Fix "cannot read exports of undefined" error (@guybedford) + +## 2.10.6 + +_2020-05-22_ + +### Bug Fixes + +- Fix some issues around class fields (#3580) +- Prevent a maximum call stack error when a called entity references itself in its declaration (#3581) + +### Pull Requests + +- [#3580](https://github.com/rollup/rollup/pull/3580): Update acorn class features (@guybedford) +- [#3581](https://github.com/rollup/rollup/pull/3581): Do not fail when including call arguments of recursively defined variables (@lukastaegert) + +## 2.10.5 + +_2020-05-19_ + +### Bug Fixes + +- Do not remove side-effects that may influence an included default export declaration when side-effects are disabled (#3572) + +### Pull Requests + +- [#3572](https://github.com/rollup/rollup/pull/3572): Observe side-effects in files containing a default export declaration that reexports a variable (@lukastaegert) + +## 2.10.4 + +_2020-05-19_ + +### Bug Fixes + +- Tree-shake unused classes with fields unless there are side-effects in the field declaration (#3569) + +### Pull Requests + +- [#3569](https://github.com/rollup/rollup/pull/3569): Make sure unused classes with fields are tree-shaken if possible (@lukastaegert) + +## 2.10.3 + +_2020-05-18_ + +### Bug Fixes + +- Validate return value of sourcemapPathTransform option (#3561) + +### Pull Requests + +- [#3561](https://github.com/rollup/rollup/pull/3561): Throw error if sourcemapPathTransform-option does not return a string (@Simonwep) + +## 2.10.2 + +_2020-05-15_ + +### Bug Fixes + +- Properly include calls to mutating array methods in certain scenarios (#3559) + +### Pull Requests + +- [#3559](https://github.com/rollup/rollup/pull/3559): Make sure UnknownFooExpressions are included when referenced as return values in a MultiExpression (@lukastaegert) + +## 2.10.1 + +_2020-05-15_ + +### Bug Fixes + +- Do not throw when "undefined" is used as a default export (#3558) + +### Pull Requests + +- [#3558](https://github.com/rollup/rollup/pull/3558): Properly handle default exporting undefined (@lukastaegert) + +## 2.10.0 + +_2020-05-13_ + +### Features + +- Avoid unnecessary empty imports from a facade chunk to the original chunk (#3552) +- Pin facade creation order so that if several user-defined chunks reference the same module, the first always becomes the "actual" chunk while the later ones become facades (#3552) + +### Bug Fixes + +- Do not omit reexports from secondary chunks when creating facades for entry points without hoisting transitive dependencies (#3552) + +### Pull Requests + +- [#3552](https://github.com/rollup/rollup/pull/3552): Avoid unnecessary facade dependency inlining (@guybedford) + +## 2.9.1 + +_2020-05-11_ + +### Bug Fixes + +- Do not create unintended live-bindings or invalid reexports when reexporting global variables (#3550) + +### Pull Requests + +- [#3550](https://github.com/rollup/rollup/pull/3550): Track updates of globals that are exported as default (@lukastaegert) + +## 2.9.0 + +_2020-05-10_ + +### Features + +- Add ids of static and dynamic imports to `this.getModuleInfo` (#3542) +- Provide `getModuleInfo` and `getModuleIds` to `manualChunks` functions (#3542) +- Add nullish coalescing support (#3548) +- Make the rebuild delay in watch mode configurable and set the default to `0` for snappy rebuilds (#3502) +- Add `this.getModuleIds` to the plugin context as future replacement for `this.moduleIds` (#3542) + +### Pull Requests + +- [#3502](https://github.com/rollup/rollup/pull/3502): Configurable build delay (@mattdesl) +- [#3542](https://github.com/rollup/rollup/pull/3542): Extend manualChunks API (@lukastaegert) +- [#3548](https://github.com/rollup/rollup/pull/3548): Support nullish coalescing with tree-shaking (@lukastaegert) + +## 2.8.2 + +_2020-05-07_ + +### Bug Fixes + +- Avoid invalid code when simplifying the body of a shorthand arrow function expression (#3540) + +### Pull Requests + +- [#3540](https://github.com/rollup/rollup/pull/3540): Wrap object expressions in parentheses if they become children of an arrow function expression (@lukastaegert) + +## 2.8.1 + +_2020-05-07_ + +### Bug Fixes + +- Allow using plugins on CLI that are exported as `exports.default` (#3529) +- Do not fail side-effect detection in nested callbacks of builtins (#3539) + +### Pull Requests + +- [#3529](https://github.com/rollup/rollup/pull/3529): Use default named export with plugins (@NotWoods) +- [#3539](https://github.com/rollup/rollup/pull/3539): Track call side-effects both by entity and CallExpression to avoid untracked side-effects in nested calls (@lukastaegert) + +## 2.8.0 + +_2020-05-06_ + +### Features + +- When a dynamically imported chunk contains more exports than the imported module namespace, do not create a facade chunk but an inline namespace (#3535) + +### Bug Fixes + +- Do not execute dynamically imported code before synchronous code in the importing module when generating CommonJS (#3535) + +### Pull Requests + +- [#3535](https://github.com/rollup/rollup/pull/3535): Avoid dynamic facade chunks (@lukastaegert) + +## 2.7.6 + +_2020-04-30_ + +### Bug Fixes + +- Fix a type issue when a default export references a global variable (#3526) + +### Pull Requests + +- [#3526](https://github.com/rollup/rollup/pull/3526): Handles default exporting global variables (@lukastaegert) + +## 2.7.5 + +_2020-04-29_ + +### Bug Fixes + +- Prevent infinite loop when default values of function parameters in a default export contain a slash (#3522) + +### Pull Requests + +- [#3522](https://github.com/rollup/rollup/pull/3522): Avoid infinite loop when finding position for id insertion in default export (@lukastaegert) + +## 2.7.4 + +_2020-04-29_ + +### Bug Fixes + +- Fix an issue where wrong variable names were used when preserving modules (#3521) + +### Pull Requests + +- [#3521](https://github.com/rollup/rollup/pull/3521): Fix and improve default export alias logic (@lukastaegert) + +## 2.7.3 + +_2020-04-27_ + +### Bug Fixes + +- Do not access `__proto__` when running Rollup (#3518) + +### Pull Requests + +- [#3518](https://github.com/rollup/rollup/pull/3518): use acorn-class-fields and acorn-static-class-features from npm (@nitsky) + +## 2.7.2 + +_2020-04-22_ + +### Bug Fixes + +- Prevent an infinite loop when creating separate manual chunks with circular dependencies (#3510) +- Do not fail if "super" is used in the definition of a class field (#3511) +- Throw if a plugin tries to emit a file with an absolute Windows path (#3509) + +### Pull Requests + +- [#3509](https://github.com/rollup/rollup/pull/3509): Ban emitFile via absolute paths on Windows OS (@SASUKE40) +- [#3510](https://github.com/rollup/rollup/pull/3510): Do not fail for circular imports between manual chunks (@lukastaegert) +- [#3511](https://github.com/rollup/rollup/pull/3511): Support "super" in class fields (@lukastaegert) + +## 2.7.1 + +_2020-04-21_ + +### Bug Fixes + +- Use correct path for dynamic imports if `output.paths` is used (#3508) + +### Pull Requests + +- [#3508](https://github.com/rollup/rollup/pull/3508): Respect output.paths in dynamic imports (@lukastaegert) + +## 2.7.0 + +_2020-04-21_ + +### Features + +- Add `preserveEntrySignatures` option to control how exports of entry points are handled (#3498) +- Add `preserveSignature` flag to `this.emitFile` to control exports of emitted chunks (#3498) +- Add `output.minifyInternalExports` option to control if internal exports are minified (#3498) + +### Pull Requests + +- [#3498](https://github.com/rollup/rollup/pull/3498): Add option to configure if entry signatures are preserved (@lukastaegert) + +## 2.6.1 + +_2020-04-12_ + +### Bug Fixes + +- Close watch mode when stdin closes in a non-TTY environment (#3493) + +### Pull Requests + +- [#3493](https://github.com/rollup/rollup/pull/3493): Ensure --watch mode exits correctly when stdin is closed (@jakesgordon) + +## 2.6.0 + +_2020-04-10_ + +### Features + +- Allow regular expressions to declare external modules (#3482) + +### Pull Requests + +- [#3482](https://github.com/rollup/rollup/pull/3482): Allow regular expressions in config.external (@johannes-z) + +## 2.5.0 + +This version is identical to 2.4.0 + +## 2.4.0 + +_2020-04-09_ + +### Features + +- Add support for most private and public class field features (#3488) + +### Bug Fixes + +- Do not replace `this` with `undefined` in class field definitions (#3488) + +### Pull Requests + +- [#3488](https://github.com/rollup/rollup/pull/3488): Rollup class fields support (@guybedford and @lukastaegert) + +## 2.3.5 + +_2020-04-09_ + +### Bug Fixes + +- Never remove labels when tree-shaking is disabled (#3492) + +### Pull Requests + +- [#3492](https://github.com/rollup/rollup/pull/3492): Always use a new inclusion context when including declarations of variables, always inlcude labels when not treeshaking (@lukastaegert) + +## 2.3.4 + +_2020-04-07_ + +### Bug Fixes + +- Handle re-exporting synthetic exports from entry-points (#3319) +- Fix cross-chunk imports of synthetic exports (#3319) +- Handle namespace objects that contain re-exported synthetic namespaces (#3319) + +### Pull Requests + +- [#3319](https://github.com/rollup/rollup/pull/3319): Handle re-exports of synthetic named exports (@manucorporat and @lukastaegert) + +## 2.3.3 + +_2020-04-04_ + +### Bug Fixes + +- Add external namespaces to dynamic namespace objects (#3474) + +### Pull Requests + +- [#3474](https://github.com/rollup/rollup/pull/3474): Support external star exports on namespace objects (@guybedford) + +## 2.3.2 + +_2020-03-31_ + +### Bug Fixes + +- Only warn but do not fail build when a namespace is called as a function (#3475) +- Make sure pre-existing sourcemap comments are also removed when rebuilding using the cache (#3476) + +### Pull Requests + +- [#3475](https://github.com/rollup/rollup/pull/3475): Call namespace error as a warning (@guybedford) +- [#3476](https://github.com/rollup/rollup/pull/3476): Store locations for removed comments in cache (@lukastaegert) + +## 2.3.1 + +_2020-03-30_ + +### Bug Fixes + +- Do not fail if the config file returns an function returning a Promise (#3472) + +### Pull Requests + +- [#3472](https://github.com/rollup/rollup/pull/3472): Fix support for async functions as config (@lukastaegert) + +## 2.3.0 + +_2020-03-29_ + +### Features + +- Do not transpile config files with `.mjs` extension in Node 13+ or `.cjs` extension in any Node version and load them appropriately (#3445) +- Extract helper to load a config file the way rollup does it via `rollup/dist/loadConfigFile` (#3445) + +### Bug Fixes + +- Keep watching the config file if an error occurs during initial load in watch node (#3445) +- Add a helpful error message when using a transpiled config in a repository with "type": "module" (#3445) + +### Pull Requests + +- [#3445](https://github.com/rollup/rollup/pull/3445): Support native ESM configs in Node 13, support untranspiled configs (@lukastaegert) +- [#3468](https://github.com/rollup/rollup/pull/3468): Don't use esm output format alias in the documentation (@vsn4ik) + +## 2.2.0 + +_2020-03-24_ + +### Features + +- Add `renderDynamicImport` hook to rewrite dynamic import expressions (#3449) +- Add information about dynamically imported modules to `this.getModuleInfo` (#3449) + +### Bug Fixes + +- Make file emission work with Uin8Array sources when using Rollup in the browser (#3452) +- Fix types to allow watch to accept an array of configs (#3453) +- Do not strip `.js` extensions from AMD imports when the import is a user-supplied replacement for a non-resolvable dynamic import target (#3453) + +### Pull Requests + +- [#3449](https://github.com/rollup/rollup/pull/3449): Add hook to rewrite dynamic import expressions (@lukastaegert) +- [#3452](https://github.com/rollup/rollup/pull/3452): Avoid the assumption of Buffer in browser envs (@JoviDeCroock) +- [#3453](https://github.com/rollup/rollup/pull/3453): fix types since watch accepts single or array config (@lukeed) +- [#3456](https://github.com/rollup/rollup/pull/3456): fix SystemJS url in tutorial (@guybedford) + +## 2.1.0 + +_2020-03-18_ + +### Features + +- Allow specifying an importer when emitting files to resolve relative ids (#3442) + +### Pull Requests + +- [#3442](https://github.com/rollup/rollup/pull/3442): Add optional `importer` parameter to `this.emitFile` (@lukastaegert) + +## 2.0.6 + +_2020-03-13_ + +### Bug Fixes + +- Do not use file names from different outputs when generating sourcemaps using the `dir` option (#3440) + +### Pull Requests + +- [#3440](https://github.com/rollup/rollup/pull/3440): Use correct file names when writing sourcemaps for multiple outputs (@lukastaegert) + +## 2.0.5 + +_2020-03-12_ + +### Bug Fixes + +- Fix an issue where conditional statements would assume they have the wrong test value (#3438) + +### Pull Requests + +- [#3438](https://github.com/rollup/rollup/pull/3438): Make sure logical expressions always check the left argument for side-effects (@lukastaegert) + +## 2.0.4 + +_2020-03-12_ + +### Bug Fixes + +- Avoid conflicts between namespace imports when preserving modules (#3435) + +### Pull Requests + +- [#3435](https://github.com/rollup/rollup/pull/3435): Deconflict multiple `index` imports for ES format using nested export star statements (@kamranayub) + +## 2.0.3 + +_2020-03-10_ + +### Bug Fixes + +- Add type for this.getCombinedSourcemap to transform context (#3431) + +### Pull Requests + +- [#3377](https://github.com/rollup/rollup/pull/3377): Switch to yargs-parser lib (@jamesgeorge007) +- [#3426](https://github.com/rollup/rollup/pull/3426): Use strict types with PluginDriver (@NotWoods) +- [#3431](https://github.com/rollup/rollup/pull/3431): Add missing type declaration for getCombinedSourcemap (@Anidetrix) +- [#3432](https://github.com/rollup/rollup/pull/3432): Detail how return values from `augmentChunkHash` are used (@jakearchibald) + +## 2.0.2 + +_2020-03-07_ + +### Bug Fixes + +- Make sure the ESM import still works (#3430) + +### Pull Requests + +- [#3430](https://github.com/rollup/rollup/pull/3430): Fix conditional exports again (@lukastaegert) + +## 2.0.1 + +_2020-03-07_ + +### Bug Fixes + +- Reenable importing rollup in Node 13.0 - 13.7 (#3428) + +### Pull Requests + +- [#3428](https://github.com/rollup/rollup/pull/3428): Fix conditional exports in Node 13.0 - 13.7 (@lukastaegert) + +## 2.0.0 + +_2020-03-06_ + +### Breaking Changes + +- Rollup now requires at least Node 10 to run, or a sufficiently modern browser (#3346) +- The file structure of Rollup's ESM builds has changed: + + - The main ESM entry point is now at `rollup/dist/es/rollup.js` instead of `rollup/dist/rollup.es.js` + - The ESM browser build is at `rollup/dist/es/rollup.browser.js` instead of `rollup/dist/rollup.browser.es.js` + + In general, the ESM builds now follow the same naming scheme as the CJS builds but are located in the `rollup/dist/es` subfolder instead of `rollup/dist` (#3391) + +- The "watch.chokidar" option no longer accepts a `boolean` value but only an object of parameters that is passed to the bundled Chokidar instance. Chokidar installations by the user will be ignored in favour of the bundled instance (#3331) +- Modules that are completely tree-shaken will no longer be listed as part of any chunks in `generateBundle` +- The `experimentalOptimizeChunks` and `chunkGroupingSize` options have been removed +- [acorn](https://github.com/acornjs/acorn) plugins can only be used if they accept a passed-in acorn instance instead of importing it themselves. See https://github.com/acornjs/acorn/pull/870#issuecomment-527339830 for what needs to be done to make plugins compatible that do not support this yet (#3391) +- Emitted chunks now have the TypeScript type `Uint8Array` instead of `Buffer`. A `Buffer` can still be used, though (#3395) +- The TypeScript types no longer use ESTree types for AST nodes but a very generic type that does not contain information specific to certain node types (#3395) +- The signature of the `writeBundle` plugin hook has been changed to match `generateBundle`: The bundle object is now passed as second parameter instead of first and the first parameter is the output options (#3361) +- The following plugin hooks have been removed: + - ongenerate: use `generateBundle` instead + - onwrite: use `writeBundle` instead + - transformBundle: use `renderChunk` instead + - transformChunk: use `renderChunk` instead +- You can no longer access `this.watcher` on the plugin context. +- The `transform` hook can no longer return `dependencies`. +- The `treeshake.pureExternalModules` option will now show a deprecation warning when used: use `treeshake.moduleSideEffects: 'no-external'` instead +- Using `import.meta.ROLLUP_ASSET_URL_<..>` and `import.meta.ROLLUP_CHUNK_URL_<..>` in code will now show warnings: use `import.meta.ROLLUP_FILE_URL_<..>` instead +- The `resolveAssetUrl` hook will now show a deprecation warning when used: use `resolveFileUrl` instead +- The following plugin context functions will show warnings when used: + - `this.emitAsset`: use `this.emitFile` + - `this.emitChunk`: use `this.emitFile` + - `this.getAssetFileName`: use `this.getFileName` + - `this.getChunkFileName`: use `this.getFileName` + - `this.isExternal`: use `this.resolve` + - `this.resolveId`: use `this.resolve` +- Directly adding properties to the bundle object in the `generateBundle` is deprecated will show a warning (removing properties is allowed, though): Use `this.emitFile` +- Accessing `chunk.isAsset` on the bundle is deprecated: Use `chunk.type === 'asset'` instead +- The error code for a missing `name` property when targeting UMD has been changed to `MISSING_NAME_OPTION_FOR_IIFE_EXPORT` to emphasize this is needed for the IIFE part of UMD (#3393) + +### Features + +- Rollup now bundles [Chokidar](https://github.com/paulmillr/chokidar) for a better watch experience (#3331) +- Rollup now bundles [acorn](https://github.com/acornjs/acorn) again, removing its only external dependency (#3391) +- Do not consider empty imports from side-effect-free modules for chunking and hoist side-effect imports if necessary (#3369) +- Rollup can now be imported as an ES module in Node via `import {rollup} from 'rollup'`. Note that this relies on Node's experimental [conditional package exports](https://nodejs.org/dist/latest-v13.x/docs/api/esm.html#esm_conditional_exports) feature and is therefore itself experimental (#3391) +- `systemjs` can be used as format alias for `system` (#3381) + +### Bug Fixes + +- Unknown output options now trigger a warning when using the JavaScript API (#3352) +- Rollup will no longer introduce Node types into TypeScript projects that do not use them (#3395) +- Generate correct sourcemaps when tree-shaking occurs in a multi-file bundle (#3423) + +### Pull Requests + +- [#3331](https://github.com/rollup/rollup/pull/3331): Bundle Chokidar (@lukastaegert) +- [#3343](https://github.com/rollup/rollup/pull/3343): Remove experimentalOptimizeChunks (@lukastaegert) +- [#3346](https://github.com/rollup/rollup/pull/3346): Update minimum required Node version to 10 (@lukastaegert) +- [#3352](https://github.com/rollup/rollup/pull/3352): Remove active deprecations (@lukastaegert) +- [#3361](https://github.com/rollup/rollup/pull/3361): Change writeBundle signature to match generateBundle (@lukastaegert) +- [#3369](https://github.com/rollup/rollup/pull/3369): Avoid empty imports from side-effect-free chunks (@lukastaegert) +- [#3381](https://github.com/rollup/rollup/pull/3381): Rename esm to es everywhere, add systemjs alias (@lukastaegert) +- [#3391](https://github.com/rollup/rollup/pull/3391): Bundle acorn, allow importing Rollup as Node ES module, update dependencies (@lukastaegert) +- [#3393](https://github.com/rollup/rollup/pull/3393): Better error code for name-less umd bundle (@rail44) +- [#3395](https://github.com/rollup/rollup/pull/3395): Remove `@types` dependencies (@lukastaegert) +- [#3423](https://github.com/rollup/rollup/pull/3423): Update magic-string and fix sourcemaps (@lukastaegert) + +## 1.32.1 + +_2020-03-06_ + +### Bug Fixes + +- Handle default export detection for AMD and IIFE externals that do not have a prototype (#3420) +- Handle missing whitespace when the else branch of an if-statement is simplified (#3421) +- Mention the importing module when reporting errors for missing named exports (#3401) +- Add code to warning for missing output.name of IIFE bundles (#3372) + +### Pull Requests + +- [#3372](https://github.com/rollup/rollup/pull/3372): Add warning code for missing output.name of IIFE bundle that has export (@rail44) +- [#3401](https://github.com/rollup/rollup/pull/3401): Missing exports errors now print the importing module (@timiyay) +- [#3418](https://github.com/rollup/rollup/pull/3418): Structure lifecycle hooks, add links to build time hooks (@lukastaegert) +- [#3420](https://github.com/rollup/rollup/pull/3420): Update generated code of getInteropBlock() to work with null prototype objects (@jdalton) +- [#3421](https://github.com/rollup/rollup/pull/3421): Avoid invalid code when "else" branch is simplified (@lukastaegert) + +## 1.32.0 + +_2020-02-28_ + +### Features + +- Allow adding plugins on the command line via `--plugin ` (#3379) + +### Pull Requests + +- [#3379](https://github.com/rollup/rollup/pull/3379): introduce CLI --plugin support (@kzc) +- [#3390](https://github.com/rollup/rollup/pull/3390): fix typo: this.addWatchfile (@mistlog) +- [#3392](https://github.com/rollup/rollup/pull/3392): Bump codecov from 3.6.1 to 3.6.5 +- [#3404](https://github.com/rollup/rollup/pull/3404): Update resolveFileUrl docs (@jakearchibald) + +## 1.31.1 + +_2020-02-14_ + +### Bug Fixes + +- Make sure errored files are always re-evaluated in watch mode to avoid an issue in the typescript plugin (#3388) + +### Pull Requests + +- [#3366](https://github.com/rollup/rollup/pull/3366): Correct spelling minifaction to minification (@VictorHom) +- [#3371](https://github.com/rollup/rollup/pull/3371): Adjust bug template to mention REPL.it (@lukastaegert) +- [#3388](https://github.com/rollup/rollup/pull/3388): Run transform hooks again in watch mode on files that errored (@lukastaegert) + +## 1.31.0 + +_2020-01-31_ + +### Features + +- Always disable tree-shaking for asm.js functions to maintain semantics (#3362) + +### Pull Requests + +- [#3362](https://github.com/rollup/rollup/pull/3362): Preserve asm.js code (@lukastaegert) + +## 1.30.1 + +_2020-01-27_ + +### Bug Fixes + +- Do not mistreat static entgry points as dynamic ones when chunking (#3357) +- Resolve a crash when chunking circular dynamic imports (#3357) + +### Pull Requests + +- [#3357](https://github.com/rollup/rollup/pull/3357): Resolve issues with circular dynamic entries (@lukastaegert) + +## 1.30.0 + +_2020-01-27_ + +### Features + +- Do not split chunks when dynamically imported modules import modules that are already loaded by all dynamic importers (#3354) +- Add `hoistTransitiveImports` option to disable hoisting imports of static dependencies into entry chunks (#3353) + +### Bug Fixes + +- Make sure polyfills are always loaded first when each static entry point contains them as first import (#3354) + +### Pull Requests + +- [#3353](https://github.com/rollup/rollup/pull/3353): Add option to avoid hoisting transitive imports (@lukastaegert) +- [#3354](https://github.com/rollup/rollup/pull/3354): Improve chunking algorithm for dynamic imports (@tjenkinson and @lukastaegert) + +## 1.29.1 + +_2020-01-21_ + +### Bug Fixes + +- Avoid crashes for circular reexports when named exports cannot be found (#3350) + +### Pull Requests + +- [#3335](https://github.com/rollup/rollup/pull/3335): Fix typo (@robbinworks) +- [#3342](https://github.com/rollup/rollup/pull/3342): Remove ":" from test file names for Windows and update dependencies (@lukastaegert) +- [#3350](https://github.com/rollup/rollup/pull/3350): Properly handle circular reexports (@lukastaegert) + +## 1.29.0 + +_2020-01-08_ + +### Features + +- Enable top-level await by default (#3089) +- Add typings for watch events (#3302) + +### Bug Fixes + +- Deconflict files that would conflict only on a case-insensitive OS (#3317) +- Do not fail in certain scenarios where a logical expression inside a sequence expression was being directly included (#3327) + +### Pull Requests + +- [#3089](https://github.com/rollup/rollup/pull/3089): Move top-level await out of experimental (@guybedford) +- [#3302](https://github.com/rollup/rollup/pull/3302): Adds type definitions for RollupWatcher events (@NotWoods) +- [#3317](https://github.com/rollup/rollup/pull/3317): Fix module id conflict on a case insensitive OS (@yesmeck) +- [#3327](https://github.com/rollup/rollup/pull/3327): Handle deoptimizations while a node is being included (@lukastaegert) + +## 1.28.0 + +_2020-01-04_ + +### Features + +- Allow piping in stdin via the command line interface (#3312, #3290) +- Allow plugins to mark modules as having syntheticNamedExports for e.g. better CJS interoperability (#3295) +- Ignore variable reassignments in dead code when tree-shaking to remove more unneeded code (#3212) + +### Bug Fixes + +- Properly respect tree-shaken code when generating sourcemaps (#3318) + +### Pull Requests + +- [#3212](https://github.com/rollup/rollup/pull/3212): Handle assignments in dead code (@tjenkinson) +- [#3290](https://github.com/rollup/rollup/pull/3290): Implement stdin input with optional "-" as the file name (@kzc) +- [#3295](https://github.com/rollup/rollup/pull/3295): Add syntheticNamedExports (@manucorporat) +- [#3300](https://github.com/rollup/rollup/pull/3300): Add note about setting `types` in tsconfig file (@tjenkinson) +- [#3303](https://github.com/rollup/rollup/pull/3303): Use ! to assert not-null in TypeScript (@NotWoods) +- [#3312](https://github.com/rollup/rollup/pull/3312): Implement stdin input (@lukastaegert) +- [#3318](https://github.com/rollup/rollup/pull/3318): Update magic-string and other dependencies (@lukastaegert) + +## 1.27.14 + +_2019-12-22_ + +### Bug Fixes + +- Update references to official rollup plugins in error messages (#3297, #3298) + +### Pull Requests + +- [#3286](https://github.com/rollup/rollup/pull/3286): Update link to JavaScript API documentation (@romankaravia) +- [#3294](https://github.com/rollup/rollup/pull/3294): Update deprecated references to the node-resolve plugin in the documentation (@Vlad-Shcherbina) +- [#3297](https://github.com/rollup/rollup/pull/3297): Update references to rollup-plugin-json (@cprecioso) +- [#3298](https://github.com/rollup/rollup/pull/3298): Update references to official rollup plugins (@cprecioso) + +## 1.27.13 + +_2019-12-14_ + +### Bug Fixes + +- Do not truncate environment variable values at the first colon when using the `--environment` option (#3283) + +### Pull Requests + +- [#3283](https://github.com/rollup/rollup/pull/3283): Allow environment variables to contain colons (@tlaverdure) + +## 1.27.12 + +_2019-12-13_ + +### Bug Fixes + +- Prevent invalid AMD or SystemJS code when accessing `import.meta` (#3282) + +### Pull Requests + +- [#3282](https://github.com/rollup/rollup/pull/3282): Always make "module" available for SystemJS and AMD formats if `import.meta` is accessed directly (@lukastaegert) + +## 1.27.11 + +_2019-12-12_ + +### Bug Fixes + +- Resolve a crash due to an infinite loop (#3280) + +### Pull Requests + +- [#3280](https://github.com/rollup/rollup/pull/3280): Prevent infinite deoptimizations (@lukastaegert) + +## 1.27.10 + +_2019-12-11_ + +### Bug Fixes + +- Keep track of function return values in more situations (#3278) + +### Pull Requests + +- [#3278](https://github.com/rollup/rollup/pull/3278): Avoid some unnecessary value tracking deoptimizations (@lukastaegert) + +## 1.27.9 + +_2019-12-07_ + +### Bug Fixes + +- Fix an issue where reexports could be missing when preserving modules (#3273) +- Allow turning of color output via NO_COLOR or FORCE_COLOR=0 environment variables (#3272) + +### Pull Requests + +- [#3272](https://github.com/rollup/rollup/pull/3272): Support either NO_COLOR or FORCE_COLOR=0 to turn off color (@kikonen) +- [#3273](https://github.com/rollup/rollup/pull/3273): Make sure that indirectly reexported modules also become chunk dependencies when preserving modules(@lukastaegert) + +## 1.27.8 + +_2019-12-02_ + +### Bug Fixes + +- Deoptimize objects when a method is called on them to make sure modifications via "this" are observed (#3266) + +### Pull Requests + +- [#3266](https://github.com/rollup/rollup/pull/3266): Workaround for various object literal mutation bugs (@kzc) + +## 1.27.7 + +_2019-12-01_ + +### Bug Fixes + +- Fix a scenario where a reassignments to computed properties were not tracked (#3267) + +### Pull Requests + +- [#3267](https://github.com/rollup/rollup/pull/3267): Fix incomplete computed property deoptimization (@lukastaegert) + +## 1.27.6 + +_2019-11-30_ + +### Bug Fixes + +- Use "auto" export mode by default for all modules when preserving modules (#3265) +- Observe "output.exports" when preserving modules and warn for mixed exports if necessary (#3265) + +### Pull Requests + +- [#3265](https://github.com/rollup/rollup/pull/3265): Use export mode "auto" by default when preserving modules (@lukastaegert) + +## 1.27.5 + +_2019-11-25_ + +### Bug Fixes + +- Make sure namespaces for inlined dynamic imports are treated as variable accesses when deconflicting (#3256) + +### Pull Requests + +- [#3256](https://github.com/rollup/rollup/pull/3256): Avoid name conflicts when inlining dynamic imports nested in functions (@lukastaegert) +- [#3257](https://github.com/rollup/rollup/pull/3257): Update dependencies (@lukastaegert) + +## 1.27.4 + +_2019-11-22_ + +### Bug Fixes + +- Aggregate circular dependency warnings in the CLI (#3249) +- Do not defer non-aggregated handlers in the CLI (#3249) + +### Pull Requests + +- [#3249](https://github.com/rollup/rollup/pull/3249): Fix broken Windows CLI tests (@lukastaegert) +- [#3251](https://github.com/rollup/rollup/pull/3251): Add installation as a separate header (@ashrith-kulai) + +## 1.27.3 + +_2019-11-20_ + +### Bug Fixes + +- Provide better warning when empty chunks are created in a code-splitting scenario (#3244) + +### Pull Requests + +- [#3244](https://github.com/rollup/rollup/pull/3244): Clearer empty chunk warning (@tjenkinson) + +## 1.27.2 + +_2019-11-18_ + +### Bug Fixes + +- Fix an issue where live bindings were not working correctly when using `+=` in SystemJS (#3242) + +### Pull Requests + +- [#3242](https://github.com/rollup/rollup/pull/3242): Export updated assignments when using shorthand update assignment expressions in SystemJS (@lukastaegert) + +## 1.27.1 + +_2019-11-18_ + +### Bug Fixes + +- Fix an issue where code after a switch-statement with removed cases was erroneously not included (#3241) + +### Pull Requests + +- [#3237](https://github.com/rollup/rollup/pull/3237): make `acornOptions` optional in `parse()` in docs (@tjenkinson) +- [#3240](https://github.com/rollup/rollup/pull/3240): Update dependencies and fix vulnerability (@lukastaegert) +- [#3241](https://github.com/rollup/rollup/pull/3241): Do not truncate after switch-statement with removed case (@lukastaegert) + +## 1.27.0 + +_2019-11-12_ + +### Features + +- Add support for output-specific plugins (#3218) +- Reenable parallel output processing when using the CLI (#3218) +- Warn if files are emitted that would overwrite previously emitted files (#3218) + +### Bug Fixes + +- Do not overwrite files emitted in other builds if outputs are generated in parallel (#3218) + +### Pull Requests + +- [#3218](https://github.com/rollup/rollup/pull/3218): Per output plugins (@lukastaegert) + +## 1.26.5 + +_2019-11-11_ + +### Bug Fixes + +- Fix a regression where it was no longer to pass a certain option format to generate (#3223) + +### Pull Requests + +- [#3223](https://github.com/rollup/rollup/pull/3223): Allow passing input options to output (@lukastaegert) + +## 1.26.4 + +_2019-11-09_ + +### Bug Fixes + +- Keep watching known files after a plugin error during the initial build (#3219) + +### Pull Requests + +- [#3216](https://github.com/rollup/rollup/pull/3216): Fix small typo (@kaisermann) +- [#3217](https://github.com/rollup/rollup/pull/3217): Update dependencies and fix security vulnerability (@lukastaegert) +- [#3219](https://github.com/rollup/rollup/pull/3219): Also recover from plugin errors during the initial build (@lukastaegert) + +## 1.26.3 + +_2019-11-02_ + +### Bug Fixes + +- Work around an incompatibility with rollup-plugin-dts (#3211) + +### Pull Requests + +- [#3211](https://github.com/rollup/rollup/pull/3211): Do no fail if the source attribute is `undefined` in an unused named export (@lukastaegert) + +## 1.26.2 + +_2019-10-31_ + +### Bug Fixes + +- Do not create invalid code when using `treeshake: false` and star re-exports (#3209) + +### Pull Requests + +- [#3209](https://github.com/rollup/rollup/pull/3209): Also remove export-all declarations when not tree-shaking (@lukastaegert) + +## 1.26.1 + +_2019-10-31_ + +### Bug Fixes + +- Prevent an issue where outputs would overwrite files emitted by other outputs (#3201) +- Do not throw an error if the config file does not have a .js extension (#3204) + +### Pull Requests + +- [#3201](https://github.com/rollup/rollup/pull/3201): Make the CLI run generate/output in serial (@marijnh) +- [#3204](https://github.com/rollup/rollup/pull/3204): support all config file extensions (.js,.mjs,...) (@arlac77) + +## 1.26.0 + +_2019-10-27_ + +### Features + +- Only warn when no output is provided for an IIFE bundle but still produce valid code (#3181) +- Support reexporting namespaces as a binding (#3193) +- Switch from hash.js to crypto for hashing in the Node build for better performance and support for very large assets (#3194) + +### Bug Fixes + +- Correctly handle chunks reexporting the same namespace as two different bindings (#3193) + +### Pull Requests + +- [#3181](https://github.com/rollup/rollup/pull/3181): Remove the need to provide an output name for IIFE bundles (@bterrier) +- [#3193](https://github.com/rollup/rollup/pull/3193): Add support for "export \* as name from …" (@lukastaegert) +- [#3194](https://github.com/rollup/rollup/pull/3194): Add support for large assets (> 100 MB) (@SebastianNiemann) + +## 1.25.2 + +_2019-10-23_ + +### Bug Fixes + +- Improve performance of bundled UMD code by adding additional parentheses to enforce eager parsing (#3183) +- Improve types to tolerate passing a Rollup config with multiple outputs to `rollup.rollup` (#3184) + +### Pull Requests + +- [#3183](https://github.com/rollup/rollup/pull/3183): Add parentheses to factory function of UMD bundles (@ajihyf) +- [#3184](https://github.com/rollup/rollup/pull/3184): RollupOptions accept output as array (@imcotton) + +## 1.25.1 + +_2019-10-20_ + +### Bug Fixes + +- Handle a situation where code was not included after a switch statement (#3178) +- Handle a situation where code was not included after a do-while loop (#3180) +- Do not fail if different outputs emit the same file (#3175) +- Give access to the original acorn error for parse errors (#3176) + +### Pull Requests + +- [#3175](https://github.com/rollup/rollup/pull/3175): Disable errors for duplicate emitted file names (@marijnh) +- [#3176](https://github.com/rollup/rollup/pull/3176): Add original parser error to rollup error; Update tests (@gribnoysup) +- [#3178](https://github.com/rollup/rollup/pull/3178): Fix switch case not being included correctly (@lukastaegert) +- [#3179](https://github.com/rollup/rollup/pull/3179): Update dependencies (@lukastaegert) +- [#3180](https://github.com/rollup/rollup/pull/3180): Handle conditional breaks in do-while loops with unconditional return (@lukastaegert) + +## 1.25.0 + +_2019-10-18_ + +### Features + +- Remove try-catch if there is no side-effect in the try-block (#3166) +- Omit side-effect-free trailing cases in switch-statements (#3166) +- Remove unused labels (#3170) + +### Bug Fixes + +- Do not remove code after labeled statements that contain a throw or return if the label is used (#3170) +- Prevent invalid code when expressions are simplified that do not follow a white-space character (#3173) +- Do not remove continue statements inside switch statements (#3166) +- Prevent trailing empty lines when tree-shaking inside switch statements (#3166) + +### Pull Requests + +- [#3166](https://github.com/rollup/rollup/pull/3166): Better try statement tree shaking (@lukastaegert) +- [#3170](https://github.com/rollup/rollup/pull/3170): Handle optional control flow in labeled statements, remove unused labels (@lukastaegert) +- [#3173](https://github.com/rollup/rollup/pull/3173): Add missing spaces in certain statements and expressions to avoid invalid code (@lukastaegert) + +## 1.24.0 + +_2019-10-15_ + +### Features + +- Respect `break`, `continue`, `return` and `throw` when tree-shaking to detect dead code (#3153) +- Do treat treat hoisted function declarations as "unknown" when checking for call side-effects (#3153) + +### Bug Fixes + +- Make sure that unknown `import.meta` properties produce valid code in SystemJS (#3152) +- Make sure `treeshake.annotations: false` is respected for class instantiation (#3153) +- Check property access side-effects for class instantiation (#3153) +- Do not suppress break statements inside labeled statements (#3153) + +### Pull Requests + +- [#3152](https://github.com/rollup/rollup/pull/3152): Allow import.meta.\* for systemjs format (@dmail) +- [#3153](https://github.com/rollup/rollup/pull/3153): Get rid of immutable.js and implement tree-shaking for broken control flow (@lukastaegert) + +## 1.23.1 + +_2019-10-05_ + +### Bug Fixes + +- Fix a regression where the node types had a specific minimal version (#3143) + +### Pull Requests + +- [#3143](https://github.com/rollup/rollup/pull/3143): Ensure that types packages have star version ranges (@lukastaegert) + +## 1.23.0 + +_2019-10-03_ + +### Features + +- Add placeholders for extensions when preserving modules (#3116) + +### Pull Requests + +- [#3116](https://github.com/rollup/rollup/pull/3116): Include extensions in preserveModules output filenames for scriptified assets (@Andarist) +- [#3142](https://github.com/rollup/rollup/pull/3142): Fix typo (@tu4mo) + +## 1.22.0 + +_2019-09-29_ + +### Features + +- Add a new "hidden" sourcemap type that generates the map files but omits the sourcemap comment (#3120) +- Generate more efficient code when using `namespaceToStringTag: true` (#3135) +- Make sure namespace objects do not have a prototype (#3136) + +### Bug Fixes + +- Do not ignore side-effectful iterators by always preserving for..of loops for now (#3132) +- Make sure `--context` is observed as a CLI option (#3134) +- Do not require specific versions for @types dependencies (#3131) + +### Pull Requests + +- [#3120](https://github.com/rollup/rollup/pull/3120): Generate sourcemaps but omit the comment (@rohitmohan96) +- [#3131](https://github.com/rollup/rollup/pull/3131): Use asterisk for @types/\* dependencies (@frenzzy) +- [#3132](https://github.com/rollup/rollup/pull/3132): Preserve empty for...of loops (@imatlopez) +- [#3133](https://github.com/rollup/rollup/pull/3133): Update dependencies (@lukastaegert) +- [#3134](https://github.com/rollup/rollup/pull/3134): Wire up --context CLI flag (@tchetwin) +- [#3135](https://github.com/rollup/rollup/pull/3135): Remove Symbol polyfill in module namespaces (@mkubilayk) +- [#3136](https://github.com/rollup/rollup/pull/3136): Set null prototype on namespace objects (@rpamely) + +## 1.21.4 + +_2019-09-16_ + +### Bug Fixes + +- Recognize common browser globals (#3117) +- Do not treat "typeof " as a side-effect (#3117) + +### Pull Requests + +- [#3117](https://github.com/rollup/rollup/pull/3117): Add browser globals to known globals and prevent "typeof" side-effects (@lukastaegert) + +## 1.21.3 + +_2019-09-14_ + +### Bug Fixes + +- Fix a regression where modifying a watched file did not trigger a rebuild (#3112) + +### Pull Requests + +- [#3112](https://github.com/rollup/rollup/pull/3112): Fix .addWatchFile() dependencies failing to invalidate in watch mode (@tivac) + +## 1.21.2 + +_2019-09-09_ + +### Bug Fixes + +- Fix wrong deprecation message to direct to `this.emitFile` instead of `this.emitAsset` + +## 1.21.1 + +_2019-09-09_ + +### Bug Fixes + +- Allow legacy plugins to still add assets directly to the bundle object (#3105) + +### Pull Requests + +- [#3105](https://github.com/rollup/rollup/pull/3105): Allow legacy plugins to still add assets directly to the bundle object (@lukastaegert) + +## 1.21.0 + +_2019-09-08_ + +### Features + +- Respect `output.entryFileNames` when preserving modules (#3088) +- Make accessing unknown globals a side-effect unless this is deactivated via `treeshake.unknownGlobalSideEffects` (#3068) +- Respect global objects when checking for pure global functions (#3068) +- Introduce a `type` to more easily distinguish chunks and assets in the output bundle (#3080) + +### Bug Fixes + +- Recover in watch mode when the initial build fails (#3081) +- Make sure `output.strict` is respected for SystemJS output (#3101) + +### Pull Requests + +- [#3068](https://github.com/rollup/rollup/pull/3068): Make accessing unknown globals a side-effect (@lukastaegert) +- [#3080](https://github.com/rollup/rollup/pull/3080): OutputBundle Tagged union with 'type = chunk|asset' (@askbeka) +- [#3081](https://github.com/rollup/rollup/pull/3081): Watch files onbuild, even if build fails (@mhkeller) +- [#3088](https://github.com/rollup/rollup/pull/3088): Add support for entryFileNames pattern used in combination with preserveModules option (@Andarist) +- [#3101](https://github.com/rollup/rollup/pull/3101): Remove 'use strict'; from systemjs when strict=false (@askbeka) + +## 1.20.3 + +_2019-08-28_ + +### Bug Fixes + +- Make sure file hashes change when a change of the naming pattern leads to a file name change of a dependency (#3083) +- Fix several issues where reexporting an external "default" export could lead to invalid or incorrect code (#3084) + +### Pull Requests + +- [#3078](https://github.com/rollup/rollup/pull/3078): Add github actions workflow config for windows (@shellscape) +- [#3083](https://github.com/rollup/rollup/pull/3083): Properly reflect dependency file names in hash (@lukastaegert) +- [#3084](https://github.com/rollup/rollup/pull/3084): Fix "default" reexport issues in non ESM/System formats (@lukastaegert) + +## 1.20.2 + +_2019-08-25_ + +### Bug Fixes + +- Avoid an issue where circular namespace reexports would crash Rollup (#3074) + +### Pull Requests + +- [#3077](https://github.com/rollup/rollup/pull/3077): Handle namespaces that reexport themselves (@lukastaegert) + +## 1.20.1 + +_2019-08-22_ + +### Bug Fixes + +- Fix an issue where variable names inside dynamic import expressions were not rendered correctly (#3073) +- Fix type definition to allow a single watcher config as well as an array (#3074) + +### Pull Requests + +- [#3073](https://github.com/rollup/rollup/pull/3073): Fix wrong variable name in import expression (@lukastaegert) +- [#3074](https://github.com/rollup/rollup/pull/3074): Fixes type definition on watch and Watcher constructor (@MicahZoltu) + +## 1.20.0 + +_2019-08-21_ + +### Features + +- Add augmentChunkHash plugin hook to be able to reflect changes in renderChunk in the chunk hash (#2921) + +### Bug Fixes + +- Do not mutate the acorn options object (#3051) +- Make sure the order of emitted chunks always reflects the order in which they were emitted (#3055) +- Do not hang when there are strings containing comment-like syntax in some scenarios (#3069) + +### Pull Requests + +- [#2921](https://github.com/rollup/rollup/pull/2921): Add augmentChunkHash plugin hook (@isidrok) +- [#2995](https://github.com/rollup/rollup/pull/2995): Add info on installing locally to docs (@mesqueeb) +- [#3037](https://github.com/rollup/rollup/pull/3037): Refresh pull request labels (@shellscape) +- [#3048](https://github.com/rollup/rollup/pull/3048): Document ROLLUP_WATCH environment variable (@shellscape) +- [#3051](https://github.com/rollup/rollup/pull/3051): Avoid changes to the original options (.acorn) object (@LongTengDao) +- [#3052](https://github.com/rollup/rollup/pull/3052): Minor refactoring: Remove one try-catch (@KSXGitHub) +- [#3053](https://github.com/rollup/rollup/pull/3053): Refactor to use async-await in more places (@KSXGitHub) +- [#3055](https://github.com/rollup/rollup/pull/3055): Provide consistent chunking via a consistent order of entry modules when emitting chunks (@lukastaegert) +- [#3058](https://github.com/rollup/rollup/pull/3058): Remove acorn-bigint and acorn-dynamic-import from bundle (@LongTengDao) +- [#3061](https://github.com/rollup/rollup/pull/3061): Update to acorn@7 (@lukastaegert) +- [#3063](https://github.com/rollup/rollup/pull/3063): Auto-generate license file (@lukastaegert) +- [#3069](https://github.com/rollup/rollup/pull/3069): Prevent infinite loop when scanning for line-breaks and there are comment-like strings (@lukastaegert) + +## 1.19.4 + +_2019-08-07_ + +### Bug Fixes + +- Prevent invalid code when exporting an external namespace (#3034) +- Prevent invalid or non-equivalent code when simplifying expressions in return and throw statements (#3035) + +### Pull Requests + +- [#3034](https://github.com/rollup/rollup/pull/3034): Avoid generating .\* as export (@LongTengDao) +- [#3035](https://github.com/rollup/rollup/pull/3035): Prevent ASI errors for conditional expressions (@lukastaegert) +- [#3036](https://github.com/rollup/rollup/pull/3036): Fix documents to use https, not http (@giraffate) + +## 1.19.3 + +_2019-08-06_ + +### Bug Fixes + +- Fix wrong URLs in error messages (#3033) + +### Pull Requests + +- [#3033](https://github.com/rollup/rollup/pull/3033): Fix wrong URLs in error messages (@giraffate) + +## 1.19.2 + +_2019-08-05_ + +### Bug Fixes + +- Add bin file to package + +## 1.19.1 + +_2019-08-05_ + +### Bug Fixes + +- Remove wrong extension in package.json file (#3031) + +### Pull Requests + +- [#3031](https://github.com/rollup/rollup/pull/3031): Fix wrong extension (@lukastaegert) + +## 1.19.0 + +_2019-08-05_ + +### Features + +- Implement a new unified file emission API for assets and chunks with support for explicit file names (#2999) +- Use the id of the last module in a chunk as base for the chunk name if no better name is available (#3025) +- Use the id of the last module in a chunk as base for the variable name of a chunk in some formats if no better name is available (#2999) + +### Bug Fixes + +- Do not produce invalid variable names if an empty name is chosen for a virtual module (#3026) +- Fix an issue where a module variable name would conflict with a local variable name in some formats (#3020) + +### Pull Requests + +- [#2999](https://github.com/rollup/rollup/pull/2999): Unified file emission api (@lukastaegert) +- [#3020](https://github.com/rollup/rollup/pull/3020): Switch to a code-splitting build and update dependencies (@lukastaegert) +- [#3025](https://github.com/rollup/rollup/pull/3025): Use id of last module in chunk as name base for auto-generated chunks (@lukastaegert) +- [#3026](https://github.com/rollup/rollup/pull/3026): Avoid variable from empty module name be empty (@LongTengDao) + +## 1.18.0 + +_2019-08-01_ + +### Features + +- Add `externalLiveBindings: false` option to optimize code when live bindings are not needed (#3010) + +### Pull Requests + +- [#2997](https://github.com/rollup/rollup/pull/2997): Integrate coverage into CI setup (@lukastaegert) +- [#2998](https://github.com/rollup/rollup/pull/2998): Update readme badges (@lukastaegert) +- [#3010](https://github.com/rollup/rollup/pull/3010): Add option to prevent code for external live bindings (@lukastaegert) + +## 1.17.0 + +_2019-07-15_ + +### Features + +- Allow plugins to access current combined sourcemap in transform hook for coverage instrumentation (#2993) + +### Pull Requests + +- [#2987](https://github.com/rollup/rollup/pull/2987): Fix code fences for link (@johanholmerin) +- [#2989](https://github.com/rollup/rollup/pull/2989): Bump lodash from 4.17.11 to 4.17.14 (@dependabot) +- [#2993](https://github.com/rollup/rollup/pull/2993): Add getCombinedSourceMap in transform plugin context (@billowz) + +## 1.16.7 + +_2019-07-09_ + +### Bug Fixes + +- Fix an issue where exported import.meta properties would lead to invalid code (#2986) + +### Pull Requests + +- [#2985](https://github.com/rollup/rollup/pull/2985): Improve sourcemap types (@jridgewell) +- [#2986](https://github.com/rollup/rollup/pull/2986): Only overwrite content when resolving import.meta properties (@lukastaegert) + +## 1.16.6 + +_2019-07-04_ + +### Bug Fixes + +- Do not pass undefined to resolveDynamicImport for unresolvable template literals (#2984) + +### Pull Requests + +- [#2984](https://github.com/rollup/rollup/pull/2984): Always forward AST nodes for unresolvable dynamic imports (@lukastaegert) + +## 1.16.5 + +_2019-07-04_ + +### Bug Fixes + +- onwarn should still be called when --silent is used (#2982) +- Properly clean up watchers for files that are deleted between builds (#2982) + +### Pull Requests + +- [#2981](https://github.com/rollup/rollup/pull/2981): Do not skip onwarn handler when --silent is used (@lukastaegert) +- [#2982](https://github.com/rollup/rollup/pull/2982): Make tests run on Node 12, fix watcher cleanup issue (@lukastaegert) + +## 1.16.4 + +_2019-07-02_ + +### Bug Fixes + +- Do not show a TypeScript error when providing a location as number to this.warn and this.error (#2974) +- Use the correct TypeScript type for Sourcemap.version (#2976) + +### Pull Requests + +- [#2965](https://github.com/rollup/rollup/pull/2965): Use async readFile in getRollupDefaultPlugin (@kaksmet) +- [#2974](https://github.com/rollup/rollup/pull/2974): Align TS types, docs and implementation for this.warn and this.error (@lukastaegert) +- [#2976](https://github.com/rollup/rollup/pull/2976): Fix sourcemap type and update dependencies (@lukastaegert) + +## 1.16.3 + +_2019-06-29_ + +### Bug Fixes + +- Prevent name conflicts with unused function parameters (#2972) + +### Pull Requests + +- [#2972](https://github.com/rollup/rollup/pull/2972): Deconflict unused parameters (@lukastaegert) + +## 1.16.2 + +_2019-06-22_ + +### Bug Fixes + +- Properly wrap dynamic imports in Promises that can be caught when generating CJS output (#2958) + +### Pull Requests + +- [#2958](https://github.com/rollup/rollup/pull/2958): Make sure errors from dynamic imports can be caught (@lukastaegert) + +## 1.16.1 + +_2019-06-21_ + +### Pull Requests + +- [#2956](https://github.com/rollup/rollup/pull/2956): Add missing CLI docs for strictDeprecations (@lukastaegert) + +## 1.16.0 + +_2019-06-21_ + +### Features + +- Add strictDeprecations option to throw when currently or upcoming deprecated features are used (#2945) +- Keep annotations and comments when simplifying logical and conditional expressions (#2955) + +### Bug Fixes + +- Generate proper namespace objects when dynamically importing external dependencies for AMD or CJS formats (#2954) +- Fix dynamically imported variables not being resolved correctly when importing from an entry chunk with only a default export (#2954) +- Do not reexport default when reexporting a namespace (#2954) + +### Pull Requests + +- [#2945](https://github.com/rollup/rollup/pull/2945): Add option to handle use of features marked for deprecation as errors (@lukastaegert) +- [#2954](https://github.com/rollup/rollup/pull/2954): Improve dynamic import interop (@lukastaegert) +- [#2955](https://github.com/rollup/rollup/pull/2955): Keep annotations and comments when simplifying logical and conditional expressions (@lukastaegert) + +## 1.15.6 + +_2019-06-16_ + +### Bug Fixes + +- No longer use an alternate screen in watch mode to allow scrolling (#2942) +- Prioritize non-external imports over external ones when resolving conflicting namespace re-exports (#2893) + +### Pull Requests + +- [#2893](https://github.com/rollup/rollup/pull/2893): Improve handling of conflicting namespace exports (@aleclarson) +- [#2942](https://github.com/rollup/rollup/pull/2942): Get rid of alternate screen and simplify screen clearing (@lukastaegert) + +## 1.15.5 + +_2019-06-14_ + +### Bug Fixes + +- Do not include any comments for completely tree-shaken files so that `renderedLength === 0` is a reliable check (#2940) +- Do not cause type errors when returning `null` from `resolveId` (#2941) + +### Pull Requests + +- [#2940](https://github.com/rollup/rollup/pull/2940): Completely omit files that do not have any included statements (@lukastaegert) +- [#2941](https://github.com/rollup/rollup/pull/2941): Explicitly allow null as return value for various hooks (@lukastaegert) + +## 1.15.4 + +_2019-06-14_ + +### Bug Fixes + +- Improve how asset and chunk URLs are resolved for UMD, IIFE and CJS output (#2937) + +### Pull Requests + +- [#2937](https://github.com/rollup/rollup/pull/2937): Fix URL resolution to work when the current script contains query parameters (@lukastaegert) + +## 1.15.3 + +_2019-06-13_ + +### Bug Fixes + +- Always reemit assets and chunks from cached transform hooks (#2936) + +### Pull Requests + +- [#2936](https://github.com/rollup/rollup/pull/2936): Fix repeated re-emission of files emitted from a transform hook (@lukastaegert) + +## 1.15.2 + +_2019-06-13_ + +### Bug Fixes + +- Make sure chunks emitted from transform hooks are also emitted for incremental builds in watch mode (#2933) + +### Pull Requests + +- [#2933](https://github.com/rollup/rollup/pull/2933): Reemit chunks emitted from transform hooks (@lukastaegert) + +## 1.15.1 + +_2019-06-11_ + +### Bug Fixes + +- Do not fail when reexporting variables in dynamic entry points from other chunks (#2928) + +### Pull Requests + +- [#2928](https://github.com/rollup/rollup/pull/2928): Handle reexports from dynamic entries across chunk (@lukastaegert) + +## 1.15.0 + +_2019-06-11_ + +### Features + +- Tone down try-catch deoptimization while maintaining polyfill support (#2918) + +### Bug Fixes + +- Handle feature detection with "typeof" for regular expressios (#2916) +- Deoptimize `'' + variable'` type coercion as expression statement for feature detection (#2917) +- Always observe argument side-effects when tree-shaking (#2924) + +### Pull Requests + +- [#2916](https://github.com/rollup/rollup/pull/2916): Deoptimize typeof for regular expression literals to better support es6-shim (@lukastaegert) +- [#2917](https://github.com/rollup/rollup/pull/2917): Support implicit type coercion errors in es5-shim (@lukastaegert) +- [#2918](https://github.com/rollup/rollup/pull/2918): Deoptimize try-catch less radically (@lukastaegert) +- [#2924](https://github.com/rollup/rollup/pull/2924): Do not tree-shake arguments with side-effects (@lukastaegert) + +## 1.14.6 + +_2019-06-10_ + +### Bug Fixes + +- Fix an issue where call arguments were not included in try statements (#2914) + +### Pull Requests + +- [#2914](https://github.com/rollup/rollup/pull/2914): Properly include try statements for each pass when deoptimization is deactivated (@lukastaegert) + +## 1.14.5 + +_2019-06-09_ + +### Bug Fixes + +- Keep external ids unmodified when using the object form of resolveId (#2907) +- Cache dynamic import resolutions when using Rollup cache (#2908) +- Keep all necessary parentheses when tree-shaking call arguments (#2911) + +### Pull Requests + +- [#2906](https://github.com/rollup/rollup/pull/2906): Update dependencies (@lukastaegert) +- [#2907](https://github.com/rollup/rollup/pull/2907): Do not renormalize external ids when using the object form (@lukastaegert) +- [#2908](https://github.com/rollup/rollup/pull/2908): Cache dynamic ids if possible (@lukastaegert) +- [#2911](https://github.com/rollup/rollup/pull/2911): Fix treeshaken parameters around parentheses (@manucorporat) + +## 1.14.4 + +_2019-06-07_ + +### Bug Fixes + +- Do not omit external re-exports for `moduleSideEffects: false` (#2905) + +### Pull Requests + +- [#2905](https://github.com/rollup/rollup/pull/2905): Make sure external re-exports are included for moduleSideEffects: false (@lukastaegert) + +## 1.14.3 + +_2019-06-06_ + +### Bug Fixes + +- Generate correct external imports when importing from a directory that would be above the root of the current working directory (#2902) + +### Pull Requests + +- [#2902](https://github.com/rollup/rollup/pull/2902): Use browser relative path algorithm for chunks (@lukastaegert) + +## 1.14.2 + +_2019-06-05_ + +### Bug Fixes + +- Prevent unnecessary inclusion of external namespace import in certain situations (#2900) + +### Pull Requests + +- [#2900](https://github.com/rollup/rollup/pull/2900): Handle early bind for member expressions (@lukastaegert) + +## 1.14.1 + +_2019-06-05_ + +### Bug Fixes + +- Fix an issue where try-statements were not included properly when a variable declared inside the statement was accessed outside it (#2898) +- Fix an issue where `await` expressions were not included properly (#2899) + +### Pull Requests + +- [#2898](https://github.com/rollup/rollup/pull/2898): Properly include try-catch-statements even if they have already been included in some way (@lukastaegert) +- [#2899](https://github.com/rollup/rollup/pull/2899): Fix unintended early return in await inclusion handling (@lukastaegert) + +## 1.14.0 + +_2019-06-05_ + +### Features + +- Deoptimize code inside and called from try-statements for feature detection (#2892) +- Tree-shake unused call arguments (#2892) + +### Pull Requests + +- [#2892](https://github.com/rollup/rollup/pull/2892): Implement try-statement-deoptimization for feature detection, tree-shake unused arguments (@lukastaegert) + +## 1.13.1 + +_2019-06-01_ + +### Bug Fixes + +- Avoid conflicts between top-level module, require etc. and CommonJS runtimes (#2889) + +### Pull Requests + +- [#2888](https://github.com/rollup/rollup/pull/2888): Enable full TypeScript strict mode (@lukastaegert) +- [#2889](https://github.com/rollup/rollup/pull/2889): Protect all module globals for CJS output from being redefined (@lukastaegert) + +## 1.13.0 + +_2019-05-31_ + +### Features + +- Omit `exports` and `module` from SystemJS wrapper if possible (#2880) +- Try to use the first letters of names when mangling exports (#2885) + +### Bug Fixes + +- Avoid conflicts with local variables when using format specific globals to render dynamic imports and file URLs (#2880) +- Do not produce undefined reexports when reexporting from entry points (#2885) + +### Pull Requests + +- [#2880](https://github.com/rollup/rollup/pull/2880): Deconflict global variables used inside format-specific code (@lukastaegert) +- [#2885](https://github.com/rollup/rollup/pull/2885): Do not produce undefined reexports when reexporting from entry points and refactor chunk linking (@lukastaegert) + +## 1.12.5 + +_2019-05-30_ + +### Pull Requests + +- [#2884](https://github.com/rollup/rollup/pull/2884): Update pluginutils for new micormatch and reduced bundle size (@lukastaegert) + +## 1.12.4 + +_2019-05-27_ + +### Bug Fixes + +- Show correct error stack trace for errors throw in "load" hooks (#2871) + +### Pull Requests + +- [#2875](https://github.com/rollup/rollup/pull/2875): Mention subfolders in docs (@lukastaegert) +- [#2871](https://github.com/rollup/rollup/pull/2871): Reserve error stack information (@LongTengDao) + +## 1.12.3 + +_2019-05-19_ + +### Bug Fixes + +- Prevent duplicate imports when exports are reexported as default exports (#2866) + +### Pull Requests + +- [#2755](https://github.com/rollup/rollup/pull/2755): Enable TypeScript strictNullChecks (@edsrzf) +- [#2866](https://github.com/rollup/rollup/pull/2866): Properly deduplicate reexported default exports (@lukastaegert) + +## 1.12.2 + +_2019-05-17_ + +### Bug Fixes + +- Do not fail when using clearScreen:false in watchMode (#2858) +- Properly resolve star reexports when preserving modules (#2860) + +### Pull Requests + +- [#2858](https://github.com/rollup/rollup/pull/2858): Declare processConfigsErr before use (@humphd) +- [#2860](https://github.com/rollup/rollup/pull/2860): Keep nested exports with preserveModules (@TomCaserta) +- [#2864](https://github.com/rollup/rollup/pull/2864): Cache transitive reexport detection (@lukastaegert) + +## 1.12.1 + +_2019-05-16_ + +### Bug Fixes + +- Extend file name sanitation to also replace "?" and "\*" e.g. when preserving modules with the updated commonjs plugin (#2860) +- Do not ignore module transformer that return an empty string (#2861) + +### Pull Requests + +- [#2860](https://github.com/rollup/rollup/pull/2860): Update to latest plugins and extend file name sanitation (@lukastaegert) +- [#2861](https://github.com/rollup/rollup/pull/2861): Allow transformers to return an empty string (@lukastaegert) + +## 1.12.0 + +_2019-05-15_ + +### Features + +- Add `treeshake.moduleSideEffects` option to allow removing empty imports without a side-effect check (#2844) +- Extend plugin API to allow marking modules as side-effect-free (#2844) +- Extend `this.resolve` plugin context function with an option to skip the `resolveId` hook of the calling plugin (#2844) +- Add `isEntry` flag to `this.getModuleInfo` plugin context function (#2844) +- Distribute Rollup as optimized ES2015 code (#2851) + +### Pull Requests + +- [#2844](https://github.com/rollup/rollup/pull/2844): Add options and hooks to control module side effects (@lukastaegert) +- [#2851](https://github.com/rollup/rollup/pull/2851): Switch to ES2015 output (@lukastaegert) + +## 1.11.3 + +_2019-05-05_ + +### Bug Fixes + +- Quote es3 keywords in namespace objects (#2825) + +### Pull Requests + +- [#2825](https://github.com/rollup/rollup/pull/2825): Add es3 support for namespace object import (@sormy) + +## 1.11.2 + +_2019-05-04_ + +### Bug Fixes + +- Prevent a crash when handling circular namespace exports (#2836) + +### Pull Requests + +- [#2836](https://github.com/rollup/rollup/pull/2836): Make sure circular `export * from X` does not stack overflow (@Swatinem) + +## 1.11.1 + +_2019-05-04_ + +### Bug Fixes + +- Fix an issue where rendered exports were reported as "removed" in the bundle information (#2835) + +### Pull Requests + +- [#2835](https://github.com/rollup/rollup/pull/2835): Fix `removedExports` to correctly track the exported item (@Swatinem) + +## 1.11.0 + +_2019-05-03_ + +### Features + +- Add `emitChunk` plugin context function to emit additional entry chunks that can be referenced from the code (#2809) +- Allow `manualChunks` to be a function (#2831) +- Omit `.js` extensions in AMD imports to make sure an AMD `baseUrl` would work (#2809) +- Automatically use the name of the imported module as a base for dynamically imported chunks (#2809) +- Add `resolveFileUrl` plugin hook to replace `resolveAssetUrl` and handle emitted chunks as well (#2809) +- Add `resolve` plugin hook to replace `resolveId` and `isExternal` that returns an object (#2829) +- Allow `resolveDynamicImport` to return an `{id, external}` object to also resolve unresolvable dynamic imports to a module (#2829) + +### Bug Fixes + +- Do not create invalid code if a dynamic import contains nothing but reexports (#2809) +- Do not fail if modules that define a manual chunk depend on each other (#2809) +- Do not fail if a module that defines a manual chunk is the dependency of a module defining a different manual chunk (#2809) +- No longer fail for unnamed duplicate entry points but combine them (#2809) +- Always return `string | null` from `this.resolveId` even if some `resolveId` hooks return objects (#2829) +- Show proper warnings when `resolveDynamicImport` resolves to a non-external module that does not exist (#2829) + +### Pull Requests + +- [#2809](https://github.com/rollup/rollup/pull/2809): Add hook for dynamic entry chunk emission (@lukastaegert) +- [#2821](https://github.com/rollup/rollup/pull/2821): Fix syntax error in documentation (@FFxSquall) +- [#2829](https://github.com/rollup/rollup/pull/2829): Improve id resolution (@lukastaegert) +- [#2831](https://github.com/rollup/rollup/pull/2831): Allow manualChunks to be a function (@lukastaegert) +- [#2832](https://github.com/rollup/rollup/pull/2832): Improve `generateBundle` documentation (@lukastaegert) +- [#2833](https://github.com/rollup/rollup/pull/2833): Update dependencies (@lukastaegert) + +## 1.10.1 + +_2019-04-19_ + +### Bug Fixes + +- Invalid options.format values will now trigger a helpful error (#2813) + +### Pull Requests + +- [#2812](https://github.com/rollup/rollup/pull/2812): Minor documentation update (@dnalborczyk) +- [#2813](https://github.com/rollup/rollup/pull/2813): Catch invalid options.format values (@marijnh) +- [#2816](https://github.com/rollup/rollup/pull/2816): Update all dependencies to fix security issues (@lukastaegert) + +## 1.10.0 + +_2019-04-11_ + +### Features + +- Improve generated code to polyfill `import.meta.url` (#2785) +- Add plugin hook to configure handling of `import.meta` (#2785) +- Improve generated code when accessing URLs of emitted assets (#2796) +- Add plugin hook to configure the generated code when accessing URLs of emitted assets (#2796) + +### Bug Fixes + +- No longer resolve assets to their parent URL in some cases (#2796) + +### Pull Requests + +- [#2785](https://github.com/rollup/rollup/pull/2785): Refactor handling of import.meta.url and add option to configure behaviour (@lukastaegert) +- [#2796](https://github.com/rollup/rollup/pull/2796): Improve and fix asset emission (@lukastaegert) + +## 1.9.3 + +_2019-04-10_ + +### Bug Fixes + +- Simplify return expressions that are evaluated before the surrounding function is bound (#2803) + +### Pull Requests + +- [#2803](https://github.com/rollup/rollup/pull/2803): Handle out-of-order binding of identifiers to improve tree-shaking (@lukastaegert) + +## 1.9.2 + +_2019-04-10_ + +### Bug Fixes + +- Allowing replacing `output.file` with `output.dir` in the `outputOptions` hook (#2802) + +### Pull Requests + +- [#2802](https://github.com/rollup/rollup/pull/2802): Observe modified output options in bundle.write (@lukastaegert) + +## 1.9.1 + +_2019-04-10_ + +### Bug Fixes + +- Make sure inline comments in dynamic imports are preserved (#2797) + +### Pull Requests + +- [#2797](https://github.com/rollup/rollup/pull/2797): Emit inline comments inside dynamic import (@manucorporat) + +## 1.9.0 + +_2019-04-05_ + +### Features + +- Add built-in support for bigint (#2789) + +### Pull Requests + +- [#2789](https://github.com/rollup/rollup/pull/2789): Ship with bigint support built-in (@danielgindi) +- [#2791](https://github.com/rollup/rollup/pull/2791): Use shared extractAssignedNames from rollup-pluginutils (@lukastaegert) +- [#2792](https://github.com/rollup/rollup/pull/2792): Test that rollup-plugin-commonjs works with preserveModules (@lukastaegert) + +## 1.8.0 + +_2019-04-02_ + +### Features + +- Support `module` as alias for `esm` and `commonjs` for `cjs` to match Node (#2783) + +### Pull Requests + +- [#2782](https://github.com/rollup/rollup/pull/2782): Inline interopDefault in config loading (@guybedford) +- [#2783](https://github.com/rollup/rollup/pull/2783): Support Node-style format aliases (@guybedford) + +## 1.7.4 + +_2019-03-28_ + +### Bug Fixes + +- Improve TypeScript type of the treeshaking options (#2779) + +### Pull Requests + +- [#2779](https://github.com/rollup/rollup/pull/2779): Make all properties in TreeshakingOptions optional (@ndelangen) + +## 1.7.3 + +_2019-03-24_ + +### Bug Fixes + +- Use getters when re-exporting live-bindings (#2765) + +### Pull Requests + +- [#2765](https://github.com/rollup/rollup/pull/2765): Support exporting live-bindings from other chunks or external dependencies (@lukastaegert) + +## 1.7.2 + +_2019-03-24_ + +### Bug Fixes + +- Make sure relative external ids are resolved correctly (#2774) + +### Pull Requests + +- [#2774](https://github.com/rollup/rollup/pull/2774): Resolve relative external ids (@lukastaegert) + +## 1.7.1 + +_2019-03-24_ + +### Bug Fixes + +- Prevent invalid code when exporting several hundred identifiers from a chunk (#2768) +- Do not wrongly deconflict labels (#2776) + +### Pull Requests + +- [#2768](https://github.com/rollup/rollup/pull/2768): Sanitize shortened internal export names (@lukastaegert) +- [#2769](https://github.com/rollup/rollup/pull/2769): Update dependencies and fix security issue (@lukastaegert) +- [#2776](https://github.com/rollup/rollup/pull/2776): Do not treat break labels as identifiers (@lukastaegert) + +## 1.7.0 + +_2019-03-20_ + +### Features + +- Sort chunk exports by name for greater consistency (#2757) + +### Bug Fixes + +- Fix a situation where tree-shakeable code would not be removed in an indeterminate manner (#2757) + +### Pull Requests + +- [#2757](https://github.com/rollup/rollup/pull/2757): Sort modules before binding, sort exports (@lukastaegert) + +## 1.6.1 + +_2019-03-20_ + +### Bug Fixes + +- Avoid name clashes of unused default exports when tree-shaking is false (#2758) +- Do not crash when generating SystemJS bundles containing array patterns with member expressions (#2760) + +### Pull Requests + +- [#2758](https://github.com/rollup/rollup/pull/2758): Make sure unused default exports are deconflicted when tree-shaking is false (@lukastaegert) +- [#2760](https://github.com/rollup/rollup/pull/2760): Handle member expressions in array patterns (@lukastaegert) + +## 1.6.0 + +_2019-03-08_ + +### Features + +- Add plugin hook to modify output options (#2736) + +### Pull Requests + +- [#2736](https://github.com/rollup/rollup/pull/2736): Add hook for modifying OutputOptions (@Comandeer) + +## 1.5.0 + +_2019-03-07_ + +### Features + +- Allow resolving to a different id while marking it as external at the same time (#2734) + +### Pull Requests + +- [#2734](https://github.com/rollup/rollup/pull/2734): Allow resolveId to return an object (@lukastaegert) + +## 1.4.2 + +_2019-03-07_ + +### Bug Fixes + +- Respect variable identity of exports when hashing (#2741) +- Resolve a situations where a variable was imported twice with the same name (#2737) + +### Pull Requests + +- [#2741](https://github.com/rollup/rollup/pull/2741): Fix hashing when different variable are exported using the same name (@lukastaegert) +- [#2737](https://github.com/rollup/rollup/pull/2737): Fix duplicate imports with conflicting names (@lukastaegert) + +## 1.4.1 + +_2019-03-04_ + +### Bug Fixes + +- Do not treat the import target "" as external by default (#2733) + +### Pull Requests + +- [#2733](https://github.com/rollup/rollup/pull/2733): Do not treat the import target "" as external by default (@LongTengDao) + +## 1.4.0 + +_2019-03-01_ + +### Features + +- Add option to change the name of the dynamic import function to allow polyfilling it (#2723) + +### Pull Requests + +- [#2723](https://github.com/rollup/rollup/pull/2723): Add dynamicImportFunction option (@keithamus) + +## 1.3.3 + +_2019-03-01_ + +### Bug Fixes + +- Fix performance regression when handling long chains of calls to property methods (#2732) + +### Pull Requests + +- [#2730](https://github.com/rollup/rollup/pull/2730): Order types, interfaces, classes, and object members (@lukastaegert) +- [#2732](https://github.com/rollup/rollup/pull/2732): Take chunk export mode into account when reexporting default (@lukastaegert) + +## 1.3.2 + +_2019-02-27_ + +### Bug Fixes + +- Allow ids of default exported classes to be exported separately (#2728) + +### Pull Requests + +- [#2728](https://github.com/rollup/rollup/pull/2728): Update dependencies (@lukastaegert) + +## 1.3.1 + +_2019-02-27_ + +### Bug Fixes + +- Correctly reexport the default export from entry chunks (#2727) + +### Pull Requests + +- [#2727](https://github.com/rollup/rollup/pull/2727): Take chunk export mode into account when reexporting default (@lukastaegert) + +## 1.3.0 + +_2019-02-26_ + +### Features + +- Treeshake call expressions prefixed with UglifyJS style `@__PURE__` annotations (#2429) + +### Pull Requests + +- [#2429](https://github.com/rollup/rollup/pull/2429): Add support for /_#**PURE**_/ comments (@conartist6 and @lukastaegert) + +## 1.2.5 + +_2019-02-26_ + +### Bug Fixes + +- Store external ids reported by plugins in watch mode (#2718) + +### Pull Requests + +- [#2718](https://github.com/rollup/rollup/pull/2718): Incremental external (@andreas-karlsson) + +## 1.2.4 + +_2019-02-26_ + +### Bug Fixes + +- Fix an issue where a variable was imported twice under the same name (#2715) + +### Pull Requests + +- [#2715](https://github.com/rollup/rollup/pull/2715): Deduplicate imports referencing default exports and their original variables (@lukastaegert) + +## 1.2.3 + +_2019-02-23_ + +### Bug Fixes + +- Use correct path when rendering dynamic imports where the entry module is empty (#2714) + +### Pull Requests + +- [#2714](https://github.com/rollup/rollup/pull/2714): Properly render dynamic imports when imported module is empty (@lukastaegert) + +## 1.2.2 + +_2019-02-19_ + +### Bug Fixes + +- Fix wrong external imports when using the `paths` options only for some outputs (#2706) + +### Pull Requests + +- [#2706](https://github.com/rollup/rollup/pull/2706): Always recreate paths for external modules (@lukastaegert) + +## 1.2.1 + +_2019-02-17_ + +### Bug Fixes + +- Fix ESM version of Rollup (#2705) + +### Pull Requests + +- [#2705](https://github.com/rollup/rollup/pull/2705): Fix ESM version of Rollup (@lukastaegert) + +## 1.2.0 + +_2019-02-17_ + +### Features + +- Fewer renamed variables due to a completely reimplemented deconflicting logic (#2689) + +### Bug Fixes + +- Respect rendered and tree-shaken exports when determining chunk hashes (#2695) +- Fix an error when dynamic imports end up in the same chunk as one of their importees (#2677) +- Do not generate invalid code when expressions containing IIFEs are simplified (#2696) +- Do not throw an error when more than ten bundles are watched (#2700) +- Treat re-exported globals in a spec-compliant way (#2691) +- Fix issues related to wrongly renamed variables (#2689) +- Do not throw an error if config files contain non-default exports (#2673) +- Improve type of `RollupOutput.output` to guarantee at least one chunk (#2679) + +### Pull Requests + +- [#2673](https://github.com/rollup/rollup/pull/2673): Allow config files to have non-default exports (@swansontec) +- [#2677](https://github.com/rollup/rollup/pull/2677): Prevent final resolution and facade creation for inlined dynamic imports (@Rich-Harris and @lukastaegert) +- [#2679](https://github.com/rollup/rollup/pull/2679): Improve type of `RollupOutput.output` (@MattiasBuelens) +- [#2689](https://github.com/rollup/rollup/pull/2689): Reimplement variable deconflicting logic (@lukastaegert) +- [#2691](https://github.com/rollup/rollup/pull/2691): Fix CI issues and update acorn dependency (@lukastaegert) +- [#2693](https://github.com/rollup/rollup/pull/2693): Fix typo in export-globals test (@MattiasBuelens) +- [#2695](https://github.com/rollup/rollup/pull/2695): Respect rendered exports when generating chunk hashes (@lukastaegert) +- [#2696](https://github.com/rollup/rollup/pull/2696): Correctly render function expression inside simplified expression statements (@lukastaegert) +- [#2700](https://github.com/rollup/rollup/pull/2700): Add a fix for MaxListenersExceededWarning (@luwes) +- [#2703](https://github.com/rollup/rollup/pull/2703): Update rollup-pluginutils (@lukastaegert) + +## 1.1.2 + +_2019-01-21_ + +### Bug Fixes + +- Tree-shaken dynamic imports no longer leave behind `undefined` entries in the bundle information (#2663) +- Dynamic imports in dynamically imported files could lead to crashes and would not always create new chunks (#2664) + +### Pull Requests + +- [#2663](https://github.com/rollup/rollup/pull/2663): Do not include tree-shaken dynamic imports in bundle information (@lukastaegert) +- [#2664](https://github.com/rollup/rollup/pull/2664): Properly handle dynamic imports declared in dynamically imported files (@everdimension) + +## 1.1.1 + +_2019-01-19_ + +### Bug Fixes + +- Make sure object prototype methods are not considered to be falsy when tree-shaking (#2652) + +### Pull Requests + +- [#2652](https://github.com/rollup/rollup/pull/2652): Make sure object prototype methods are not considered to be falsy (@lukastaegert) +- [#2654](https://github.com/rollup/rollup/pull/2654): Use correct signature for `this.setAssetSource` in docs (@everdimension) +- [#2656](https://github.com/rollup/rollup/pull/2656): Swap descriptions for `[extname]` and `[ext]` in docs (@tivac) + +## 1.1.0 + +_2019-01-09_ + +### Features + +- Make `this.meta` available from the `options` plugin hook (#2642) +- Add a new `writeBundle` plugin hook that is called _after_ all files have been written (#2643) + +### Bug Fixes + +- Make sure the `acorn` import of the bundled non-ESM acorn plugins is correctly translated to ESM (#2636) +- Make sure input options are actually passed to the `buildStart` hook (#2642) + +### Pull Requests + +- [#2636](https://github.com/rollup/rollup/pull/2636): Improve how acorn is imported, update dependencies (@lukastaegert) +- [#2642](https://github.com/rollup/rollup/pull/2642): Make this.meta available in options hook, pass input options to buildStart (@lukastaegert) +- [#2643](https://github.com/rollup/rollup/pull/2643): Implement writeBundle hook (@lukastaegert) + +## 1.0.2 + +_2019-01-05_ + +### Bug Fixes + +- Make sure the transform hook is always reevaluated when a file watched by the hook changes (#2633) +- Fix a crash when generating hashes for tree-shaken dynamic imports (#2638) +- Fix a crash and some inconsistencies when using the acorn-bigint plugin (#2640) + +### Pull Requests + +- [#2633](https://github.com/rollup/rollup/pull/2633): Document `this.addWatchFile` and make sure it also declares transform dependencies (@lukastaegert) +- [#2635](https://github.com/rollup/rollup/pull/2635): Make sure `code` is optional in warning type (@lukastaegert) +- [#2638](https://github.com/rollup/rollup/pull/2638): Do not fail when generating hashes for tree-shaken dynamic imports (@lukastaegert) +- [#2640](https://github.com/rollup/rollup/pull/2640): Always treat bigints as unknown (@lukastaegert) +- [#2641](https://github.com/rollup/rollup/pull/2641): Make sure all CLI options are listed in the summary (@lukastaegert) + +## 1.0.1 + +_2019-01-03_ + +### Bug Fixes + +- Properly handle reexporting an external default export for non-ESM targets when using named exports mode (#2620) +- Do not (wrongly) re-declare input options in the merged `RollupOptions` type (#2622) + +### Pull Requests + +- [#2620](https://github.com/rollup/rollup/pull/2620): Fixed issue with reexporting default as default with `{exports: named, interop: true}` options (@Andarist) +- [#2622](https://github.com/rollup/rollup/pull/2622): Simplify RollupOptions (@Kinrany) +- [#2627](https://github.com/rollup/rollup/pull/2627): Show how to skip imports for optional plugins (@chris-morgan) + +## 1.0.0 + +_2018-12-28_ + +### Breaking Changes + +- Several (mostly deprecated) options have been removed or renamed (#2293, #2409): + - banner -> output.banner + - dest -> output.file + - entry -> input + - experimentalCodeSplitting -> now always active + - experimentalDynamicImport -> now always active + - experimentalPreserveModules -> preserveModules + - exports -> output.exports + - extend -> output.extend + - footer -> output.footer + - format -> output.format + - freeze -> output.freeze + - globals -> output.globals + - indent -> output.indent + - interop -> output.interop + - intro -> output.intro + - load -> use plugin API + - moduleName -> output.name + - name -> output.name + - noConflict -> output.noConflict + - output.moduleId -> output.amd.id + - outro -> output.outro + - paths -> output.paths + - preferConst -> output.preferConst + - pureExternalModules -> treeshake.pureExternalModules + - resolveExternal -> use plugin API + - resolveId -> use plugin API + - sourcemap -> output.sourcemap + - sourceMap -> output.sourcemap + - sourceMapFile -> output.sourcemapFile + - strict -> output.strict + - targets -> use output as an array + - transform -> use plugin API + - useStrict -> output.strict +- In general, output options can no longer be used as input options (#2409) +- `bundle.generate` and `bundle.write` now return a new format (#2293) +- Several plugin hooks have become deprecated and will display warnings when used (#2409): + - transformBundle + - transformChunk + - ongenerate + - onwrite +- Plugin transform dependencies are deprecated in favour of using the `this.addWatchFile` plugin context function (#2409) +- Accessing `this.watcher` in plugin hooks is deprecated in favour of the `watchChange` plugin hook and the `this.addWatchFile` plugin context function (#2409) +- Using dynamic import statements will by default create a new chunk unless `inlineDynamicImports` is used (#2293) +- Rollup now uses acorn@6 which means that acorn plugins must be compatible with this version; acorn is now external for non-browser builds to make plugins work (#2293) + +### Features + +- The `--dir` ClI option can now be aliased as `-d` (#2293) +- The `--input` option now supports named entry points via `=` (#2293) + +### Bug Fixes + +- Both the `--input` option as well as the default CLI option now support named inputs (#2293) + +### Pull Requests + +- [#2293](https://github.com/rollup/rollup/pull/2293): Unify code paths for 1.0 relase and update documentation (@guybedford and @lukastaegert) +- [#2409](https://github.com/rollup/rollup/pull/2409): Remove old deprecated features and add new deprecation warnings (@guybedford) +- [#2486](https://github.com/rollup/rollup/pull/2486): Upgrade to acorn 6 (@marijnh) +- [#2611](https://github.com/rollup/rollup/pull/2611): Fix hook's name in test description (@Andarist) +- [#2612](https://github.com/rollup/rollup/pull/2612): Fix a self-contradicting comment in the docs (@LongTengDao) + +## 0.68.2 + +_2018-12-23_ + +### Bug Fixes + +- Do not assume hoisted variables to have been initialized (#2607) + +### Pull Requests + +- [#2607](https://github.com/rollup/rollup/pull/2607): Fix an issues where hoisted variables were assumed to have been initialized (@lye) + +## 0.68.1 + +_2018-12-19_ + +### Bug Fixes + +- Fix an issue with UMD wrappers where a variable is used without being defined (#2600) + +### Pull Requests + +- [#2600](https://github.com/rollup/rollup/pull/2600): Fix UMD and IIFE wrapper issues and add comprehensive functional wrapper tests (@lukastaegert) + +## 0.68.0 + +_2018-12-16_ + +### Breaking Changes + +- `optimizeChunks` is renamed to `experimentalOptimizeChunks` to reflect this feature is not production-ready yet (#2575) + +### Features + +- Plugins can iterate all module ids via `this.moduleIds` (#2565) +- Plugins can get graph information about a module via `this.getModuleInfo(id)` (#2565) +- Plugins and JS API users get more information about the generated chunks: `dynamicImports`, `facadeModuleId`, `isDynamicEntry`, `name` (#2575) +- Tree-shaken dynamic imports will no longer create chunks or influence chunking in any way (#2575) +- Dynamic imports will no longer follow the `entryFileNames` but the `chunkFileNames` property reflecting those are solely internally used (#2575) +- If there are chunk naming conflicts, entry chunks will always take precedence (#2575) +- If an entry facade is created, only the facade chunk is marked as `isEntry` (#2575) +- Dynamic chunks will only be marked as `isEntry` if they are actually entry chunks as well; thus there is now a 1-to-1 correspondence between modules listed in `input` and chunks marked as `isEntry` (#2575) +- Chunks no longer contain imports for variables that are tree-shaken in the chunk but used in other chunks (#2584) +- Chunks will always import re-exported variables directly from the chunk where they are originally exported from (#2584) +- Null characters will be pruned from chunk ids to allow for virtually created chunks and make `rollup-plugin-multi-entry` compatible with code-splitting and thus the upcoming 1.0 version (#2590) +- Simplify the UMD wrapper code as much as possible, especially if there are no exports (#2594) +- The UMD wrapper will now work in strict mode by checking for `self` before `this` when determining the global variable (#2594) + +### Bug Fixes + +- If a facade is created for a dynamic entry point, this facade will be imported instead of the facaded chunk (#2575) +- Manual chunks that include multiple entry points will have proper facades created for all entry points if necessary (#2575) +- If missing exports are shimmed, the shim variable will not be global but created on a per-module basis and is deconflicted with variables having the same name (#2584) +- Missing export shims work properly in SystemJS (#2584) +- `preserveModules` now handles dynamic namespace imports (#2584) +- Fix chunk execution order in certain scenarios (#2584) +- Exports and assignments using destructuring syntax will properly update the exported variables when generating SystemJS output (#2587) +- Hashes in chunk names will now also take dynamic imports into account (#2596) + +### Pull Requests + +- [#2565](https://github.com/rollup/rollup/pull/2565): Provide module graph information on the plugin context (@samccone) +- [#2575](https://github.com/rollup/rollup/pull/2575): Extend bundle information, tree-shake dynamic imports, fix dynamic import facade creation, support manual chunks with multiple entry points, make `optimizeChunks` experimental (@lukastaegert) +- [#2577](https://github.com/rollup/rollup/pull/2577): Update dependencies (@lukastaegert) +- [#2584](https://github.com/rollup/rollup/pull/2584): Prune tree-shaken chunk imports, fix missing export shimming, support dynamic namespaces when preserving modules, improve chunk execution order (@lukastaegert) +- [#2587](https://github.com/rollup/rollup/pull/2587): Support exports using destructuring declarations and assignments in SystemJS (@lukastaegert) +- [#2590](https://github.com/rollup/rollup/pull/2590): Make sure chunk ids do not contain invalid characters to allow for chunks to correspond to virtual modules (@lukastaegert) +- [#2594](https://github.com/rollup/rollup/pull/2594): Simplify UMD wrapper code and make sure it works in strict mode (@lukastaegert) +- [#2596](https://github.com/rollup/rollup/pull/2596): Take both static and dynamic dependencies into account when calculating hashes (@lukastaegert) + +## 0.67.4 + +_2018-12-03_ + +### Bug Fixes + +- Prevent corrupt source maps for files with very long lines (#2571) + +### Pull Requests + +- [#2571](https://github.com/rollup/rollup/pull/2571): Fix an issue with long lines in sourcemaps (@mislav) + +## 0.67.3 + +_2018-11-17_ + +### Bug Fixes + +- Make sure the ESM browser build is actually published to npm (#2560) +- Throw proper error when using `inlineDynamicImports` with `experimentalPreserveModules` (#2560) + +### Pull Requests + +- [#2552](https://github.com/rollup/rollup/pull/2552): Properly include ESM browser build in package (@lukastaegert) +- [#2560](https://github.com/rollup/rollup/pull/2560): Show proper error when using `inlineDynamicImports` with `experimentalPreserveModules` (@clarkdo) + +## 0.67.2 + +_2018-11-17_ + +### Bug Fixes + +- Prevent crash when not returning sourcemaps from `renderChunk` plugin hook (#2558) + +### Pull Requests + +- [#2558](https://github.com/rollup/rollup/pull/2558): Prevent crash when not returning sourcemaps from `renderChunk` (@kyle1320) + +## 0.67.1 + +_2018-11-11_ + +### Bug Fixes + +- Deconflict CLI entry points with same name but on different paths if no explicit naming is used (#2548) + +### Pull Requests + +- [#2548](https://github.com/rollup/rollup/pull/2548): Deconflict CLI entry points with same name but on different paths if no explicit naming is used (@lukastaegert) + +## 0.67.0 + +_2018-11-04_ + +### Breaking Changes + +none + +### Features + +- Do not resolve external dynamic imports via plugins to match the logic for static external imports again (#2505) +- Support virtual modules created by plugins when preserving modules (#2511) +- Add new `output.sourcemapExcludeSources` option to exclude the actual sources from sourcemaps (#2531) + +### Bug Fixes + +- Fix TypeScript type for sourcemaps (#2507) +- Fix order of external and inter-chunk imports to match the proper execution order (#2508) +- Do not tree-shake children of unknown nodes to e.g. properly handle do-expressions via acorn plugin (#2510) +- Prevent memory leak when using the bundle as cache (#2522) +- Fix mis-placed semicolons for certain SystemJS exports (#2529) + +### Pull Requests + +- [#2505](https://github.com/rollup/rollup/pull/2505): Do not resolve external dynamic imports via plugins (@lukastaegert) +- [#2507](https://github.com/rollup/rollup/pull/2507): Fix public sourcemap type (@aMarCruz) +- [#2508](https://github.com/rollup/rollup/pull/2508): Improve execution order of chunks and externals (@lukastaegert) +- [#2510](https://github.com/rollup/rollup/pull/2510): Do not tree-shake children of unknown nodes to e.g. properly handle do-expressions via acorn plugin (@devsnek) +- [#2511](https://github.com/rollup/rollup/pull/2511): Create chunks for virtual modules when preserving modules (@lukastaegert) +- [#2522](https://github.com/rollup/rollup/pull/2522): Prevent memory leak when using the bundle as cache (@kyle1320) +- [#2529](https://github.com/rollup/rollup/pull/2529): Fix mis-placed semicolons for certain SystemJS exports (@kyle1320) +- [#2531](https://github.com/rollup/rollup/pull/2531): add `sourcemapExcludeSources` option to exclude the source content from sourcemaps (@kitsonk) + +## 0.66.6 + +_2018-10-10_ + +- Properly deconflict function and class declaration ids of reassigned default exports ([#2502](https://github.com/rollup/rollup/pull/2502)) + +## 0.66.5 + +_2018-10-09_ + +- Remove cache from memory once no longer needed ([#2496](https://github.com/rollup/rollup/pull/2496)) +- Provide better error message when reexporting external namespace reexports ([#2499](https://github.com/rollup/rollup/pull/2499)) + +## 0.66.4 + +_2018-10-04_ + +- Fix links in warnings and errors ([#2471](https://github.com/rollup/rollup/pull/2471)) + +## 0.66.3 + +_2018-10-03_ + +- Detect side-effects in string.replace function arguments ([#2476](https://github.com/rollup/rollup/pull/2476)) +- Make sure chunk ids are assigned before creating output bundle ([#2483](https://github.com/rollup/rollup/pull/2483)) +- Use proper plugin name in error ([#2470](https://github.com/rollup/rollup/pull/2470)) +- Update TypeScript version and fix type errors ([#2488](https://github.com/rollup/rollup/pull/2488)) + +## 0.66.2 + +_2018-09-21_ + +- Add additional information to parse errors messages in JSON and other non-JS files ([#2466](https://github.com/rollup/rollup/pull/2466)) + +## 0.66.1 + +_2018-09-19_ + +- Ignore falsy plugins ([#2464](https://github.com/rollup/rollup/pull/2464)) +- Switch back to official TypeScript plugin ([#2465](https://github.com/rollup/rollup/pull/2465)) + +## 0.66.0 + +_2018-09-16_ + +- Support ES2019 optional catch bindings ([#2455](https://github.com/rollup/rollup/pull/2455)) +- Add option to transform paths within sourcemaps ([#2430](https://github.com/rollup/rollup/pull/2430)) +- Add renderStart and renderEnd plugin hooks ([#2438](https://github.com/rollup/rollup/pull/2438)) +- Expose ESM browser build and minify browser builds ([#2437](https://github.com/rollup/rollup/pull/2437) +- Associate hoisted variables in function bodys with function parameters ([#2456](https://github.com/rollup/rollup/pull/2456)) +- Fix issue when deconflicting variables used as pattern defaults ([#2446](https://github.com/rollup/rollup/pull/2446)) +- Properly deconflict default exported class and function expressions with ids ([#2458](https://github.com/rollup/rollup/pull/2458)) +- Faster internal test builds ([#2457](https://github.com/rollup/rollup/pull/2457)) +- Switch to rollup-plugin-typescript2 ([#2460](https://github.com/rollup/rollup/pull/2460)) +- Fix internal "perf" script ([#2433](https://github.com/rollup/rollup/pull/2433)) +- Test that errors are passed to the buildEnd hook ([#2450](https://github.com/rollup/rollup/pull/2450)) + +## 0.65.2 + +_2018-09-05_ + +- Prevent watch mode memory leak ([#2441](https://github.com/rollup/rollup/pull/2441)) + +## 0.65.1 + +_2018-09-05_ + +- Prevent globbing when using chokidar ([#2432](https://github.com/rollup/rollup/pull/2432)) + +## 0.65.0 + +_2018-08-25_ + +- Refactor and unify plugin system ([#2382](https://github.com/rollup/rollup/pull/2382)) +- Implement plugin cache API ([#2389](https://github.com/rollup/rollup/pull/2389)) +- Add watchChange plugin hook to watch changed files, deprecate asset dependencies ([#2405](https://github.com/rollup/rollup/pull/2405)) +- Refine asset handling ([#2369](https://github.com/rollup/rollup/pull/2369)) +- Implement `renderChunk` hook to replace `transformChunk` and `transformBundle` hooks ([#2406](https://github.com/rollup/rollup/pull/2406)) +- Add rollup version to plugin context ([#2394](https://github.com/rollup/rollup/pull/2394)) +- Do not resume stdin in watch mode to fix it for Lerna users ([#2410](https://github.com/rollup/rollup/pull/2410)) +- Allow `[format]` placeholder for id generation ([#2387](https://github.com/rollup/rollup/pull/2387)) +- Always log error stacks even when a code frame is given ([#2417](https://github.com/rollup/rollup/pull/2417)) +- Do not test module ids starting with `\0` as external ([#2400](https://github.com/rollup/rollup/pull/2400)) +- Fix tracing of namespace variables ([#2408](https://github.com/rollup/rollup/pull/2408)) +- Fix re-tracing of namespace variables ([#2420](https://github.com/rollup/rollup/pull/2420)) +- Properly wrap comment annotations in SystemJS exports ([#2408](https://github.com/rollup/rollup/pull/2408)) +- Fix renaming of destructured parameters ([#2419](https://github.com/rollup/rollup/pull/2419)) +- Do not display version in watch mode when using `--silent` ([#2392](https://github.com/rollup/rollup/pull/2392)) +- Make `cacheExpiry` an experimental option for now ([#2401](https://github.com/rollup/rollup/pull/2401)) +- Lint test configs on commit ([#2402](https://github.com/rollup/rollup/pull/2402)) +- Add code of conduct ([#2388](https://github.com/rollup/rollup/pull/2388)) +- Move to CircleCI ([#2390](https://github.com/rollup/rollup/pull/2390)) +- Update pull request template ([#2404](https://github.com/rollup/rollup/pull/2404)) + +## 0.64.1 + +_2018-08-07_ + +- Do not render initializers of hoisted variables in dead branches ([#2384](https://github.com/rollup/rollup/pull/2384)) + +## 0.64.0 + +_2018-08-07_ + +- Print memory consumption together with performance timings ([#2370](https://github.com/rollup/rollup/pull/2370)) +- Enable plugins to mark imports as external by returning false for resolveId ([#2351](https://github.com/rollup/rollup/pull/2351)) +- Always retain empty manual chunks ([#2362](https://github.com/rollup/rollup/pull/2362)) +- Ensure CLI warnings are shown on errors and add error for external id collisions ([#2334](https://github.com/rollup/rollup/pull/2334)) +- Remove unnecessary dependency, update dependencies, fix linting of test config ([#2376](https://github.com/rollup/rollup/pull/2376)) +- Add targeted Github issue templates ([#2356](https://github.com/rollup/rollup/pull/2356)) + +## 0.63.5 + +_2018-08-01_ + +- Ensure onwrite plugin hooks execute in sequence ([#2364](https://github.com/rollup/rollup/pull/2364)) +- Always warn when no name is provided for a global module ([#2359](https://github.com/rollup/rollup/pull/2359)) +- Add utility type for user created plugins ([#2355](https://github.com/rollup/rollup/pull/2355)) +- Remove deprecated es6 format from types ([#2349](https://github.com/rollup/rollup/pull/2349)) +- Mark inlineDynamicImports as optional in types ([#2348](https://github.com/rollup/rollup/pull/2348)) + +## 0.63.4 + +_2018-07-20_ + +- Use turbocolor instead of chalk ([#2339](https://github.com/rollup/rollup/pull/2339)) + +## 0.63.3 + +_2018-07-20_ + +- Handle expressions where "in" and "instanceof" are applied to primitive values ([#2344](https://github.com/rollup/rollup/pull/2344)) + +## 0.63.2 + +_2018-07-18_ + +- Fix bind order in for-of loops ([#2338](https://github.com/rollup/rollup/pull/2338)) + +## 0.63.1 + +_2018-07-18_ + +## 0.63.0 + +_2018-07-17_ + +- Fix many tree-shaking related issues ([#2315](https://github.com/rollup/rollup/pull/2315)) +- Add experimental support for top-level await ([#2235](https://github.com/rollup/rollup/pull/2235)) +- Prevent duplicate version printout in watch mode ([#2325](https://github.com/rollup/rollup/pull/2325)) +- Respect error frames provided by plugins ([#2309](https://github.com/rollup/rollup/pull/2309)) +- Add `esm` format alias to types ([#2327](https://github.com/rollup/rollup/pull/2327)) +- Further unify internal test setup ([#2329](https://github.com/rollup/rollup/pull/2329)) + +## 0.62.0 + +_2018-06-27_ + +- Add option to automatically shim missing exports ([#2118](https://github.com/rollup/rollup/pull/2118)) +- Inline dynamic imports that are also imported statically and only used in a single chunk ([#2295](https://github.com/rollup/rollup/pull/2295)) +- Handle caching and invalidation of assets ([#2267](https://github.com/rollup/rollup/pull/2267)) +- Fix plugin related types ([#2299](https://github.com/rollup/rollup/pull/2299)) + +## 0.61.2 + +_2018-06-23_ + +- Improve watcher error handling, only rebuild invalidated outputs ([#2296](https://github.com/rollup/rollup/pull/2296)) +- Update dependencies, make watcher more stable ([#2297](https://github.com/rollup/rollup/pull/2297)) + +## 0.61.1 + +_2018-06-21_ + +- Do not try to deconflict "undefined" ([#2291](https://github.com/rollup/rollup/pull/2291)) +- Properly track values for loop interator declarations and reassigned namespaces, add smoke test ([#2292](https://github.com/rollup/rollup/pull/2292)) + +## 0.61.0 + +_2018-06-20_ + +- Declare file dependencies via transform plugin hooks ([#2259](https://github.com/rollup/rollup/pull/2259)) +- Handle undefined values when evaluating conditionals ([#2264](https://github.com/rollup/rollup/pull/2264)) +- Handle known undefined properties when evaluating conditionals ([#2265](https://github.com/rollup/rollup/pull/2265)) +- Access watch events via the plugin context ([#2261](https://github.com/rollup/rollup/pull/2261)) +- Add option to suppress `__esModule` flag in output ([#2287](https://github.com/rollup/rollup/pull/2287)) +- Fix issue when re-declaring variables, track reassignments in more cases ([#2279](https://github.com/rollup/rollup/pull/2279)) +- Add VSCode debug settings ([#2276](https://github.com/rollup/rollup/pull/2276)) + +## 0.60.7 + +_2018-06-14_ + +- Fix typing issue ([#2269](https://github.com/rollup/rollup/pull/2269)) + +## 0.60.6 + +_2018-06-14_ + +- Track mutations of included virtual arrays ([#2263](https://github.com/rollup/rollup/pull/2263)) +- Update readme ([#2266](https://github.com/rollup/rollup/pull/2266)) + +## 0.60.5 + +_2018-06-14_ + +- Track deep reassignments of global and exported variables and improve performance ([#2254](https://github.com/rollup/rollup/pull/2254)) + +## 0.60.4 + +_2018-06-13_ + +- Properly handle initially uninitialized exports and exports of globals in SystemJS output ([#2258](https://github.com/rollup/rollup/pull/2258)) + +## 0.60.3 + +_2018-06-13_ + +- Fix types to allow watching an array of outputs ([#2262](https://github.com/rollup/rollup/pull/2262)) + +## 0.60.2 + +_2018-06-11_ + +- Permit setting an asset's source in `generateBundle` ([#2256](https://github.com/rollup/rollup/pull/2256)) +- Add automatic linting ([#2242](https://github.com/rollup/rollup/pull/2242)) + +## 0.60.1 + +_2018-06-07_ + +- Fix plugin regressions ([#2246](https://github.com/rollup/rollup/pull/2246)) +- Avoid conflicts for large numbers of variables ([#2244](https://github.com/rollup/rollup/pull/2244)) + +## 0.60.0 + +_2018-06-06_ + +- New plugin hooks: transformChunk, buildStart, buildEnd; extended plugin context with warn, error, resolveId, isExternal, emitAsset, setAssetSource and getAssetFileName available to any hook ([#2208](https://github.com/rollup/rollup/pull/2208)) +- [BREAKING] Deprecate the `legacy` option and thus IE8 support ([#2141](https://github.com/rollup/rollup/pull/2141)) +- Detect more known extensions and load .mjs without extension ([#2211](https://github.com/rollup/rollup/pull/2211)) +- Add compact output mode ([#2151](https://github.com/rollup/rollup/pull/2151)) +- Significantly improve sourcemap generation performance ([#2228](https://github.com/rollup/rollup/pull/2228)) +- Enable naming SystemJS modules ([#2028](https://github.com/rollup/rollup/pull/2028)) +- Do not use alternate screen if clearScreen is set in watch mode ([#2125](https://github.com/rollup/rollup/pull/2125)) +- Allow object input form for code-splitting in watch mode ([#2217](https://github.com/rollup/rollup/pull/2217)) +- Track reassignments of methods of exports from outside ([#2240](https://github.com/rollup/rollup/pull/2240)) +- Preserve id of default exported functions and classes ([#2234](https://github.com/rollup/rollup/pull/2234)) +- Add semicolons after default exports ([#2209](https://github.com/rollup/rollup/pull/2209)) +- Fix build problems on Windows ([#2232](https://github.com/rollup/rollup/pull/2232)) +- Display install size in readme ([#2196](https://github.com/rollup/rollup/pull/2196)) +- Improve preserve modules test ([#2236](https://github.com/rollup/rollup/pull/2236)) + +## 0.59.4 + +_2018-05-28_ + +- Fix performance regression when many return statements are used ([#2218](https://github.com/rollup/rollup/pull/2218)) + +## 0.59.3 + +_2018-05-24_ + +- Fix reassignment tracking for constructor parameters ([#2214](https://github.com/rollup/rollup/pull/2214)) + +## 0.59.2 + +_2018-05-21_ + +- Fix reassignment tracking in for-in loops ([#2205](https://github.com/rollup/rollup/pull/2205)) + +## 0.59.1 + +_2018-05-16_ + +- Fix infinite recursion when determining literal values of circular structures ([#2193](https://github.com/rollup/rollup/pull/2193)) +- Fix invalid code when simplifying expressions without spaces ([#2194](https://github.com/rollup/rollup/pull/2194)) + +## 0.59.0 + +_2018-05-15_ + +- Tree-shake statically analysable dynamic conditionals ([#2167](https://github.com/rollup/rollup/pull/2167)) +- Do not emit empty chunks when code-splitting or empty files when preserving modules ([#2128](https://github.com/rollup/rollup/pull/2128)) +- Support `import.meta.url` ([#2164](https://github.com/rollup/rollup/pull/2164)) +- Add `esm` format alias ([#2102](https://github.com/rollup/rollup/pull/2102)) +- Use alphanumeric base64 characters when deconflicting variables ([#2188](https://github.com/rollup/rollup/pull/2188)) +- Improve handling of external modules imported as both default and named imports ([#2136](https://github.com/rollup/rollup/pull/2136)) +- Properly deconflict named imports from other chunks ([#2177](https://github.com/rollup/rollup/pull/2177)) +- Fix an issue with namespaces containing reexports ([#2157](https://github.com/rollup/rollup/pull/2157)) +- Fix an issue with with incorrectly mapped default exports when code-splitting CJS or AMD modules ([#2178](https://github.com/rollup/rollup/pull/2178)) +- Fix an issue with wrong paths of relative external imports ([#2160](https://github.com/rollup/rollup/pull/2160)) +- Fix an issue when using default exports and `interop: false` ([#2149](https://github.com/rollup/rollup/pull/2149)) +- Fix in issue with invalid syntax in SystemJS output ([#2187](https://github.com/rollup/rollup/pull/2187)) +- Fix an issue when tree-shaking call expressions and reassigned variables ([#2186](https://github.com/rollup/rollup/pull/2186)) +- Fix file paths in source maps ([#2161](https://github.com/rollup/rollup/pull/2161)) +- Fix wrong file name in error message ([#2137](https://github.com/rollup/rollup/pull/2137)) +- Always use npm 5 on CI ([#2185](https://github.com/rollup/rollup/pull/2185)) + +## 0.58.2 + +_2018-04-23_ + +- Fix rendering of certain statically resolvable if statements ([#2146](https://github.com/rollup/rollup/pull/2146)) + +## 0.58.1 + +_2018-04-18_ + +- Fix comment detection ([#2129](https://github.com/rollup/rollup/pull/2129)) + +## 0.58.0 + +_2018-04-16_ + +- Support individual chunk names with optional content hashes ([#2068](https://github.com/rollup/rollup/pull/2068)) +- Support manually created chunks ([#2084](https://github.com/rollup/rollup/pull/2084)) +- Automatically import deep dependencies when code splitting for better performance ([#2073](https://github.com/rollup/rollup/pull/2073)) +- Automatically minify internal export/import names for esm and system output ([#2087](https://github.com/rollup/rollup/pull/2087)) +- Add option to automatically merge small chunks ([#2090](https://github.com/rollup/rollup/pull/2090)) +- Significantly improve tree-shaking performance ([#2119](https://github.com/rollup/rollup/pull/2119)) +- Enable tree-shaking for logical expressions ([#2098](https://github.com/rollup/rollup/pull/2098)) +- Rework external types and reduce type related dependencies ([#2108](https://github.com/rollup/rollup/pull/2108)) +- Support parallel dependency resolution ([#2116](https://github.com/rollup/rollup/pull/2116)) +- Improve deprecation handling ([#2076](https://github.com/rollup/rollup/pull/2076)) +- Enable `--perf` timings in watch mode ([#2065](https://github.com/rollup/rollup/pull/2065)) +- Improve performance timers ([#2111](https://github.com/rollup/rollup/pull/2111)) +- Improve error handling for plugins ([#2100](https://github.com/rollup/rollup/pull/2100)) +- Improve error when using `--dir` in a single file build ([#2123](https://github.com/rollup/rollup/pull/2123)) +- Do not warn for external imports that are unused due to tree-shaking ([#2124](https://github.com/rollup/rollup/pull/2124)) +- Update mixed export warning message ([#2107](https://github.com/rollup/rollup/pull/2107)) +- Remove duplicate badges from readme ([#2083](https://github.com/rollup/rollup/pull/2083)) +- Update readme examples ([#2086](https://github.com/rollup/rollup/pull/2086)) + +## 0.57.1 + +_2018-03-17_ + +- Improve sourcemap generation performance ([#2062](https://github.com/rollup/rollup/pull/2062)) +- Add reserved config option namespace and improve CLI interface ([#2063](https://github.com/rollup/rollup/pull/2063)) +- Fix issue with default exported function and class expressions ([#2059](https://github.com/rollup/rollup/pull/2059)) +- Replace `forEach` with faster `for` loops in some places ([#2064](https://github.com/rollup/rollup/pull/2064)) + +## 0.57.0 + +_2018-03-15_ + +- Add option to preserve the module structure instead of bundling ([#1922](https://github.com/rollup/rollup/pull/1922)) +- Enable watch mode when code-splitting ([#2035](https://github.com/rollup/rollup/pull/2035)) +- Optionally pass CLI commands to config file ([#1926](https://github.com/rollup/rollup/pull/1926)) +- Option to add correct `.toString` tags to namespaces ([#2041](https://github.com/rollup/rollup/pull/2041)) +- Option and scripts to display performance timings ([#2045](https://github.com/rollup/rollup/pull/2045)) +- Fixes for exported or early accessed namespaces + improved namespace indentation ([#2041](https://github.com/rollup/rollup/pull/2041)) +- Include missing TypeScript dependencies ([#1965](https://github.com/rollup/rollup/pull/1965)) +- Add #\_PURE annotation to frozen namespaces ([#2044](https://github.com/rollup/rollup/pull/2044)) +- Improve sourcemap and tree-shaking performance ([#2052](https://github.com/rollup/rollup/pull/2052)) +- Inline sourcemap lookups and make rollup smaller ([#2055](https://github.com/rollup/rollup/pull/2055)) +- Use updated magic-string types ([#2057](https://github.com/rollup/rollup/pull/2057)) +- [BREAKING] Revert class id preservation from #2025 ([#2048](https://github.com/rollup/rollup/pull/2048)) +- [BREAKING] Refactor missing export plugin hook ([#1987](https://github.com/rollup/rollup/pull/1987)) + +## 0.56.5 + +_2018-03-07_ + +- Preserve ids when deconflicting classes ([#2025](https://github.com/rollup/rollup/pull/2025)) +- Fix an issue with re-exported namespace imports ([#2034](https://github.com/rollup/rollup/pull/2034)) +- Prevent an infinite loop when binding member expressions ([#1963](https://github.com/rollup/rollup/pull/1963)) +- Convert code style via prettier ([#2031](https://github.com/rollup/rollup/pull/2031)) +- Fix links in documentation ([#2026](https://github.com/rollup/rollup/pull/2026)) + +## 0.56.4 + +_2018-03-05_ + +- Make rollup builds reproducible ([#2024](https://github.com/rollup/rollup/pull/2024)) +- Improve error handling for source maps ([#2012](https://github.com/rollup/rollup/pull/2012)) +- Properly handle SystemJS default exports without semicolons ([#2019](https://github.com/rollup/rollup/pull/2019)) +- Properly handle importing the same variable several times when code-splitting ([#2020](https://github.com/rollup/rollup/pull/2020)) +- Improve re-export tracing ([#2021](https://github.com/rollup/rollup/pull/2021)) +- Apply "prettier" on commit ([#2017](https://github.com/rollup/rollup/pull/2017)) +- Automatically clean up outdated tests ([#2009](https://github.com/rollup/rollup/pull/2009)) +- Add SystemJS output to form tests ([#2022](https://github.com/rollup/rollup/pull/2022)) +- Improve internal build configuration ([#2016](https://github.com/rollup/rollup/pull/2016)) + +## 0.56.3 + +_2018-02-25_ + +- Fix issues around default exports and module facades ([#2001](https://github.com/rollup/rollup/pull/2001)) +- Improve and fix internal chunk interface ([#1994](https://github.com/rollup/rollup/pull/1994)) +- Fix superfluous semicolons added after declarations ([#1999](https://github.com/rollup/rollup/pull/1999)) +- Improve code-splitting tests ([#1990](https://github.com/rollup/rollup/pull/1990)) + +## 0.56.2 + +_2018-02-19_ + +- Fix handling of reassigned default exports ([#1975](https://github.com/rollup/rollup/pull/1975)) +- Fix handling of renamed exports in entry points ([#1977](https://github.com/rollup/rollup/pull/1977)) +- Update internal TypeScript version ([#1980](https://github.com/rollup/rollup/pull/1980)) +- Omit compiled source files from published types ([#1981](https://github.com/rollup/rollup/pull/1981)) +- Fix example in readme file ([#1984](https://github.com/rollup/rollup/pull/1984)) +- Fix non-replaced dynamic imports in non-ESM output ([#1985](https://github.com/rollup/rollup/pull/1985)) + +## 0.56.1 + +_2018-02-16_ + +- Fix regression when rendering switch statements ([#1971](https://github.com/rollup/rollup/pull/1971)) + +## 0.56.0 + +_2018-02-15_ + +- Update to ECMAScript 2018 ([#1953](https://github.com/rollup/rollup/pull/1953)) +- Rework tree-shaking rendering algorithm ([#1949](https://github.com/rollup/rollup/pull/1949)) +- Tree-shake pure prototype calls on literals ([#1916](https://github.com/rollup/rollup/pull/1916)) +- Expose AST parser to plugins ([#1945](https://github.com/rollup/rollup/pull/1945)) +- Fix namespace re-export deconflicting ([#1960](https://github.com/rollup/rollup/pull/1960)) +- Allow globals to be re-exported ([#1959](https://github.com/rollup/rollup/pull/1959)) +- Fix internal performance timers ([#1966](https://github.com/rollup/rollup/pull/1966)) + +## 0.55.5 + +_2018-02-10_ + +- Remove OpenCollective dependency ([#1915](https://github.com/rollup/rollup/pull/1915)) + +## 0.55.4 + +_2018-02-09_ + +- Improve name deconflicting of external variables ([#1930](https://github.com/rollup/rollup/pull/1930)) +- Improve re-export handling ([#1947](https://github.com/rollup/rollup/pull/1947)) +- Mark preserveSymlinks option as optional ([#1939](https://github.com/rollup/rollup/pull/1939)) +- Enable code-splitting tests to check directory structures ([#1924](https://github.com/rollup/rollup/pull/1924)) +- Improve TypeScript definition test ([#1954](https://github.com/rollup/rollup/pull/1954)) + +## 0.55.3 + +_2018-02-01_ + +- Remove OpenCollective dependency ([#1915](https://github.com/rollup/rollup/pull/1915)) + +## 0.55.2 + +_2018-02-01_ + +- Add option to not follow symlinks ([#1819](https://github.com/rollup/rollup/pull/1819)) +- Fix crash in windows shell ([#1928](https://github.com/rollup/rollup/pull/1928)) +- Fix and test for external TypeScript errors ([#1903](https://github.com/rollup/rollup/pull/1903)) +- Activate OpenCollective ([#1915](https://github.com/rollup/rollup/pull/1915)) +- Optimize CI scripts ([#1921](https://github.com/rollup/rollup/pull/1921)) + +## 0.55.1 + +_2018-01-26_ + +- Improve dynamic import workflow ([#1907](https://github.com/rollup/rollup/pull/1907)) +- Properly handle multiple dynamic imports of the same module ([#1911](https://github.com/rollup/rollup/pull/1911)) +- Fix import specifier deshadowing ([#1912](https://github.com/rollup/rollup/pull/1912)) +- Allow plugin load hook to return an empty string ([#1908](https://github.com/rollup/rollup/pull/1908)) +- Let onwarn handler accept strings ([#1905](https://github.com/rollup/rollup/pull/1905)) + +## 0.55.0 + +_2018-01-23_ + +- Support code splitting ([#1841](https://github.com/rollup/rollup/pull/1841)) +- Support SystemJS as output format ([#1897](https://github.com/rollup/rollup/pull/1897)) +- Allow injecting acorn plugins ([#1857](https://github.com/rollup/rollup/pull/1857)) +- Add `missingExport` plugin hook ([#1845](https://github.com/rollup/rollup/pull/1845)) +- No longer parse config files via bublé ([#1899](https://github.com/rollup/rollup/pull/1899)) +- Use externally maintained dynamic import acorn plugin ([#1891](https://github.com/rollup/rollup/pull/1891)) +- Fix an error message ([#1886](https://github.com/rollup/rollup/pull/1886)) +- Refactor internal rendering options ([#1900](https://github.com/rollup/rollup/pull/1900)) +- Extract internal path resolution ([#1879](https://github.com/rollup/rollup/pull/1879)) +- Extract internal bundle option handling ([#1880](https://github.com/rollup/rollup/pull/1880)) +- Add import description type ([#1884](https://github.com/rollup/rollup/pull/1884)) +- Clean up watch options types ([#1860](https://github.com/rollup/rollup/pull/1860)) +- Clean up some tests ([#1888](https://github.com/rollup/rollup/pull/1888)) + +## 0.54.1 + +_2018-01-17_ + +- Fix TypeScript errors in emitted type definitions ([#1871](https://github.com/rollup/rollup/pull/1871)) + +## 0.54.0 + +_2018-01-12_ + +- Automatically inline locally resolvable dynamic imports ([#1816](https://github.com/rollup/rollup/pull/1816)) +- Preserve directives in function bodies ([#1856](https://github.com/rollup/rollup/pull/1856)) +- Refactor an error notification ([#1846](https://github.com/rollup/rollup/pull/1846)) +- Refactor a wrong import ([#1863](https://github.com/rollup/rollup/pull/1863)) +- Improve emitted TypeScript definitions ([#1864](https://github.com/rollup/rollup/pull/1864)) +- Refactor unused import ([#1866](https://github.com/rollup/rollup/pull/1866)) + +## 0.53.4 + +_2018-01-10_ + +- More type cleanup ([#1858](https://github.com/rollup/rollup/pull/1858)) +- Use chalks internal helper to detect if colors should be used ([#1853](https://github.com/rollup/rollup/pull/1853)) +- Refactor entity handling to use interfaces ([#1840](https://github.com/rollup/rollup/pull/1840)) +- Use immutable.js internal types ([#1844](https://github.com/rollup/rollup/pull/1844)) +- Ship `TypeScript` declaration files ([#1837](https://github.com/rollup/rollup/pull/1837)) + +## 0.53.3 + +_2018-01-02_ + +- Use correct name when re-exporting from external modules ([#1794](https://github.com/rollup/rollup/pull/1794)) +- Disable warnings when `resolveId` returns false ([#1825](https://github.com/rollup/rollup/pull/1825)) + +## 0.53.2 + +_2017-12-30_ + +- Properly handle output arrays in the JavaScript API ([#1827](https://github.com/rollup/rollup/pull/1827)) + +## 0.53.1 + +_2017-12-28_ + +- Properly deprecate more config options ([#1812](https://github.com/rollup/rollup/pull/1812)) +- Pass output options to `transformBundle` plugin hook ([#1813](https://github.com/rollup/rollup/pull/1813)) + +## 0.53.0 + +_2017-12-22_ + +- Experimental dynamic import support ([#1790](https://github.com/rollup/rollup/pull/1790)) +- Unify config validation ([#1805](https://github.com/rollup/rollup/pull/1805)) + +## 0.52.3 + +_2017-12-19_ + +- Properly hoist default exported functions in more situations ([#1799](https://github.com/rollup/rollup/pull/1799)) +- Allow plugin transformations to not overwrite source maps by returning null ([#1797](https://github.com/rollup/rollup/pull/1797)) +- Provide more parameters to "external" handler ([#1792](https://github.com/rollup/rollup/pull/1792)) + +## 0.52.2 + +_2017-12-15_ + +- No longer ignore side-effects in JSON.parse and JSON.stringify ([#1785](https://github.com/rollup/rollup/pull/1785)) +- Updated links in warnings ([#1776](https://github.com/rollup/rollup/pull/1776)) +- No longer prevent self-imports ([#1777](https://github.com/rollup/rollup/pull/1777)) +- Properly hoist default exported functions ([#1787](https://github.com/rollup/rollup/pull/1787)) +- Prevent corruption when re-exporting default exports ([#1765](https://github.com/rollup/rollup/pull/1765)) + +## 0.52.1 + +_2017-12-05_ + +- Improve deprecation warnings ([#1765](https://github.com/rollup/rollup/pull/1765)) +- Properly use stdin ([#1774](https://github.com/rollup/rollup/pull/1774)) +- Let --environment be used multiple times ([#1768](https://github.com/rollup/rollup/pull/1768)) +- Always transpile config files ([#1759](https://github.com/rollup/rollup/pull/1759)) +- Respect globals option in headers of UMD and IIFE files ([#1747](https://github.com/rollup/rollup/pull/1747)) + +## 0.52.0 + +_2017-11-25_ + +- Accept config as promise ([#1731](https://github.com/rollup/rollup/pull/1731)) +- Accept promises for intro/outro/banner/footer ([#1253](https://github.com/rollup/rollup/pull/1253)) +- Option to prevent freezing of namespace imports ([#1696](https://github.com/rollup/rollup/pull/1696)) +- Option to retain all output in watch mode ([#1688](https://github.com/rollup/rollup/pull/1688)) +- Options to fine-tune treeshaking ([#1760](https://github.com/rollup/rollup/pull/1760)) + +## 0.51.8 + +_2017-11-19_ + +- Fix speed problems by simplifying treeshaking reassignment handling ([#1740](https://github.com/rollup/rollup/pull/1740)) +- Update dependencies ([#1742](https://github.com/rollup/rollup/pull/1742)) + +## 0.51.7 + +_2017-11-17_ + +- Keep "this"-context when calling sequence expressions ([#1724](https://github.com/rollup/rollup/pull/1724)) + +## 0.51.6 + +_2017-11-16_ + +- Use sourcemaps to determine error locations ([#1728](https://github.com/rollup/rollup/pull/1728)) + +## 0.51.5 + +_2017-11-11_ + +- Fix regressions with uninitialised conditional expressions ([#1720](https://github.com/rollup/rollup/pull/1720)) + +## 0.51.4 + +_2017-11-11_ + +- Fix regressions preventing builds ([#1725](https://github.com/rollup/rollup/pull/1725)) + +## 0.51.3 + +_2017-11-10_ + +- Fix regression when treeshaking sequence expressions ([#1717](https://github.com/rollup/rollup/pull/1717)) + +## 0.51.2 + +_2017-11-09_ + +- Fix treeshaking regression when labels are used inside functions ([#1712](https://github.com/rollup/rollup/pull/1712)) + +## 0.51.1 + +_2017-11-08_ + +- Fix an issue with empty return statements ([#1704](https://github.com/rollup/rollup/pull/1704)) + +## 0.51.0 + +_2017-11-08_ + +- Massive improvements to the treeshaking algorithm ([#1667](https://github.com/rollup/rollup/pull/1667)) + +## 0.50.1 + +_2017-11-08_ + +- Fix treeshaking regression ([#1695](https://github.com/rollup/rollup/pull/1695)) +- Treeshaking improvements ([#1650](https://github.com/rollup/rollup/pull/1650)) +- Enable installation from Github ([#1670](https://github.com/rollup/rollup/pull/1670)) +- Update documentation ([#1660](https://github.com/rollup/rollup/pull/1660)) + +## 0.50.0 + +_2017-09-16_ + +- Many treeshaking improvements ([#1624](https://github.com/rollup/rollup/pull/1624)) +- Show finish time in watch mode ([#1620](https://github.com/rollup/rollup/pull/1620)) + +## 0.49.3 + +_2017-09-08_ + +- Respect `watch` options ([#1596](https://github.com/rollup/rollup/issues/1596)) +- Fix treeshaking regressions ([#1604](https://github.com/rollup/rollup/pull/1604)) +- Allow `-o` to work with `output.format` ([#1606](https://github.com/rollup/rollup/pull/1606)) + +## 0.49.2 + +_2017-08-29_ + +- Fix treeshaking regressions ([#1591](https://github.com/rollup/rollup/pull/1591)) + +## 0.49.1 + +_2017-08-28_ + +- Fix treeshaking regressions ([#1586](https://github.com/rollup/rollup/pull/1586)) + +## 0.49.0 + +_2017-08-27_ + +- Completely update the treeshaking algorithm ([#1582](https://github.com/rollup/rollup/pull/1582)) +- Only flip screen buffer if appropriate ([#1574](https://github.com/rollup/rollup/pull/1574)) +- Guard against two instances creating the same dir ([#1576](https://github.com/rollup/rollup/pull/1576)) + +## 0.48.2 + +- Paths is an output option ([#1569](https://github.com/rollup/rollup/pull/1569)) + +## 0.48.1 + +- Print deprecation warnings in watch mode, and fix options when watcher restarts ([#1568](https://github.com/rollup/rollup/pull/1568)) + +## 0.48.0 + +- Numerous changes to the `options` object and CLI arguments ([#1479](https://github.com/rollup/rollup/issues/1479)). See [this gist](https://gist.github.com/Rich-Harris/d472c50732dab03efeb37472b08a3f32) for a rundown. + +## 0.47.6 + +- Set `process.env.ROLLUP_WATCH` _before_ loading config file + +## 0.47.5 + +- Fix broken multi-bundle configs with `rollup.watch` ([#1532](https://github.com/rollup/rollup/issues/1532)) + +## 0.47.4 + +- Delete cached config file before reloading in watch mode + +## 0.47.3 + +- Deshadow aliased imports ([#1550](https://github.com/rollup/rollup/issues/1550)) + +## 0.47.2 + +- Rebuild with dependency that npm randomly deleted + +## 0.47.1 + +- Ignore external namespace imports when deshadowing ([#1547](https://github.com/rollup/rollup/issues/1547)) + +## 0.47.0 + +- Watch config file, restart `rollup.watch` on change ([#1535](https://github.com/rollup/rollup/issues/1535)) +- Correctly render `export { foo } from` declarations in `es` output ([#1543](https://github.com/rollup/rollup/pull/1543)) +- Reinstate missing `rollup.VERSION` + +## 0.46.3 + +- init for/for-of loop section head with correct scopes ([#1538](https://github.com/rollup/rollup/issues/1538), [#1539](https://github.com/rollup/rollup/issues/1539)) +- Fix namespace imports and re-exports in `es` output ([#1511](https://github.com/rollup/rollup/issues/1511)) +- Deshadow indirectly imported namespaces ([#1488](https://github.com/rollup/rollup/issues/1488), [#1505](https://github.com/rollup/rollup/issues/1505)) + +## 0.46.2 + +- Pass options to `bundle.write` correctly in `rollup.watch` ([#1533](https://github.com/rollup/rollup/issues/1533)) +- init for-in loop section head with correct scopes ([#1480](https://github.com/rollup/rollup/issues/1480)) +- support `--no-interop` flag ([#1524](https://github.com/rollup/rollup/issues/1524)) + +## 0.46.1 + +- Remove `rollup.watch` from browser build ([#1530](https://github.com/rollup/rollup/issues/1530)) +- Remove `source-map-support` dependency ([#1528](https://github.com/rollup/rollup/issues/1528)) + +## 0.46.0 + +- `options.format` is now required ([#1491](https://github.com/rollup/rollup/pull/1491)) +- if `options.format` is `es6`, it will now throw an error (should be `es`) ([#1491](https://github.com/rollup/rollup/pull/1491)) +- Add experimental `rollup.watch` method, replacing [rollup-watch](https://github.com/rollup/rollup-watch) ([#1491](https://github.com/rollup/rollup/pull/1491)) +- Batch warnings together in CLI output ([#1491](https://github.com/rollup/rollup/pull/1491)) +- Clear screen between rebuilds in `--watch` mode ([#1491](https://github.com/rollup/rollup/pull/1491)) +- `onwarn` function's second argument is the default handler, allowing easier filtering without reimplementing any logic ([#1491](https://github.com/rollup/rollup/pull/1491)) +- Prevent semi-colon removal after variable declaration that is for loop body ([#1275](https://github.com/rollup/rollup/issues/1275)) +- Return `exports` for namespaced but non-extended IIFE bundles ([#1492](https://github.com/rollup/rollup/issues/1492)) +- Fix scoping in switch statements ([#1498](https://github.com/rollup/rollup/pull/1498)) +- Handle side-effects in tagged template expressions ([#1508](https://github.com/rollup/rollup/pull/1508)) +- More descriptive error for missing options.format ([#1510](https://github.com/rollup/rollup/pull/1510)) +- Refactor scope handling ([#1517](https://github.com/rollup/rollup/pull/1517)) +- Handle failure of a config in multi-config build ([#1513](https://github.com/rollup/rollup/issues/1513)) + +## 0.45.2 + +- Fix interop when import is a string ([#1486](https://github.com/rollup/rollup/issues/1486)) +- Separate `resolvedIds` from `resolvedExternalIds` ([#1490](https://github.com/rollup/rollup/pull/1490)) +- Add `--extend` flag to CLI ([#1482](https://github.com/rollup/rollup/pull/1482)) + +## 0.45.1 + +- Remove `weak` from `optionalDependencies` ([#1483](https://github.com/rollup/rollup/issues/1483)) + +## 0.45.0 + +- [BREAKING] `bundle.generate(...)` returns a Promise, so that `transformBundle` plugin hooks can be asynchronous ([#1474](https://github.com/rollup/rollup/issues/1474)) + +## 0.44.0 + +- [BREAKING] Don't extend existing globals, unless `options.extend` is true ([#827](https://github.com/rollup/rollup/issues/827)) +- Fix handling of catch clause parameters ([#1462](https://github.com/rollup/rollup/issues/1462)) + +## 0.43.1 + +- Fix memory leak on incremental rebuilds ([#883](https://github.com/rollup/rollup/issues/883)) +- Allow `this.warn` and `this.error` to accept a `{line, column}` object as an alternative to a character index ([#1265](https://github.com/rollup/rollup/issues/1265)) +- Print more useful error if entry module is 'external' ([#1264](https://github.com/rollup/rollup/issues/1264)) +- Catch errors in `bundle.generate` options ([#1463](https://github.com/rollup/rollup/pull/1463)) +- Fix magic-string deprecation warning ([#1445](https://github.com/rollup/rollup/pull/1445)) + +## 0.43.0 + +- Allow config files to import JSON ([#1426](https://github.com/rollup/rollup/issues/1426)) +- Allow undefined imports in interop block ([#1341](https://github.com/rollup/rollup/issues/1341)) +- Add `process.env.ROLLUP_WATCH = 'true'` in watch mode ([#1429](https://github.com/rollup/rollup/issues/1429)) +- Add `pureExternalModules` option ([#1352](https://github.com/rollup/rollup/issues/1352)) +- Allow plugins to specify `options.entry` ([#1270](https://github.com/rollup/rollup/issues/1270)) +- Update dependencies + +## 0.42.0 + +- Deprecate `options.moduleId` in favour of `options.amd.id` ([#1365](https://github.com/rollup/rollup/pull/1365)) +- Add `options.amd.define` option to specify name of AMD `define` function ([#1365](https://github.com/rollup/rollup/pull/1365)) +- Fix incorrect class removal with `treeshake: false` ([#1375](https://github.com/rollup/rollup/pull/1375)) +- Deconflict module exports imported as namespaces ([#1384](https://github.com/rollup/rollup/issues/1384)) +- Handle bare self-imports ([#1274](https://github.com/rollup/rollup/issues/1274)) +- Allow config file to export an array of multiple configs ([#1389](https://github.com/rollup/rollup/pull/1389)) +- Handle exponentiation operator, and fail gracefully on unknown operators ([#1416](https://github.com/rollup/rollup/issues/1416)) +- Add `watch` option ([#1424](https://github.com/rollup/rollup/pull/1424)) + +## 0.41.6 + +- Preserve `originalSourceMap` on incremental rebuilds for loaders with sourcemaps ([#1336](https://github.com/rollup/rollup/issues/1336)) + +## 0.41.5 + +- Wrap ternary consequent/alternate sequences in parens ([#1273](https://github.com/rollup/rollup/issues/1273)) +- Fix erroneous warning on multiple `export * from` declarations with defaults ([#1278](https://github.com/rollup/rollup/issues/1278)) +- Prevent variable conflicts with `treeshake: false` ([#1268](https://github.com/rollup/rollup/issues/1268)) +- Allow missing `source` when collapsing sourcemaps ([#1254](https://github.com/rollup/rollup/issues/1254)) +- Allow plugins to log with strings ([#1316](https://github.com/rollup/rollup/pull/1316)) + +## 0.41.4 + +- Fix cases of multiple `export * from 'external'` declarations ([#1252](https://github.com/rollup/rollup/issues/1252)) +- Fix 'TODO' error message ([#1257](https://github.com/rollup/rollup/issues/1257)) + +## 0.41.3 + +- Don't treat `this.foo` as possible namespace ([#1258](https://github.com/rollup/rollup/issues/1258)) + +## 0.41.2 + +- Optimize `namespace['foo']` references ([#1240](https://github.com/rollup/rollup/pull/1240)) + +## 0.41.1 + +- Include `new` expressions where callee is a class with side-effects ([#980](https://github.com/rollup/rollup/issues/980) [#1233](https://github.com/rollup/rollup/issues/1233)) + +## 0.41.0 + +- Add `this.warn(...)` and `this.error(...)` methods to plugin `transform` hook contexts ([#1140](https://github.com/rollup/rollup/issues/1140)) +- `throw` always considered to be a side effect ([#1227](https://github.com/rollup/rollup/pull/1227)) + +## 0.40.2 + +- Add `file` property to sourcemaps for bundles with plugins ([#986](https://github.com/rollup/rollup/issues/986)) +- Don't require globals for empty imports ([#1217](https://github.com/rollup/rollup/issues/1217)) + +## 0.40.1 + +- Allow missing space between `export default` and declaration ([#1218](https://github.com/rollup/rollup/pull/1218)) + +## 0.40.0 + +- [BREAKING] Better, more consistent error logging ([#1212](https://github.com/rollup/rollup/pull/1212)) +- Don't use colours and emojis for non-TTY stderr ([#1201](https://github.com/rollup/rollup/issues/1201)) + +## 0.39.2 + +- Prevent mutation of cached ASTs (fixes stack overflow with rollup-watch) ([#1205](https://github.com/rollup/rollup/pull/1205)) + +## 0.39.1 + +- Ignore `var` initialisers in dead branches ([#1198](https://github.com/rollup/rollup/issues/1198)) + +## 0.39.0 + +- [BREAKING] Warnings are objects, rather than strings ([#1194](https://github.com/rollup/rollup/issues/1194)) + +## 0.38.3 + +- More informative warning for implicit external dependencies ([#1051](https://github.com/rollup/rollup/issues/1051)) +- Warn when creating browser bundle with external dependencies on Node built-ins ([#1051](https://github.com/rollup/rollup/issues/1051)) +- Statically analyse LogicalExpression nodes, for better dead code removal ([#1061](https://github.com/rollup/rollup/issues/1061)) + +## 0.38.2 + +- Preserve `var` declarations in dead branches ([#997](https://github.com/rollup/rollup/issues/997)) +- Warn if exporting a call expression that looks like a function declaration ([#1011](https://github.com/rollup/rollup/issues/1011)) +- Wrap function expressions in parentheses if necessary ([#1011](https://github.com/rollup/rollup/issues/1011)) + +## 0.38.1 + +- Fix sourcemap comment removal ([#1104](https://github.com/rollup/rollup/issues/1104)) +- Warn if empty bundle is generated ([#444](https://github.com/rollup/rollup/issues/444)) +- Support ES2017 syntax ([#492](https://github.com/rollup/rollup/issues/492)) +- Remove unused imports from external modules ([#595](https://github.com/rollup/rollup/issues/595)) +- Remove unused function and class declarations inside function bodies ([#1108](https://github.com/rollup/rollup/issues/1108), [#1178](https://github.com/rollup/rollup/issues/1178)) +- Deconflict function expression IDs ([#1176](https://github.com/rollup/rollup/issues/1176)) + +## 0.38.0 + +- [BREAKING] `export { foo as default }` creates live binding ([#1078](https://github.com/rollup/rollup/issues/1078)) +- Prevent sourceMappingURL removal edge case ([#988](https://github.com/rollup/rollup/issues/988)) +- Bind function expression IDs to the correct scope ([#1083](https://github.com/rollup/rollup/issues/1083)) +- Correctly deshadow destructured parameters with assignments ([#1008](https://github.com/rollup/rollup/issues/1008)) + +## 0.37.2 + +- Remove unused `new` expressions without side-effects ([#179](https://github.com/rollup/rollup/issues/179)) +- Only remove valid sourceMappingURL comments ([#1132](https://github.com/rollup/rollup/issues/1132)) +- Ensure blocks containing activated `var` declarations are included in output ([#1113](https://github.com/rollup/rollup/issues/1113)) +- Support plugin outros ([#1116](https://github.com/rollup/rollup/issues/1116)) + +## 0.37.1 + +- Follow symlinks ([#447](https://github.com/rollup/rollup/issues/447)) +- Fix tree-shaking of recursive functions and other cases ([#1120](https://github.com/rollup/rollup/issues/1120), [#1142](https://github.com/rollup/rollup/issues/1142)) +- Support module names that require quotes ([#582](https://github.com/rollup/rollup/issues/582), [#584](https://github.com/rollup/rollup/issues/584)) +- Fix [#957](https://github.com/rollup/rollup/issues/957) + +## 0.37.0 + +- [BREAKING] Default exports are not included in reified namespaces ([#1028](https://github.com/rollup/rollup/issues/1028)) +- Parentheses do not defeat tree-shaking ([#1101](https://github.com/rollup/rollup/issues/1101), [#1128](https://github.com/rollup/rollup/issues/1128)) +- More `legacy` fixes: do not create getters ([#1069](https://github.com/rollup/rollup/pull/1069)), do not include `__esModule` ([#1068](https://github.com/rollup/rollup/pull/1068)), quote reserved property names ([#1057](https://github.com/rollup/rollup/pull/1057)) +- Fix missing namespace member warnings ([#1045](https://github.com/rollup/rollup/issues/1045)) +- Fix TypeError in arrow function without braces returning a function ([#1062](https://github.com/rollup/rollup/pull/1062)) + +## 0.36.4 + +- Only depend on program-level call expressions ([#977](https://github.com/rollup/rollup/issues/977)) + +## 0.36.3 + +- Add `legacy` option for IE8 support ([#989](https://github.com/rollup/rollup/pull/989)) + +## 0.36.2 + +- Insert semicolons where necessary to fix broken code ([#1004](https://github.com/rollup/rollup/issues/1004)) +- Include module ID and location when warning about top-level `this` ([#1012](https://github.com/rollup/rollup/pull/1012)) +- More informative error for missing exports ([#1033](https://github.com/rollup/rollup/issues/1033)) +- `options.moduleContext` for per-module context overrides ([#1023](https://github.com/rollup/rollup/pull/1023)) + +## 0.36.1 + +- Include naked block statements ([#981](https://github.com/rollup/rollup/issues/981)) +- Correctly include falsy alternate statements in optimised if blocks ([#973](https://github.com/rollup/rollup/issues/973)) +- Prevent omission of default exports that are only used by the exporting module ([#967](https://github.com/rollup/rollup/pull/967)) +- Prevent warning on `auto` exports with ES output ([#966](https://github.com/rollup/rollup/pull/966)) + +## 0.36.0 + +- `export { foo as default }` no longer creates a live binding ([#860](https://github.com/rollup/rollup/issues/860)) + +## 0.35.15 + +- Warn on missing unused imports in deshadowing phase ([#928](https://github.com/rollup/rollup/issues/928)) +- Always add a newline to the end of bundles ([#958](https://github.com/rollup/rollup/issues/958)) + +## 0.35.14 + +- Include all parent statements of expression with effects, up to function boundary ([#930](https://github.com/rollup/rollup/issues/930)) + +## 0.35.13 + +- Include superclasses when including their subclasses ([#932](https://github.com/rollup/rollup/issues/932)) + +## 0.35.12 + +- Add `interop: false` option to disable unwrapping of external imports ([#939](https://github.com/rollup/rollup/issues/939)) + +## 0.35.11 + +- Deconflict reified namespaces with other declarations ([#910](https://github.com/rollup/rollup/issues/910)) + +## 0.35.10 + +- Only remove EmptyStatement nodes directly inside blocks ([#913](https://github.com/rollup/rollup/issues/931)) + +## 0.35.9 + +- Support Node 0.12 ([#909](https://github.com/rollup/rollup/issues/909)) + +## 0.35.8 + +- Correctly deshadow re-assigned module functions ([#910](https://github.com/rollup/rollup/issues/910)) + +## 0.35.7 + +- Refactor `flushTime.js` ([#922](https://github.com/rollup/rollup/pull/922)) + +## 0.35.6 + +- Fix browser build + +## 0.35.5 + +- Allow empty for loop heads ([#919](https://github.com/rollup/rollup/issues/919)) + +## 0.35.4 + +- Preserve effects in for-of and for-in loops ([#870](https://github.com/rollup/rollup/issues/870)) +- Remove empty statements ([#918](https://github.com/rollup/rollup/pull/918)) + +## 0.35.3 + +- Render identifiers inside template literals + +## 0.35.2 + +- Fix broken build caused by out of date locally installed dependencies + +## 0.35.1 + +- Rewrite deconflicted class identifiers ([#915](https://github.com/rollup/rollup/pull/915)) +- Include `dependencies` in `bundle.modules` objects ([#903](https://github.com/rollup/rollup/issues/903)) +- Update to Acorn 4 ([#914](https://github.com/rollup/rollup/pull/914)) + +## 0.35.0 + +- Rewrite analysis/tree-shaking code ([#902](https://github.com/rollup/rollup/pull/902)) +- Include conditional mutations of global objects ([#901](https://github.com/rollup/rollup/issues/901)) +- Only reify namespaces if necessary ([#898](https://github.com/rollup/rollup/issues/898)) +- Track mutations of aliased globals ([#893](https://github.com/rollup/rollup/issues/893)) +- Include duplicated var declarations ([#716](https://github.com/rollup/rollup/issues/716)) + +## 0.34.13 + +- Pass `{ format }` through to `transformBundle` ([#867](https://github.com/rollup/rollup/issues/867)) + +## 0.34.12 + +- Fix `rollup --watch` ([#887](https://github.com/rollup/rollup/issues/887)) +- Case-sensitive paths ([#862](https://github.com/rollup/rollup/issues/862)) + +## 0.34.11 + +- Prevent leaky state when `bundle` is reused ([#875](https://github.com/rollup/rollup/issues/875)) +- Ensure `intro` appears before interop block ([#880](https://github.com/rollup/rollup/issues/880)) + +## 0.34.10 + +- Allow custom `options.context` to replace top-level `this` ([#851](https://github.com/rollup/rollup/issues/851)) +- Fix `noConflict` when used via `rollup --config` ([#846](https://github.com/rollup/rollup/issues/846)) +- Place `outro` block _after_ export block ([#852](https://github.com/rollup/rollup/issues/852)) + +## 0.34.9 + +- Disable indentation by default, for faster bundle generation ([#812](https://github.com/rollup/rollup/pull/812)) +- More helpful error on missing entry file ([#802](https://github.com/rollup/rollup/issues/802)) +- Preserve comments before import declarations ([#815](https://github.com/rollup/rollup/pull/815)) + +## 0.34.8 + +- Wrap UMD factory function in parens to avoid lazy parsing ([#774](https://github.com/rollup/rollup/pull/774)) + +## 0.34.7 + +- Leave it up to resolveId to normalize the entry path ([#835](https://github.com/rollup/rollup/pull/835)) +- Cache decoded mappings ([#834](https://github.com/rollup/rollup/pull/834)) + +## 0.34.5 + +- Fix circular export ([#813](https://github.com/rollup/rollup/issues/813)) + +## 0.34.4 + +- Module render performance tweak ([#823](https://github.com/rollup/rollup/pull/823)) + +## 0.34.3 + +- Avoid infinite recursion in `Bundle.sort()` ([#800](https://github.com/rollup/rollup/pull/800)) + +## 0.34.2 + +- resolveId calls are cached now to improve incremental build +- Fixed error message recursion in plugins + +## 0.34.1 + +- Support `paths` config ([#754](https://github.com/rollup/rollup/issues/754)) +- Allow `export *` from external module, internally + +## 0.34.0 + +- Use resolved IDs for relative imports that are also external modules, to allow `options.globals` to work with them ([#763](https://github.com/rollup/rollup/issues/763)) +- Ensure reassigned exports are declared in an ES bundle, and remove empty `exports.foo;` statements ([#755](https://github.com/rollup/rollup/issues/755)) +- Add newline after sourcemap comment ([#756](https://github.com/rollup/rollup/issues/756)) + +## 0.33.2 + +- Add `bundle` as second argument to `ongenerate` and `onwrite` hooks ([#773](https://github.com/rollup/rollup/pull/773)) +- Warn on top-level `this` ([#770](https://github.com/rollup/rollup/issues/770)) + +## 0.33.1 + +- Fix `--no-strict` option ([#751](https://github.com/rollup/rollup/pull/751)) +- Fix Windows edge case with case-sensitive paths ([#760](https://github.com/rollup/rollup/pull/760)) + +## 0.33.0 + +- Downgrade missing transformer sourcemap to a warning, not an error, and print the name of the offending plugin if possible ([#746](https://github.com/rollup/rollup/issues/746)) +- Warn if same name is re-exported from two modules ([#722](https://github.com/rollup/rollup/issues/722)) + +## 0.32.4 + +- Add `ongenerate` and `onwrite` plugin hooks ([#742](https://github.com/rollup/rollup/pull/742)) + +## 0.32.3 + +- Generated correct sourcemaps with reified namespaces ([#668](https://github.com/rollup/rollup/issues/668)) +- Exclude plugin helper modules from sourcemaps ([#747](https://github.com/rollup/rollup/pull/747)) + +## 0.32.2 + +- Allow `--globals` to work with `--external` or `options.external` in whatever configuration ([#743](https://github.com/rollup/rollup/issues/743)) + +## 0.32.1 + +- Preserve side-effects to default exports that coincide with used named exports ([#733](https://github.com/rollup/rollup/issues/733)) +- Support `rollup -c node:pkgname` ([#736](https://github.com/rollup/rollup/issues/736)) + +## 0.32.0 + +- Deprecate `es6` format in favour of `es` ([#468](https://github.com/rollup/rollup/issues/468)) +- Add correct `jsnext:main` build ([#726](https://github.com/rollup/rollup/pull/726)) + +## 0.31.2 + +- Allow `load` plugins to provide sourcemap ([#715](https://github.com/rollup/rollup/pull/715)) +- Allow `sourceMapFile` in config options ([#717](https://github.com/rollup/rollup/issues/717)) + +## 0.31.1 + +- Logging for errors emitted by `rollup-watch` ([#712](https://github.com/rollup/rollup/issues/712)) + +## 0.31.0 + +- Rewrite top-level `this` as `undefined` ([#707](https://github.com/rollup/rollup/pull/707)) +- Pass `options.acorn` to Acorn ([#564](https://github.com/rollup/rollup/issues/564)) + +## 0.30.0 + +- Bundle CLI ([#700](https://github.com/rollup/rollup/issues/700)) +- Ensure absolute paths are normalised ([#704](https://github.com/rollup/rollup/issues/704)) +- Allow `rollup --watch` to work with targets + +## 0.29.1 + +- Merge `target` options with main options ([#701](https://github.com/rollup/rollup/issues/701)) +- Update magic-string ([#690](https://github.com/rollup/rollup/issues/690)) + +## 0.29.0 + +- `rollup --watch` ([#284](https://github.com/rollup/rollup/issues/284)) + +## 0.28.0 + +- Experimental support for incremental rebuilds ([#658](https://github.com/rollup/rollup/pull/658)) + +## 0.27.1 + +- Ensure names exported from a module are not replaced with reserved words ([#696](https://github.com/rollup/rollup/pull/696)) +- Revert ([#692](https://github.com/rollup/rollup/pull/692)) – resolved IDs must be strings + +## 0.27.0 + +- Use native promises instead of `es6-promise` ([#689](https://github.com/rollup/rollup/issues/689)) +- Support multiple targets in config files ([#655](https://github.com/rollup/rollup/issues/655)) +- Allow `resolveId` plugin functions to return non-strings ([#692](https://github.com/rollup/rollup/pull/692)) + +## 0.26.7 + +- Distinguish between default and namespace imports of external module ([#637](https://github.com/rollup/rollup/issues/637)) +- Add `__esModule` property to named exports in AMD, CJS and UMD modes ([#650](https://github.com/rollup/rollup/issues/650)) + +## 0.26.6 + +- Deconflict named imports from external modules in ES bundles ([#659](https://github.com/rollup/rollup/issues/659)) +- Support `options.preferConst` to generate `const` declarations for exports rather than `var` declarations ([#653](https://github.com/rollup/rollup/issues/653)) + +## 0.26.5 + +- Preserve `debugger` statements ([#664](https://github.com/rollup/rollup/issues/664)) +- Allow `options.external` to be a function ([#522](https://github.com/rollup/rollup/issues/522)) + +## 0.26.4 + +- Prevent plugin-provided external IDs being normalised ([#630](https://github.com/rollup/rollup/issues/630), [#633](https://github.com/rollup/rollup/issues/633)) +- Throw if module exports/re-exports the same name twice, or has multiple default exports ([#679](https://github.com/rollup/rollup/issues/679)) +- Warn about `eval` security issue ([#675](<(https://github.com/rollup/rollup/issues/675)>)) + +## 0.26.3 + +- Ensure reference is not incorrectly marked as a reassignment ([#648](https://github.com/rollup/rollup/issues/648)) + +## 0.26.2 + +- Sanity check output of `load` hook ([#607](https://github.com/rollup/rollup/issues/607)) +- Correct scoping for ID class expressions ([#626](https://github.com/rollup/rollup/issues/626)) +- Warn if named and default exports are used together in auto mode ([#587](https://github.com/rollup/rollup/issues/587)) +- Allow variable initialisers to be rewritten if necessary ([#632](https://github.com/rollup/rollup/issues/632)) +- Prevent double `var` with no-treeshake option ([#639](https://github.com/rollup/rollup/pull/639)) + +## 0.26.1 + +- Add `treeshake: false`/`--no-treeshake` option for debugging ([#505](https://github.com/rollup/rollup/issues/505)) +- Update build process to use Bublé ([#620](https://github.com/rollup/rollup/pull/620)) + +## 0.26.0 + +- Add `noConflict`/`--no-conflict` option for UMD builds ([#580](https://github.com/rollup/rollup/pull/580)) +- Normalise relative external paths ([#591](https://github.com/rollup/rollup/pull/591)) +- Report files causing transform errors ([#609](https://github.com/rollup/rollup/pull/609)) +- Handle sourcemap segments with a single member ([#619](https://github.com/rollup/rollup/pull/619)) +- Update dependencies + +## 0.25.8 + +- Unixize entry path ([#586](https://github.com/rollup/rollup/pull/586)) + +## 0.25.7 + +- Expand deshadowed shorthand properties ([#575](https://github.com/rollup/rollup/issues/575)) +- Allow external files to be non-existent ([#532](https://github.com/rollup/rollup/issues/532)) + +## 0.25.6 + +- Fix a regression introduced by #566 ([#569](https://github.com/rollup/rollup/issues/569)) +- Prune dead conditional expressions more carefully ([#567](https://github.com/rollup/rollup/issues/567)) + +## 0.25.5 + +- Make sure shorthand destructuring assignments don't break ([#528](https://github.com/rollup/rollup/issues/528)) +- Allow 'exports' key ([#542](https://github.com/rollup/rollup/issues/542)) +- Ensure `foo. bar` where `foo` is a namespace import is rewritten correctly ([#566](https://github.com/rollup/rollup/issues/566)) +- Fix an edge case for exported globals (e.g. `export { document }`) ([#562](https://github.com/rollup/rollup/issues/562)) + +## 0.25.4 + +- Fix misnamed exports of default imports in ES bundles ([#513](https://github.com/rollup/rollup/issues/513)) +- CLI: warn on missing config ([#515](https://github.com/rollup/rollup/pull/515)) +- Detect side-effects in non-top-level member expression assignment ([#476](https://github.com/rollup/rollup/issues/476)) +- Don't remove computed property class keys ([#504](https://github.com/rollup/rollup/issues/504)) +- Augment existing global object rather than replacing ([#493](https://github.com/rollup/rollup/issues/493)) +- Don't fail on `export {}`, warn instead ([#486](https://github.com/rollup/rollup/issues/486)) + +## 0.25.3 + +- Handle non-objects and `null` in `_interopDefault` ([#474](https://github.com/rollup/rollup/issues/474)) + +## 0.25.2 + +- Skip dead branches of a conditional expression (#[465](https://github.com/rollup/rollup/pull/465)) +- Allow globals to be exported ([#472](https://github.com/rollup/rollup/pull/472)) +- Ensure reassigned exports are exported ([#484](https://github.com/rollup/rollup/issues/484)) + +## 0.25.1 + +- Throw error if namespace is called ([#446](https://github.com/rollup/rollup/issues/446)) +- Prevent shadowing bug in ES6 output ([#441](https://github.com/rollup/rollup/pull/441)) +- Prevent `var exports.foo` ([#426](https://github.com/rollup/rollup/issues/426)) +- Prevent double export of aliased symbols ([#438](https://github.com/rollup/rollup/issues/438)) +- Provide more informative error if Rollup is used in-browser without appropriate `resolveId`/`load` hooks ([#275](https://github.com/rollup/rollup/issues/275)) +- Use `_interopDefault` function to DRY out code with many external dependencies, in CommonJS output ([#458](https://github.com/rollup/rollup/pull/458)) + +## 0.25.0 + +- **breaking** Module order is determined according to spec, rather than in a way designed to prevent runtime errors. Rollup will warn if it detects runtime errors are likely ([#435](https://github.com/rollup/rollup/issues/435)) +- Prevent overly aggressive tree-shaking with complex call expressions ([#440](https://github.com/rollup/rollup/issues/440)) + +## 0.24.1 + +- Handle calls to default exports other that are not function expressions or references to function declarations ([#421](https://github.com/rollup/rollup/issues/421)) +- Ensure namespace blocks are created for chained imports ([#430](https://github.com/rollup/rollup/issues/430)) +- Include references in computed property keys ([#434](https://github.com/rollup/rollup/issues/434)) +- Use CLI `--external` option correctly ([#417](https://github.com/rollup/rollup/pull/417)) +- Allow relative imports to be treated as external, if absolute paths are provided in `options.external` ([#410](https://github.com/rollup/rollup/issues/410)) +- Make IIFE output adhere to Crockford style ([#415](https://github.com/rollup/rollup/pull/415)) + +## 0.24.0 + +- No longer attempts to resolve IDs in `options.external` ([#407](https://github.com/rollup/rollup/issues/407)) +- Fix broken sourcemap resolution in cases where some modules are transformed and others aren't ([#404](https://github.com/rollup/rollup/issues/404)) + +## 0.23.2 + +- Ensure `dest` or `sourceMapFile` is resolved against CWD for purposes of sourcemap generation ([#344](https://github.com/rollup/rollup/issues/344)) +- Support `banner`, `footer`, `intro` and `outro` options via CLI ([#330](https://github.com/rollup/rollup/issues/330)) +- Allow `options.global` to be a function rather than an object, and warn on missing names ([#293](https://github.com/rollup/rollup/issues/293)) +- Ensure side-effects are captured in cyclical call expressions ([#397](https://github.com/rollup/rollup/issues/397)) +- Fix parse error with body-less arrow function expressions ([#403](https://github.com/rollup/rollup/issues/403)) + +## 0.23.1 + +- Reinstate missing fix from ([#392](https://github.com/rollup/rollup/pull/392)) + +## 0.23.0 + +- Add `bundleTransform` plugin hook and option ([#387](https://github.com/rollup/rollup/pull/387)) +- Correctly store names in sourcemaps, regardless of transformers +- Add `--environment` option to CLI ([#388](https://github.com/rollup/rollup/pull/388)) +- Handle destructuring in exports ([#374](https://github.com/rollup/rollup/issues/374)) +- Fix UMD global exports bug introduced in 0.22.1 ([#392](https://github.com/rollup/rollup/pull/392)) + +## 0.22.2 + +- Prevent lost `var` keywords ([#390](https://github.com/rollup/rollup/issues/390)) + +## 0.22.1 + +- Update expected option keys ([#379](https://github.com/rollup/rollup/issues/379)) +- Handle transformers that return stringified sourcemaps ([#377](https://github.com/rollup/rollup/issues/377)) +- Automatically create missing namespaces if `moduleName` contains dots ([#378](https://github.com/rollup/rollup/issues/378)) +- Ignore external dependency warnings coming from config file ([#333](https://github.com/rollup/rollup/issues/333)) +- Update to latest magic-string for performance boost + +## 0.22.0 + +- Duplicate warnings are squelched ([#362](https://github.com/rollup/rollup/issues/362)) +- Plugins can manipulate or override the `options` object ([#371](https://github.com/rollup/rollup/pull/371)) + +## 0.21.3 + +- Validate option keys ([#348](https://github.com/rollup/rollup/pull/348)) +- Allow namespaces imports to sit alongside named imports ([#355](https://github.com/rollup/rollup/issues/355)) +- Count references inside destructured objects ([#364](https://github.com/rollup/rollup/issues/364)) +- Preserve top-level `delete` statements ([#352](https://github.com/rollup/rollup/issues/352)) + +## 0.21.2 + +- Missing relative imports are an error, not a warning ([#321](https://github.com/rollup/rollup/issues/321)) +- Fixed incorrectly renamed default exports in ES6 bundles ([#339](https://github.com/rollup/rollup/issues/339)) +- Fixed infinite recursion bug ([#341](https://github.com/rollup/rollup/issues/341)) + +## 0.21.1 + +- Remove `aggressive: true` (was too aggressive) ([#309](https://github.com/rollup/rollup/pull/309)) +- Handle top-level block statements ([#326](https://github.com/rollup/rollup/issues/326)) +- Optimise namespaces with default exports ([#314](https://github.com/rollup/rollup/issues/314)) + +## 0.21.0 + +- Only include statements whose side-effects are relevant (i.e. contribute to exports or affect global state) ([#253](https://github.com/rollup/rollup/pull/253)) ([#253](https://github.com/rollup/rollup/pull/253)) +- Exclude dead branches from analysis and inclusion ([#249](https://github.com/rollup/rollup/pull/249)) +- Add `aggressive: true` option to eliminate all side-effects outside entry module +- More informative error when re-exporting non-existent binding ([#274](https://github.com/rollup/rollup/issues/274)) +- Fix infinite recursion bug ([#291](https://github.com/rollup/rollup/issues/291)) +- Log errors when using `rollup --config` ([#288](https://github.com/rollup/rollup/pull/288)) +- Return rejected promises on startup instead of throwing error, if options are invalid ([#303](https://github.com/rollup/rollup/pull/303)) + +## 0.20.5 + +- Ensure re-exports don't create a local binding ([#270](https://github.com/rollup/rollup/pull/270)) + +## 0.20.4 + +- Check file exists at resolve time, to allow filenames with non-extension dots in them ([#250](https://github.com/rollup/rollup/pull/250)) +- Import `Promise` where used, for Node 0.10 support ([#254](https://github.com/rollup/rollup/issues/254)) +- Allow asynchronous transformer plugins ([#260](https://github.com/rollup/rollup/issues/260)) +- Don't assume re-exported bindings are globals when deconflicting ([#267](https://github.com/rollup/rollup/issues/267)) + +## 0.20.3 + +- Fix bug where multiple `export *` declarations caused error ([#244](https://github.com/rollup/rollup/pulls/244)) +- Missing namespace exports are a warning, not an error ([#244](https://github.com/rollup/rollup/pulls/244)) +- Plugins can provide `banner` and `footer` options (string, or function that returns a string) ([#235](https://github.com/rollup/rollup/issues/235)) +- Warn on encountering `eval` ([#186](https://github.com/rollup/rollup/issues/186)) + +## 0.20.2 + +- Handle errors in build config file +- More robust deconflicting, in cases where e.g. `foo$1` already exists +- Use Rollup CLI for own build process + +## 0.20.1 + +- Support `--config` file to enable plugins with CLI ([#226](https://github.com/rollup/rollup/pulls/226)) +- Prevent `default` being used as variable name ([#215](https://github.com/rollup/rollup/issues/215)) +- Update deps + +## 0.20.0 + +- Support for [plugins](https://github.com/rollup/rollup/wiki/Plugins) ([#207](https://github.com/rollup/rollup/pulls/207)) +- BREAKING – `options.transform`, `options.load`, `options.resolveId`, `options.resolveExternal` and `options.external` are no longer supported, and should be handled by plugins. [More info](https://github.com/rollup/rollup/wiki/Plugins) +- BREAKING – the .js extension is only added if it looks like there's no extension, allowing e.g. `import data from 'data.json'` (with the appropriate transformer). For safety, always include the file extension – import `./foo.js`, not `./foo` + +## 0.19.2 + +- Fix exporting namespaces to include all of their exports ([#204](https://github.com/rollup/rollup/issues/204)) +- Namespace exotic objects are frozen to ensure that its properties cannot be modified, reconfigured, redefined or deleted ([#203](https://github.com/rollup/rollup/pulls/203)) +- Fix `ReferenceError: Promise is not defined` in node v0.10 ([#189](https://github.com/rollup/rollup/issues/189)) + +## 0.19.1 + +- Fix `module.basename()` when used with custom `resolveId` function +- Use [rollup-babel](https://github.com/rollup/rollup-babel) to build self +- Exposed the version string through the API: `require( 'rollup' ).VERSION` + +## 0.19.0 + +- **breaking** The `transform` option is no longer passed through to custom loaders. Loaders should only concern themselves with providing source code; transformation will _always_ take place +- `options.transform` functions can return a string, or a `{code, map, ast}` object. Where possible, sourcemap chains will be flattened ([#175](https://github.com/rollup/rollup/pull/175)) +- `options.resolveId`, `options.resolveExternal` and `options.load` can each be a function or an array of functions. If an array, the first non-null/undefined return value is used. In both cases, failed resolution/loading will fall back to the defaults, unless an error is thrown. ([#174](https://github.com/rollup/rollup/pull/174)) +- New `intro` and `outro` options – similar to `banner` and `footer` except inserted _inside_ any format-specific wrapper +- Multiple var declarations in an export block (e.g. `export let a = 1, b = 2`) are split up to facilitate tree-shaking ([#171](https://github.com/rollup/rollup/issues/171)) +- More informative error when using a missing namespace property ([#169](https://github.com/rollup/rollup/pull/169)) +- Update various dependencies + +## 0.18.5 + +- Allow namespaces to be assigned to variables ([#168](https://github.com/rollup/rollup/issues/168)) +- Promote `chalk` and `source-map-support` to `dependencies`, as they're used by the CLI ([#167](https://github.com/rollup/rollup/pull/167)) + +## 0.18.4 + +- Make external modules configurable (i.e. `external.config.foo = 'bar'`) without erroring + +## 0.18.3 + +- Crop indent exclusion ranges to exclude enclosing quotes ([#166](https://github.com/rollup/rollup/issues/166)) + +## 0.18.2 + +- Include definitions of namespace members that are exported as defaults + +## 0.18.1 + +- Include `acorn.parse` in bundle, remove `sander` from dependencies, simplify build + +## 0.18.0 + +- Internal rewrite +- Reinstate statically-analysable namespace imports +- Avoid using getters in namespace blocks where possible ([#144](https://github.com/rollup/rollup/issues/144)) +- Track variable aliases ([#96](https://github.com/rollup/rollup/issues/96)) +- Prevent multiline strings being indented ([#164](https://github.com/rollup/rollup/issues/164)) + +## 0.17.4 + +- Allow imports from hidden directories (replay of [#133](https://github.com/rollup/rollup/issues/133)) + +## 0.17.3 + +- Handle parenthesised default exports ([#136](https://github.com/rollup/rollup/issues/136)) + +## 0.17.2 + +- Allow use of scoped npm packages ([#131](https://github.com/rollup/rollup/issues/131)) + +## 0.17.1 + +- Allow namespaces to be passed to a function ([#149](https://github.com/rollup/rollup/issues/149)) + +## 0.17.0 + +- Roll back to 0.15.0 and reapply subsequent fixes pending resolution of ([#132](https://github.com/rollup/rollup/issues/132)) and related issues + +## 0.16.4 + +- Fix import paths with `.` ([#133](https://github.com/rollup/rollup/issues/133)) +- Prevent sourceMappingURL confusion leading to broken sourcemap +- Add code coverage reporting [#130](https://github.com/rollup/rollup/pull/130)) +- Add `modules` property to user-facing `bundle` – an array with `{id}` objects ([#128](https://github.com/rollup/rollup/issues/128)) + +## 0.16.3 + +- Prevent adjacent blocks of multiple var declarations causing magic-string failure ([#105](https://github.com/rollup/rollup/issues/105)) + +## 0.16.2 + +- Top-level function calls and assignments to globals are treated as side-effects, and always included +- Import files from subdirectories of external packages, e.g. `import mod from 'foo/sub/mod'` ([#126](https://github.com/rollup/rollup/issues/126)) + +## 0.16.1 + +- Handle assignment patterns, and destructured/rest parameters, when analysing scopes +- Fix bug preventing project from self-building (make base `Identifier` class markable) + +## 0.16.0 + +- Internal refactoring ([#99](https://github.com/rollup/rollup/pull/99)) +- Optimisation for statically-analysable namespace imports ([#99](https://github.com/rollup/rollup/pull/99)) +- Windows support (theoretically!) ([#117](https://github.com/rollup/rollup/pull/117) / [#119](https://github.com/rollup/rollup/pull/119)) + +## 0.15.0 + +- Load all modules specified by `import` statements, and do tree-shaking synchronously once loading is complete. This results in simpler and faster code, and enables future improvements ([#97](https://github.com/rollup/rollup/pull/97)) +- Only rewrite `foo` as `exports.foo` when it makes sense to ([#92](https://github.com/rollup/rollup/issues/92)) +- Fix bug with shadowed variables that are eventually exported ([#91](https://github.com/rollup/rollup/issues/91)) +- Exclude unused function declarations that happen to modify a used name ([#90](https://github.com/rollup/rollup/pull/90)) +- Simplify internal `Scope` model – scopes always attach to blocks, never function expressions/declarations + +## 0.14.1 + +- `export { name } from './other'` does not create a local binding ([#16](https://github.com/rollup/rollup/issues/16)) +- A single binding can be exported under multiple names ([#18](https://github.com/rollup/rollup/issues/18)) +- `useStrict` option exposed to CLI as `--strict`/`--no-strict` ([#81](https://github.com/rollup/rollup/issues/81)) +- Neater exports from ES6 bundles + +## 0.14.0 + +- Internal refactoring +- Correctly deconflict generated default export names ([#72](https://github.com/rollup/rollup/issues/72)) +- Handle `export { x } from 'y'` declarations ([#74](https://github.com/rollup/rollup/issues/74)) +- Dedupe named imports from external modules in ES6 bundles ([#77](https://github.com/rollup/rollup/issues/77)) + +## 0.13.0 + +- Support `banner` and `footer` options ([#66](https://github.com/rollup/rollup/pull/66)) +- Remove pre-existing sourcemap comments ([#66](https://github.com/rollup/rollup/pull/66)) +- Deconflict external imports ([#66](https://github.com/rollup/rollup/pull/66)) +- Use existing AST, if provided ([#66](https://github.com/rollup/rollup/pull/66)) +- Rename internal namespace exports as appropriate ([#66](https://github.com/rollup/rollup/pull/66)) +- Remove uninitialised var declarations that get exported ([#66](https://github.com/rollup/rollup/pull/66)) +- Rename variables named `exports` to avoid conflicts ([#66](https://github.com/rollup/rollup/pull/66)) + +## 0.12.1 + +- Don't attempt to mark statements belonging to external modules ([#68](https://github.com/rollup/rollup/issues/68)) +- Correctly deshadow variables that conflict with imports ([#68](https://github.com/rollup/rollup/issues/68)) + +## 0.12.0 + +- Internal re-architecting, resulting in more efficient bundling with reduced memory usage +- Shorthand properties are expanded if necessary ([#61](https://github.com/rollup/rollup/issues/61)) +- Fixed various bugs with bundle external dependencies, particularly when generating ES6 bundles ([#59](https://github.com/rollup/rollup/issues/59)) +- Add `--globals` option to CLI ([#60](https://github.com/rollup/rollup/pull/60)) +- Allow imports of external modules for side-effects ([#55](https://github.com/rollup/rollup/pull/55)) +- Prevent Rollup hanging on non-existent external module ([#54](https://github.com/rollup/rollup/pull/54)) + +## 0.11.4 + +- Side-effect preservation applies to internal default exports ([#43](https://github.com/rollup/rollup/issues/43)) + +## 0.11.3 + +- Class methods are not incorrectly renamed ([#42](https://github.com/rollup/rollup/issues/42)) +- External modules are assigned names before canonical names are determined ([#42](https://github.com/rollup/rollup/issues/42)) + +## 0.11.2 + +- Correctly handle computed properties (e.g. `foo[bar]`) when discovering dependencies ([#47](https://github.com/rollup/rollup/pull/47)) + +## 0.11.1 + +- Support for `export * from '..'` ([#46](https://github.com/rollup/rollup/pull/46)) + +## 0.11.0 + +- Experimental browser-friendly build (`dist/rollup.browser.js`) ([#25](https://github.com/rollup/rollup/issues/25)) +- Internal re-architecting to make discovery process simpler and more performant +- Preservation of side-effects that happen in a separate module to the affected definition ([#39](https://github.com/rollup/rollup/issues/39)) + +## 0.10.0 + +- Better sorting algorithm – sorting happens at the module level, rather than the statement level. This avoids certain edge cases +- IIFEs are ignored for the purposes of distinguishing between 'strong' and 'weak' dependencies +- Empty `var` declarations for exported bindings are omitted + +## 0.9.1 + +- Much faster statement insertion (fixes major 0.9.0 performance regression) + +## 0.9.0 + +- BREAKING - `resolvePath` is now `resolveId`. The returned `id` (which by default is a filepath) is passed to the `load` function, which can optionally be overridden, and which is applied to all modules including the entry module. This allows custom resolver and loading logic for integration with third party systems (e.g. JSPM) or, eventually, in-browser usage ([#30](https://github.com/rollup/rollup/issues/30)) +- A statement cannot appear after later statements from the same bundle ([#34](https://github.com/rollup/rollup/issues/34)) +- Tricky cyclical dependencies are handled ([#36](https://github.com/rollup/rollup/issues/36)) +- `sourcemap` option is used by CLI (was omitted previously) + +## 0.8.3 + +- Correctly rename functions that have arguments with the same name ([#32](https://github.com/rollup/rollup/issues/32)) +- Ensure unused default exports are given a legal name ([#33](https://github.com/rollup/rollup/issues/33)) + +## 0.8.2 + +- Support `moduleId` and `moduleName` via CLI ([#24](https://github.com/rollup/rollup/issues/24)) + +## 0.8.1 + +- Anonymous functions that are exported as default are converted to named function declarations for correct hoisting, rather than being bound to functions ([#29](https://github.com/rollup/rollup/issues/29)) +- Automatically-generated default export names are deconflicted with local definitions ([#29](https://github.com/rollup/rollup/issues/29)) + +## 0.8.0 + +- Top-level variable declarations with multiple declarators are split up, to avoid unnecessary code importing and incorrectly-ordered statements ([#26](https://github.com/rollup/rollup/issues/26)) +- `this` at the top level is `undefined` ([#28](https://github.com/rollup/rollup/issues/28)) + +## 0.7.8 + +- Avoid using `path.parse` - unsupported in node 0.10 + +## 0.7.7 + +- Promise `source-map-support` from `devDependencies` to `dependencies` ([#23](https://github.com/rollup/rollup/issues/23)) + +## 0.7.6 + +- Better placement of `export default` statements ([#21](https://github.com/rollup/rollup/issues/21)) +- Prevent function calls and property assignments from being treated as rebinding for sake of unbound default exports +- Add `--external foo,bar,baz` option to CLI (equivalent to `external: ['foo', 'bar', 'baz']`) +- Add CLI tests + +## 0.7.5 + +- Prevent accidental conflicts with the global namespace ([#20](https://github.com/rollup/rollup/issues/20)) + +## 0.7.4 + +- More precise statement re-ordering to satisfy `export default` constraint (fixes bug introduced in 0.7.3) + +## 0.7.3 + +- Default exports are not bound. To enable this, statements within a module are sorted to retain their original order ([#15](https://github.com/rollup/rollup/issues/15)) +- Better positioning of comments ([#14](https://github.com/rollup/rollup/issues/14)) +- Various fixes to get Travis-CI rigged up + +## 0.7.2 + +- Fix sourcemap paths on Windows ([#6](https://github.com/rollup/rollup/pull/6)) + +## 0.7.1 + +- Named functions can be used as default exports from a bundle +- Method calls are assumed to mutate the owner (i.e. `foo.bar()` mutates `foo`) ([#13](https://github.com/rollup/rollup/issues/13)) +- `options.indent` can be used to control indentation of resulting bundle. `options.true` (default) means 'auto', `options.false` means empty string. Alternatively specify whitespace e.g. `' '` or `'\t'` ([#5](https://github.com/rollup/rollup/issues/5)) + +## 0.7.0 + +- Ensure statements are always separated by a newline ([#9](https://github.com/rollup/rollup/pull/9)) +- Use CommonJS `exports` correctly (UMD exports) +- Throw error if `moduleName` is required but missing (UMD exports) +- Attach IIFE global to `this` rather than `window` +- Allow names inside bundle to the the names of `Object.prototype` properties ([#12](https://github.com/rollup/rollup/pull/12)) +- Keep exports live ([#11](https://github.com/rollup/rollup/pull/11)) + +## 0.6.5 + +- Add sourceMappingURL comment to code, as appropriate +- Higher resolution sourcemaps + +## 0.6.4 + +- Fix CJS bundling with default export + +## 0.6.3 + +- Fix exports and external module imports with some output formats +- Fix endless cycle bug on Windows ([#3](https://github.com/rollup/rollup/pull/3)) - thanks @Bobris + +## 0.6.2 + +- Permit assignments to properties of imported bindings + +## 0.6.1 + +- Support for basic transformers + +## 0.6.0 + +- BREAKING - `rollup.rollup` and `bundle.write` both take a single options argument +- BREAKING - external modules must be declared upfront with `options.external: [...]` +- Non-relative module paths will be resolved by looking for `jsnext:main` fields in the appropriate `package.json` files. This behaviour can be overridden by passing an alternative `resolveExternal` function +- Fix sourcemap options +- Include CLI files in npm package (duh) + +## 0.5.0 + +- Command line interface +- Sourcemap generation +- Correct behaviour with `export { x as y } from 'z'` + +## 0.4.1 + +- More import name deconflicting + +## 0.4.0 + +- Self-hosting! `rollup.rollup` now rolls up rollup +- Fix bug with comments inside a statement later being appended to it +- Prevent shadowing of external modules +- Rewrite computed property identifiers where necessary +- Preserve original statement order where possible +- Internal refactoring + +## 0.3.1 + +- Saner deconflicting +- Rename namespace imports from external modules correctly + +## 0.3.0 + +- Basic functionality present, mostly spec-compliant + +## 0.2.1 + +- Include dist files in npm package (duh) + +## 0.2.0 + +- First release capable of doing anything useful +- Still lots of basic functionality missing + +## 0.1.0 + +- Initial experiment diff --git a/node_modules/rollup/LICENSE.md b/node_modules/rollup/LICENSE.md new file mode 100644 index 0000000..7aa84ce --- /dev/null +++ b/node_modules/rollup/LICENSE.md @@ -0,0 +1,739 @@ +# Rollup core license +Rollup is released under the MIT license: + +The MIT License (MIT) + +Copyright (c) 2017 [these people](https://github.com/rollup/rollup/graphs/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +# Licenses of bundled dependencies +The published Rollup artifact additionally contains code with the following licenses: +MIT, ISC + +# Bundled dependencies: +## acorn +License: MIT +By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine +Repository: https://github.com/acornjs/acorn.git + +> MIT License +> +> Copyright (C) 2012-2020 by various contributors (see AUTHORS) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## acorn-walk +License: MIT +By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine +Repository: https://github.com/acornjs/acorn.git + +> MIT License +> +> Copyright (C) 2012-2020 by various contributors (see AUTHORS) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## anymatch +License: ISC +By: Elan Shanker +Repository: https://github.com/micromatch/anymatch + +> The ISC License +> +> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) +> +> 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. + +--------------------------------------- + +## binary-extensions +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/binary-extensions + +> MIT License +> +> Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), 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: +> +> 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. + +--------------------------------------- + +## braces +License: MIT +By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm +Repository: micromatch/braces + +> The MIT License (MIT) +> +> Copyright (c) 2014-2018, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## chokidar +License: MIT +By: Paul Miller, Elan Shanker +Repository: git+https://github.com/paulmillr/chokidar.git + +> The MIT License (MIT) +> +> Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker +> +> 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. + +--------------------------------------- + +## colorette +License: MIT +By: Jorge Bucaran +Repository: jorgebucaran/colorette + +> Copyright © Jorge Bucaran <> +> +> 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. + +--------------------------------------- + +## date-time +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/date-time + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## fill-range +License: MIT +By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling +Repository: jonschlinkert/fill-range + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## glob-parent +License: ISC +By: Gulp Team, Elan Shanker, Blaine Bublitz +Repository: gulpjs/glob-parent + +> The ISC License +> +> Copyright (c) 2015, 2019 Elan Shanker +> +> 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. + +--------------------------------------- + +## hash.js +License: MIT +By: Fedor Indutny +Repository: git@github.com:indutny/hash.js + +--------------------------------------- + +## inherits +License: ISC +Repository: git://github.com/isaacs/inherits + +> The ISC License +> +> Copyright (c) Isaac Z. Schlueter +> +> 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. + +--------------------------------------- + +## is-binary-path +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-binary-path + +> MIT License +> +> Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), 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: +> +> 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. + +--------------------------------------- + +## is-extglob +License: MIT +By: Jon Schlinkert +Repository: jonschlinkert/is-extglob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2016, Jon Schlinkert +> +> 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. + +--------------------------------------- + +## is-glob +License: MIT +By: Jon Schlinkert, Brian Woodward, Daniel Perez +Repository: micromatch/is-glob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2017, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## is-number +License: MIT +By: Jon Schlinkert, Olsten Larck, Rouven Weßling +Repository: jonschlinkert/is-number + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## is-reference +License: MIT +By: Rich Harris +Repository: git+https://github.com/Rich-Harris/is-reference.git + +--------------------------------------- + +## locate-character +License: MIT +By: Rich Harris +Repository: Rich-Harris/locate-character + +--------------------------------------- + +## magic-string +License: MIT +By: Rich Harris +Repository: https://github.com/rich-harris/magic-string + +> Copyright 2018 Rich Harris +> +> 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. + +--------------------------------------- + +## micromatch +License: MIT +By: Jon Schlinkert, Amila Welihinda, Bogdan Chadkin, Brian Woodward, Devon Govett, Elan Shanker, Fabrício Matté, Martin Kolárik, Olsten Larck, Paul Miller, Tom Byrer, Tyler Akins, Peter Bright, Kuba Juszczyk +Repository: micromatch/micromatch + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## minimalistic-assert +License: ISC +Repository: https://github.com/calvinmetcalf/minimalistic-assert.git + +> Copyright 2015 Calvin Metcalf +> +> 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. + +--------------------------------------- + +## normalize-path +License: MIT +By: Jon Schlinkert, Blaine Bublitz +Repository: jonschlinkert/normalize-path + +> The MIT License (MIT) +> +> Copyright (c) 2014-2018, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## parse-ms +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/parse-ms + +> 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. + +--------------------------------------- + +## picomatch +License: MIT +By: Jon Schlinkert +Repository: micromatch/picomatch + +> The MIT License (MIT) +> +> Copyright (c) 2017-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## pretty-bytes +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/pretty-bytes + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## pretty-ms +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/pretty-ms + +> 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. + +--------------------------------------- + +## readdirp +License: MIT +By: Thorsten Lorenz, Paul Miller +Repository: git://github.com/paulmillr/readdirp.git + +> MIT License +> +> Copyright (c) 2012-2019 Thorsten Lorenz, 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: +> +> 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. + +--------------------------------------- + +## require-relative +License: MIT +By: Valerio Proietti +Repository: git://github.com/kamicane/require-relative.git + +--------------------------------------- + +## rollup-pluginutils +License: MIT +By: Rich Harris +Repository: rollup/rollup-pluginutils + +--------------------------------------- + +## signal-exit +License: ISC +By: Ben Coe +Repository: https://github.com/tapjs/signal-exit.git + +> The ISC License +> +> Copyright (c) 2015, 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 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. + +--------------------------------------- + +## sourcemap-codec +License: MIT +By: Rich Harris +Repository: https://github.com/Rich-Harris/sourcemap-codec + +> The MIT License +> +> Copyright (c) 2015 Rich Harris +> +> 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. + +--------------------------------------- + +## time-zone +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/time-zone + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## to-regex-range +License: MIT +By: Jon Schlinkert, Rouven Weßling +Repository: micromatch/to-regex-range + +> The MIT License (MIT) +> +> Copyright (c) 2015-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## yargs-parser +License: ISC +By: Ben Coe +Repository: https://github.com/yargs/yargs-parser.git + +> Copyright (c) 2016, 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 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/rollup/README.md b/node_modules/rollup/README.md new file mode 100644 index 0000000..7cf59ff --- /dev/null +++ b/node_modules/rollup/README.md @@ -0,0 +1,127 @@ +

+ +

+ +

+ + npm version + + + install size + + + code coverage + + + backers + + + sponsors + + + license + + + dependency status + + + Join the chat at https://is.gd/rollup_chat + +

+ +

Rollup

+ +## Overview + +Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the standardized ES module format for code, instead of previous idiosyncratic solutions such as CommonJS and AMD. ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. Rollup can optimize ES modules for faster native loading in modern browsers, or output a legacy module format allowing ES module workflows today. + +## Quick Start Guide + +Install with `npm install --global rollup`. Rollup can be used either through a [command line interface](https://rollupjs.org/#command-line-reference) with an optional configuration file, or else through its [JavaScript API](https://rollupjs.org/guide/en/#javascript-api). Run `rollup --help` to see the available options and parameters. The starter project templates, [rollup-starter-lib](https://github.com/rollup/rollup-starter-lib) and [rollup-starter-app](https://github.com/rollup/rollup-starter-app), demonstrate common configuration options, and more detailed instructions are available throughout the [user guide](https://rollupjs.org/). + +### Commands + +These commands assume the entry point to your application is named main.js, and that you'd like all imports compiled into a single file named bundle.js. + +For browsers: + +```bash +# compile to a + +-------------------------------------------------------------------------------- + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' +}; + +var smc = new SourceMapConsumer(rawSourceMap); + +console.log(smc.sources); +// [ 'http://example.com/www/js/one.js', +// 'http://example.com/www/js/two.js' ] + +console.log(smc.originalPositionFor({ + line: 2, + column: 28 +})); +// { source: 'http://example.com/www/js/two.js', +// line: 2, +// column: 10, +// name: 'n' } + +console.log(smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 +})); +// { line: 2, column: 28 } + +smc.eachMapping(function (m) { + // ... +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } +} + +var ast = parse("40 + 2", "add.js"); +console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' +})); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: "source-mapped.js" +}); + +map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); +``` + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +```js +var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +``` + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] + +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +* `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +* `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +* `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }) +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor("my-cool-lib.clj") +// "..." + +consumer.sourceContentFor("this is not in the source map"); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor("this is not in the source map", true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { console.log(m); }) +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +* `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: "my-generated-javascript-file.js", + sourceRoot: "http://example.com/app/js/" +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +* `sourceMapConsumer` The SourceMap. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: "module-one.scm", + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 } +}) +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +```js +generator.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString() +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, "a.cpp", [ + new SourceNode(3, 4, "b.cpp", "extern int status;\n"), + new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); +var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), + consumer); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(" + "); +node.add(otherNode); +node.add([leftHandOperandNode, " + ", rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend("/** Build Id: f783haef86324gf **/\n\n"); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +```js +node.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, "a.js", "generated from a"); +a.setSourceContent("a.js", "original a"); +var b = new SourceNode(1, 2, "b.js", "generated from b"); +b.setSourceContent("b.js", "original b"); +var c = new SourceNode(1, 2, "c.js", "generated from c"); +c.setSourceContent("c.js", "original c"); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); +var operand = new SourceNode(3, 4, "a.rs", "="); +var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); + +var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var joinedNode = node.join(" "); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ""); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toString() +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toStringWithSourceMap({ file: "my-output-file.js" }) +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/node_modules/source-map/dist/source-map.debug.js b/node_modules/source-map/dist/source-map.debug.js new file mode 100644 index 0000000..aad0620 --- /dev/null +++ b/node_modules/source-map/dist/source-map.debug.js @@ -0,0 +1,3234 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vd2VicGFjay91bml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uIiwid2VicGFjazovLy93ZWJwYWNrL2Jvb3RzdHJhcCAxNjI0YzcyOTliODg3ZjdiZGY2NCIsIndlYnBhY2s6Ly8vLi9zb3VyY2UtbWFwLmpzIiwid2VicGFjazovLy8uL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LXZscS5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LmpzIiwid2VicGFjazovLy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NvbnRpbnVlO1xuICAgICAgICAgIH1cbiAgICAgICAgICBuZXh0ICs9ICcsJztcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5nZW5lcmF0ZWRDb2x1bW5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgaWYgKG1hcHBpbmcuc291cmNlICE9IG51bGwpIHtcbiAgICAgICAgc291cmNlSWR4ID0gdGhpcy5fc291cmNlcy5pbmRleE9mKG1hcHBpbmcuc291cmNlKTtcbiAgICAgICAgbmV4dCArPSBiYXNlNjRWTFEuZW5jb2RlKHNvdXJjZUlkeCAtIHByZXZpb3VzU291cmNlKTtcbiAgICAgICAgcHJldmlvdXNTb3VyY2UgPSBzb3VyY2VJZHg7XG5cbiAgICAgICAgLy8gbGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkIGluIFNvdXJjZU1hcCBzcGVjIHZlcnNpb24gM1xuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbExpbmUgLSAxXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNPcmlnaW5hbExpbmUpO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsTGluZSA9IG1hcHBpbmcub3JpZ2luYWxMaW5lIC0gMTtcblxuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbENvbHVtblxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtIHByZXZpb3VzT3JpZ2luYWxDb2x1bW4pO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsQ29sdW1uID0gbWFwcGluZ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A8IDApIHtcbiAgICAgIHJldHVybiBbXTtcbiAgICB9XG5cbiAgICB2YXIgbWFwcGluZ3MgPSBbXTtcblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRNYXBwaW5nKG5lZWRsZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwib3JpZ2luYWxMaW5lXCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJvcmlnaW5hbENvbHVtblwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHV0aWwuY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYmluYXJ5U2VhcmNoLkxFQVNUX1VQUEVSX0JPVU5EKTtcbiAgICBpZiAoaW5kZXggPj0gMCkge1xuICAgICAgdmFyIG1hcHBpbmcgPSB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgaWYgKGFBcmdzLmNvbHVtbiA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIHZhciBvcmlnaW5hbExpbmUgPSBtYXBwaW5nLm9yaWdpbmFsTGluZTtcblxuICAgICAgICAvLyBJdGVyYXRlIHVudGlsIGVpdGhlciB3ZSBydW4gb3V0IG9mIG1hcHBpbmdzLCBvciB3ZSBydW4gaW50b1xuICAgICAgICAvLyBhIG1hcHBpbmcgZm9yIGEgZGlmZmVyZW50IGxpbmUgdGhhbiB0aGUgb25lIHdlIGZvdW5kLiBTaW5jZVxuICAgICAgICAvLyBtYXBwaW5ncyBhcmUgc29ydGVkLCB0aGlzIGlzIGd1YXJhbnRlZWQgdG8gZmluZCBhbGwgbWFwcGluZ3MgZm9yXG4gICAgICAgIC8vIHRoZSBsaW5lIHdlIGZvdW5kLlxuICAgICAgICB3aGlsZSAobWF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TdHIsIGVuZCkpIHtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBzdHIgPSBhU3RyLnNsaWNlKGluZGV4LCBlbmQpO1xuXG4gICAgICAgIHNlZ21lbnQgPSBjYWNoZWRTZWdtZW50c1tzdHJdO1xuICAgICAgICBpZiAoc2VnbWVudCkge1xuICAgICAgICAgIGluZGV4ICs9IHN0ci5sZW5ndGg7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgc2VnbWVudCA9IFtdO1xuICAgICAgICAgIHdoaWxlIChpbmRleCA8IGVuZCkge1xuICAgICAgICAgICAgYmFzZTY0VkxRLmRlY29kZShhU3RyLCBpbmRleCwgdGVtcCk7XG4gICAgICAgICAgICB2YWx1ZSA9IHRlbXAudmFsdWU7XG4gICAgICAgICAgICBpbmRleCA9IHRlbXAucmVzdDtcbiAgICAgICAgICAgIHNlZ21lbnQucHVzaCh2YWx1ZSk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAyKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlLCBidXQgbm8gbGluZSBhbmQgY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAzKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlIGFuZCBsaW5lLCBidXQgbm8gY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgY2FjaGVkU2VnbWVudHNbc3RyXSA9IHNlZ21lbnQ7XG4gICAgICAgIH1cblxuICAgICAgICAvLyBHZW5lcmF0ZWQgY29sdW1uLlxuICAgICAgICBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbiA9IHByZXZpb3VzR2VuZXJhdGVkQ29sdW1uICsgc2VnbWVudFswXTtcbiAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiAxKSB7XG4gICAgICAgICAgLy8gT3JpZ2luYWwgc291cmNlLlxuICAgICAgICAgIG1hcHBpbmcuc291cmNlID0gcHJldmlvdXNTb3VyY2UgKyBzZWdtZW50WzFdO1xuICAgICAgICAgIHByZXZpb3VzU291cmNlICs9IHNlZ21lbnRbMV07XG5cbiAgICAgICAgICAvLyBPcmlnaW5hbCBsaW5lLlxuICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxMaW5lID0gcHJldmlvdXNPcmlnaW5hbExpbmUgKyBzZWdtZW50WzJdO1xuICAgICAgICAgIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gbWFwcGluZy5vcmlnaW5hbExpbmU7XG4gICAgICAgICAgLy8gTGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkXG4gICAgICAgICAgbWFwcGluZy5vcmlnaW5hbExpbmUgKz0gMTtcblxuICAgICAgICAgIC8vIE9yaWdpbmFsIGNvbHVtbi5cbiAgICAgICAgICBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uID0gcHJldmlvdXNPcmlnaW5hbENvbHVtbiArIHNlZ21lbnRbM107XG4gICAgICAgICAgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IG1hcHBpbmcub3JpZ2luYWxDb2x1bW47XG5cbiAgICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiA0KSB7XG4gICAgICAgICAgICAvLyBPcmlnaW5hbCBuYW1lLlxuICAgICAgICAgICAgbWFwcGluZy5uYW1lID0gcHJldmlvdXNOYW1lICsgc2VnbWVudFs0XTtcbiAgICAgICAgICAgIHByZXZpb3VzTmFtZSArPSBzZWdtZW50WzRdO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuXG4gICAgICAgIGdlbmVyYXRlZE1hcHBpbmdzLnB1c2gobWFwc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HNlIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IGFSZWxhdGl2ZVBhdGhcbiAgICAgICAgICA/IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICA6IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBub2RlLmFkZChuZXcgU291cmNlTm9kZShtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBtYXBwaW5nLm5hbWUpKTtcbiAgICAgIH1cbiAgICB9XG4gIH07XG5cbi8qKlxuICogQWRkIGEgY2h1bmsgb2YgZ2VuZXJhdGVkIEpTIHRvIHRoaXMgc291cmNlIG5vZGUuXG4gKlxuICogQHBhcmFtIGFDaHVuayBBIHN0cmluZyBzbmlwcGV0IG9mIGdlbmVyYXRlZCBKUyBjb2RlLCBhbm90aGVyIGluc3RhbmNlIG9mXG4gKiAgICAgICAgU291cmNlTm9kZSwgb3IgYW4gYXJyYXkgd2hlcmUgZWFjaCBtZW1iZXIgaXMgb25lIG9mIHRob3NlIHRoaW5ncy5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUuYWRkID0gZnVuY3Rpb24gU291cmNlTm9kZV9hZGQoYUNodW5rKSB7XG4gIGlmIChBcnJheS5pc0FycmF5KGFDaHVuaykpIHtcbiAgICBhQ2h1bmsuZm9yRWFjaChmdW5jdGlvbiAoY2h1bmspIHtcbiAgICAgIHRoaXMuYWRkKGNodW5rKTtcbiAgICB9LCB0aGlzKTtcbiAgfVxuICBlbHNlIGlmIChhQ2h1bmtbaXNTb3VyY2VOb2RlXSB8fCB0eXBlb2YgYUNodW5rID09PSBcInN0cmlu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hbDoge1xuICAgICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgICBjb2x1bW46IG9yaWdpbmFsLmNvbHVtblxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWQubGluZSxcbiAgICAgICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWQuY29sdW1uXG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgbmFtZTogb3JpZ2luYWwubmFtZVxuICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBnZW5lcmF0ZWQuY29sdW1uKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcbiAgdGhpcy53YWxrU291cmNlQ29udGVudHMoZnVuY3Rpb24gKHNvdXJjZUZpbGUsIHNvdXJjZUNvbnRlbnQpIHtcbiAgICBtYXAuc2V0U291cmNlQ29udGVudChzb3VyY2VGaWxlLCBzb3VyY2VDb250ZW50KTtcbiAgfSk7XG5cbiAgcmV0dXJuIHsgY29kZTogZ2VuZXJhdGVkLmNvZGUsIG1hcDogbWFwIH07XG59O1xuXG5leHBvcnRzLlNvdXJjZU5vZGUgPSBTb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW5vZGUuanNcbi8vIG1vZHVsZSBpZCA9IDEwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCJdLCJzb3VyY2VSb290IjoiIn0= \ No newline at end of file diff --git a/node_modules/source-map/dist/source-map.js b/node_modules/source-map/dist/source-map.js new file mode 100644 index 0000000..b4eb087 --- /dev/null +++ b/node_modules/source-map/dist/source-map.js @@ -0,0 +1,3233 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/node_modules/source-map/dist/source-map.min.js b/node_modules/source-map/dist/source-map.min.js new file mode 100644 index 0000000..c7c72da --- /dev/null +++ b/node_modules/source-map/dist/source-map.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.sourceMap=n():e.sourceMap=n()}(this,function(){return function(e){function n(t){if(r[t])return r[t].exports;var o=r[t]={exports:{},id:t,loaded:!1};return e[t].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=e,n.c=r,n.p="",n(0)}([function(e,n,r){n.SourceMapGenerator=r(1).SourceMapGenerator,n.SourceMapConsumer=r(7).SourceMapConsumer,n.SourceNode=r(10).SourceNode},function(e,n,r){function t(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new s,this._names=new s,this._mappings=new a,this._sourcesContents=null}var o=r(2),i=r(4),s=r(5).ArraySet,a=r(6).MappingList;t.prototype._version=3,t.fromSourceMap=function(e){var n=e.sourceRoot,r=new t({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(t.source=e.source,null!=n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(t.name=e.name)),r.addMapping(t)}),e.sources.forEach(function(t){var o=t;null!==n&&(o=i.relative(n,t)),r._sources.has(o)||r._sources.add(o);var s=e.sourceContentFor(t);null!=s&&r.setSourceContent(t,s)}),r},t.prototype.addMapping=function(e){var n=i.getArg(e,"generated"),r=i.getArg(e,"original",null),t=i.getArg(e,"source",null),o=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,t,o),null!=t&&(t=String(t),this._sources.has(t)||this._sources.add(t)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:t,name:o})},t.prototype.setSourceContent=function(e,n){var r=e;null!=this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),null!=n?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[i.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},t.prototype.applySourceMap=function(e,n,r){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=i.relative(o,t));var a=new s,u=new s;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var s=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=s.source&&(n.source=s.source,null!=r&&(n.source=i.join(r,n.source)),null!=o&&(n.source=i.relative(o,n.source)),n.originalLine=s.line,n.originalColumn=s.column,null!=s.name&&(n.name=s.name))}var l=n.source;null==l||a.has(l)||a.add(l);var c=n.name;null==c||u.has(c)||u.add(c)},this),this._sources=a,this._names=u,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=r&&(n=i.join(r,n)),null!=o&&(n=i.relative(o,n)),this.setSourceContent(n,t))},this)},t.prototype._validateMapping=function(e,n,r,t){if(n&&"number"!=typeof n.line&&"number"!=typeof n.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||n||r||t)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:t}))},t.prototype._serializeMappings=function(){for(var e,n,r,t,s=0,a=1,u=0,l=0,c=0,g=0,p="",h=this._mappings.toArray(),f=0,d=h.length;f0){if(!i.compareByGeneratedPositionsInflated(n,h[f-1]))continue;e+=","}e+=o.encode(n.generatedColumn-s),s=n.generatedColumn,null!=n.source&&(t=this._sources.indexOf(n.source),e+=o.encode(t-g),g=t,e+=o.encode(n.originalLine-1-l),l=n.originalLine-1,e+=o.encode(n.originalColumn-u),u=n.originalColumn,null!=n.name&&(r=this._names.indexOf(n.name),e+=o.encode(r-c),c=r)),p+=e}return p},t.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var r=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},t.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},t.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=t},function(e,n,r){function t(e){return e<0?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),r=e>>1;return n?-r:r}var i=r(3),s=5,a=1<>>=s,o>0&&(n|=l),r+=i.encode(n);while(o>0);return r},n.decode=function(e,n,r){var t,a,c=e.length,g=0,p=0;do{if(n>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(a=i.decode(e.charCodeAt(n++)),a===-1)throw new Error("Invalid base64 digit: "+e.charAt(n-1));t=!!(a&l),a&=u,g+=a<=0;c--)s=u[c],"."===s?u.splice(c,1):".."===s?l++:l>0&&(""===s?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=a?"/":"."),i?(i.path=r,o(i)):r}function s(e,n){""===e&&(e="."),""===n&&(n=".");var r=t(n),s=t(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),o(r);if(r||n.match(y))return n;if(s&&!s.host&&!s.path)return s.host=n,o(s);var a="/"===n.charAt(0)?n:i(e.replace(/\/+$/,"")+"/"+n);return s?(s.path=a,o(s)):a}function a(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==n.indexOf(e+"/");){var t=e.lastIndexOf("/");if(t<0)return n;if(e=e.slice(0,t),e.match(/^([^\/]+:\/)?\/*$/))return n;++r}return Array(r+1).join("../")+n.substr(e.length+1)}function u(e){return e}function l(e){return g(e)?"$"+e:e}function c(e){return g(e)?e.slice(1):e}function g(e){if(!e)return!1;var n=e.length;if(n<9)return!1;if(95!==e.charCodeAt(n-1)||95!==e.charCodeAt(n-2)||111!==e.charCodeAt(n-3)||116!==e.charCodeAt(n-4)||111!==e.charCodeAt(n-5)||114!==e.charCodeAt(n-6)||112!==e.charCodeAt(n-7)||95!==e.charCodeAt(n-8)||95!==e.charCodeAt(n-9))return!1;for(var r=n-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,n,r){var t=f(e.source,n.source);return 0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t||r?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=e.generatedLine-n.generatedLine,0!==t?t:f(e.name,n.name)))))}function h(e,n,r){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t||r?t:(t=f(e.source,n.source),0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:f(e.name,n.name)))))}function f(e,n){return e===n?0:null===e?1:null===n?-1:e>n?1:-1}function d(e,n){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=f(e.source,n.source),0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:f(e.name,n.name)))))}function m(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}function _(e,n,r){if(n=n||"",e&&("/"!==e[e.length-1]&&"/"!==n[0]&&(e+="/"),n=e+n),r){var a=t(r);if(!a)throw new Error("sourceMapURL could not be parsed");if(a.path){var u=a.path.lastIndexOf("/");u>=0&&(a.path=a.path.substring(0,u+1))}n=s(o(a),n)}return i(n)}n.getArg=r;var v=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,y=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=o,n.normalize=i,n.join=s,n.isAbsolute=function(e){return"/"===e.charAt(0)||v.test(e)},n.relative=a;var C=function(){var e=Object.create(null);return!("__proto__"in e)}();n.toSetString=C?u:l,n.fromSetString=C?u:c,n.compareByOriginalPositions=p,n.compareByGeneratedPositionsDeflated=h,n.compareByGeneratedPositionsInflated=d,n.parseSourceMapInput=m,n.computeSourceURL=_},function(e,n,r){function t(){this._array=[],this._set=s?new Map:Object.create(null)}var o=r(4),i=Object.prototype.hasOwnProperty,s="undefined"!=typeof Map;t.fromArray=function(e,n){for(var r=new t,o=0,i=e.length;o=0)return n}else{var r=o.toSetString(e);if(i.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},t.prototype.at=function(e){if(e>=0&&er||t==r&&s>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=r(4);o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){t(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=o},function(e,n,r){function t(e,n){var r=e;return"string"==typeof e&&(r=a.parseSourceMapInput(e)),null!=r.sections?new s(r,n):new o(r,n)}function o(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var t=a.getArg(r,"version"),o=a.getArg(r,"sources"),i=a.getArg(r,"names",[]),s=a.getArg(r,"sourceRoot",null),u=a.getArg(r,"sourcesContent",null),c=a.getArg(r,"mappings"),g=a.getArg(r,"file",null);if(t!=this._version)throw new Error("Unsupported version: "+t);s&&(s=a.normalize(s)),o=o.map(String).map(a.normalize).map(function(e){return s&&a.isAbsolute(s)&&a.isAbsolute(e)?a.relative(s,e):e}),this._names=l.fromArray(i.map(String),!0),this._sources=l.fromArray(o,!0),this._absoluteSources=this._sources.toArray().map(function(e){return a.computeSourceURL(s,e,n)}),this.sourceRoot=s,this.sourcesContent=u,this._mappings=c,this._sourceMapURL=n,this.file=g}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function s(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var o=a.getArg(r,"version"),i=a.getArg(r,"sections");if(o!=this._version)throw new Error("Unsupported version: "+o);this._sources=new l,this._names=new l;var s={line:-1,column:0};this._sections=i.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var r=a.getArg(e,"offset"),o=a.getArg(r,"line"),i=a.getArg(r,"column");if(o=0){var i=this._originalMappings[o];if(void 0===e.column)for(var s=i.originalLine;i&&i.originalLine===s;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var l=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==l;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return t},n.SourceMapConsumer=t,o.prototype=Object.create(t.prototype),o.prototype.consumer=t,o.prototype._findSourceIndex=function(e){var n=e;if(null!=this.sourceRoot&&(n=a.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);var r;for(r=0;r1&&(r.source=d+o[1],d+=o[1],r.originalLine=h+o[2],h=r.originalLine,r.originalLine+=1,r.originalColumn=f+o[3],f=r.originalColumn,o.length>4&&(r.name=m+o[4],m+=o[4])),A.push(r),"number"==typeof r.originalLine&&S.push(r)}g(A,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=A,g(S,a.compareByOriginalPositions),this.__originalMappings=S},o.prototype._findMapping=function(e,n,r,t,o,i){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return u.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[r];if(o.generatedLine===n.generatedLine){var i=a.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),i=a.computeSourceURL(this.sourceRoot,i,this._sourceMapURL));var s=a.getArg(o,"name",null);return null!==s&&(s=this._names.at(s)),{source:i,line:a.getArg(o,"originalLine",null),column:a.getArg(o,"originalColumn",null),name:s}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;var r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];var t=e;null!=this.sourceRoot&&(t=a.relative(this.sourceRoot,t));var o;if(null!=this.sourceRoot&&(o=a.urlParse(this.sourceRoot))){var i=t.replace(/^file:\/\//,"");if("file"==o.scheme&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!o.path||"/"==o.path)&&this._sources.has("/"+t))return this.sourcesContent[this._sources.indexOf("/"+t)]}if(n)return null;throw new Error('"'+t+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=a.getArg(e,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};var r={source:n,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},o=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",t.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===r.source)return{line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=o,s.prototype=Object.create(t.prototype),s.prototype.constructor=t,s.prototype._version=3,Object.defineProperty(s.prototype,"sources",{get:function(){for(var e=[],n=0;n0?t-u>1?r(u,t,o,i,s,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,o,i,s,a):a==n.LEAST_UPPER_BOUND?u:e<0?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,o,i){if(0===t.length)return-1;var s=r(-1,t.length,e,t,o,i||n.GREATEST_LOWER_BOUND);if(s<0)return-1;for(;s-1>=0&&0===o(t[s],t[s-1],!0);)--s;return s}},function(e,n){function r(e,n,r){var t=e[n];e[n]=e[r],e[r]=t}function t(e,n){return Math.round(e+Math.random()*(n-e))}function o(e,n,i,s){if(i=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},t.prototype.walk=function(e){for(var n,r=0,t=this.children.length;r0){for(n=[],r=0;r 0 && aGenerated.column >= 0\n\t && !aOriginal && !aSource && !aName) {\n\t // Case 1.\n\t return;\n\t }\n\t else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n\t && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n\t && aGenerated.line > 0 && aGenerated.column >= 0\n\t && aOriginal.line > 0 && aOriginal.column >= 0\n\t && aSource) {\n\t // Cases 2 and 3.\n\t return;\n\t }\n\t else {\n\t throw new Error('Invalid mapping: ' + JSON.stringify({\n\t generated: aGenerated,\n\t source: aSource,\n\t original: aOriginal,\n\t name: aName\n\t }));\n\t }\n\t };\n\t\n\t/**\n\t * Serialize the accumulated mappings in to the stream of base 64 VLQs\n\t * specified by the source map format.\n\t */\n\tSourceMapGenerator.prototype._serializeMappings =\n\t function SourceMapGenerator_serializeMappings() {\n\t var previousGeneratedColumn = 0;\n\t var previousGeneratedLine = 1;\n\t var previousOriginalColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousName = 0;\n\t var previousSource = 0;\n\t var result = '';\n\t var next;\n\t var mapping;\n\t var nameIdx;\n\t var sourceIdx;\n\t\n\t var mappings = this._mappings.toArray();\n\t for (var i = 0, len = mappings.length; i < len; i++) {\n\t mapping = mappings[i];\n\t next = ''\n\t\n\t if (mapping.generatedLine !== previousGeneratedLine) {\n\t previousGeneratedColumn = 0;\n\t while (mapping.generatedLine !== previousGeneratedLine) {\n\t next += ';';\n\t previousGeneratedLine++;\n\t }\n\t }\n\t else {\n\t if (i > 0) {\n\t if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n\t continue;\n\t }\n\t next += ',';\n\t }\n\t }\n\t\n\t next += base64VLQ.encode(mapping.generatedColumn\n\t - previousGeneratedColumn);\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (mapping.source != null) {\n\t sourceIdx = this._sources.indexOf(mapping.source);\n\t next += base64VLQ.encode(sourceIdx - previousSource);\n\t previousSource = sourceIdx;\n\t\n\t // lines are stored 0-based in SourceMap spec version 3\n\t next += base64VLQ.encode(mapping.originalLine - 1\n\t - previousOriginalLine);\n\t previousOriginalLine = mapping.originalLine - 1;\n\t\n\t next += base64VLQ.encode(mapping.originalColumn\n\t - previousOriginalColumn);\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (mapping.name != null) {\n\t nameIdx = this._names.indexOf(mapping.name);\n\t next += base64VLQ.encode(nameIdx - previousName);\n\t previousName = nameIdx;\n\t }\n\t }\n\t\n\t result += next;\n\t }\n\t\n\t return result;\n\t };\n\t\n\tSourceMapGenerator.prototype._generateSourcesContent =\n\t function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n\t return aSources.map(function (source) {\n\t if (!this._sourcesContents) {\n\t return null;\n\t }\n\t if (aSourceRoot != null) {\n\t source = util.relative(aSourceRoot, source);\n\t }\n\t var key = util.toSetString(source);\n\t return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n\t ? this._sourcesContents[key]\n\t : null;\n\t }, this);\n\t };\n\t\n\t/**\n\t * Externalize the source map.\n\t */\n\tSourceMapGenerator.prototype.toJSON =\n\t function SourceMapGenerator_toJSON() {\n\t var map = {\n\t version: this._version,\n\t sources: this._sources.toArray(),\n\t names: this._names.toArray(),\n\t mappings: this._serializeMappings()\n\t };\n\t if (this._file != null) {\n\t map.file = this._file;\n\t }\n\t if (this._sourceRoot != null) {\n\t map.sourceRoot = this._sourceRoot;\n\t }\n\t if (this._sourcesContents) {\n\t map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n\t }\n\t\n\t return map;\n\t };\n\t\n\t/**\n\t * Render the source map being generated to a string.\n\t */\n\tSourceMapGenerator.prototype.toString =\n\t function SourceMapGenerator_toString() {\n\t return JSON.stringify(this.toJSON());\n\t };\n\t\n\texports.SourceMapGenerator = SourceMapGenerator;\n\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t *\n\t * Based on the Base 64 VLQ implementation in Closure Compiler:\n\t * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n\t *\n\t * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n\t * Redistribution and use in source and binary forms, with or without\n\t * modification, are permitted provided that the following conditions are\n\t * met:\n\t *\n\t * * Redistributions of source code must retain the above copyright\n\t * notice, this list of conditions and the following disclaimer.\n\t * * Redistributions in binary form must reproduce the above\n\t * copyright notice, this list of conditions and the following\n\t * disclaimer in the documentation and/or other materials provided\n\t * with the distribution.\n\t * * Neither the name of Google Inc. nor the names of its\n\t * contributors may be used to endorse or promote products derived\n\t * from this software without specific prior written permission.\n\t *\n\t * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\t * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\t * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\t * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\t * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\t * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\t * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\t * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\t * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\t * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\t */\n\t\n\tvar base64 = __webpack_require__(3);\n\t\n\t// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n\t// length quantities we use in the source map spec, the first bit is the sign,\n\t// the next four bits are the actual value, and the 6th bit is the\n\t// continuation bit. The continuation bit tells us whether there are more\n\t// digits in this value following this digit.\n\t//\n\t// Continuation\n\t// | Sign\n\t// | |\n\t// V V\n\t// 101011\n\t\n\tvar VLQ_BASE_SHIFT = 5;\n\t\n\t// binary: 100000\n\tvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\t\n\t// binary: 011111\n\tvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\t\n\t// binary: 100000\n\tvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\t\n\t/**\n\t * Converts from a two-complement value to a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n\t * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n\t */\n\tfunction toVLQSigned(aValue) {\n\t return aValue < 0\n\t ? ((-aValue) << 1) + 1\n\t : (aValue << 1) + 0;\n\t}\n\t\n\t/**\n\t * Converts to a two-complement value from a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n\t * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n\t */\n\tfunction fromVLQSigned(aValue) {\n\t var isNegative = (aValue & 1) === 1;\n\t var shifted = aValue >> 1;\n\t return isNegative\n\t ? -shifted\n\t : shifted;\n\t}\n\t\n\t/**\n\t * Returns the base 64 VLQ encoded value.\n\t */\n\texports.encode = function base64VLQ_encode(aValue) {\n\t var encoded = \"\";\n\t var digit;\n\t\n\t var vlq = toVLQSigned(aValue);\n\t\n\t do {\n\t digit = vlq & VLQ_BASE_MASK;\n\t vlq >>>= VLQ_BASE_SHIFT;\n\t if (vlq > 0) {\n\t // There are still more digits in this value, so we must make sure the\n\t // continuation bit is marked.\n\t digit |= VLQ_CONTINUATION_BIT;\n\t }\n\t encoded += base64.encode(digit);\n\t } while (vlq > 0);\n\t\n\t return encoded;\n\t};\n\t\n\t/**\n\t * Decodes the next base 64 VLQ value from the given string and returns the\n\t * value and the rest of the string via the out parameter.\n\t */\n\texports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n\t var strLen = aStr.length;\n\t var result = 0;\n\t var shift = 0;\n\t var continuation, digit;\n\t\n\t do {\n\t if (aIndex >= strLen) {\n\t throw new Error(\"Expected more digits in base 64 VLQ value.\");\n\t }\n\t\n\t digit = base64.decode(aStr.charCodeAt(aIndex++));\n\t if (digit === -1) {\n\t throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n\t }\n\t\n\t continuation = !!(digit & VLQ_CONTINUATION_BIT);\n\t digit &= VLQ_BASE_MASK;\n\t result = result + (digit << shift);\n\t shift += VLQ_BASE_SHIFT;\n\t } while (continuation);\n\t\n\t aOutParam.value = fromVLQSigned(result);\n\t aOutParam.rest = aIndex;\n\t};\n\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\t\n\t/**\n\t * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n\t */\n\texports.encode = function (number) {\n\t if (0 <= number && number < intToCharMap.length) {\n\t return intToCharMap[number];\n\t }\n\t throw new TypeError(\"Must be between 0 and 63: \" + number);\n\t};\n\t\n\t/**\n\t * Decode a single base 64 character code digit to an integer. Returns -1 on\n\t * failure.\n\t */\n\texports.decode = function (charCode) {\n\t var bigA = 65; // 'A'\n\t var bigZ = 90; // 'Z'\n\t\n\t var littleA = 97; // 'a'\n\t var littleZ = 122; // 'z'\n\t\n\t var zero = 48; // '0'\n\t var nine = 57; // '9'\n\t\n\t var plus = 43; // '+'\n\t var slash = 47; // '/'\n\t\n\t var littleOffset = 26;\n\t var numberOffset = 52;\n\t\n\t // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t if (bigA <= charCode && charCode <= bigZ) {\n\t return (charCode - bigA);\n\t }\n\t\n\t // 26 - 51: abcdefghijklmnopqrstuvwxyz\n\t if (littleA <= charCode && charCode <= littleZ) {\n\t return (charCode - littleA + littleOffset);\n\t }\n\t\n\t // 52 - 61: 0123456789\n\t if (zero <= charCode && charCode <= nine) {\n\t return (charCode - zero + numberOffset);\n\t }\n\t\n\t // 62: +\n\t if (charCode == plus) {\n\t return 62;\n\t }\n\t\n\t // 63: /\n\t if (charCode == slash) {\n\t return 63;\n\t }\n\t\n\t // Invalid base64 digit.\n\t return -1;\n\t};\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t/**\n\t * This is a helper function for getting values from parameter/options\n\t * objects.\n\t *\n\t * @param args The object we are extracting values from\n\t * @param name The name of the property we are getting.\n\t * @param defaultValue An optional value to return if the property is missing\n\t * from the object. If this is not specified and the property is missing, an\n\t * error will be thrown.\n\t */\n\tfunction getArg(aArgs, aName, aDefaultValue) {\n\t if (aName in aArgs) {\n\t return aArgs[aName];\n\t } else if (arguments.length === 3) {\n\t return aDefaultValue;\n\t } else {\n\t throw new Error('\"' + aName + '\" is a required argument.');\n\t }\n\t}\n\texports.getArg = getArg;\n\t\n\tvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\n\tvar dataUrlRegexp = /^data:.+\\,.+$/;\n\t\n\tfunction urlParse(aUrl) {\n\t var match = aUrl.match(urlRegexp);\n\t if (!match) {\n\t return null;\n\t }\n\t return {\n\t scheme: match[1],\n\t auth: match[2],\n\t host: match[3],\n\t port: match[4],\n\t path: match[5]\n\t };\n\t}\n\texports.urlParse = urlParse;\n\t\n\tfunction urlGenerate(aParsedUrl) {\n\t var url = '';\n\t if (aParsedUrl.scheme) {\n\t url += aParsedUrl.scheme + ':';\n\t }\n\t url += '//';\n\t if (aParsedUrl.auth) {\n\t url += aParsedUrl.auth + '@';\n\t }\n\t if (aParsedUrl.host) {\n\t url += aParsedUrl.host;\n\t }\n\t if (aParsedUrl.port) {\n\t url += \":\" + aParsedUrl.port\n\t }\n\t if (aParsedUrl.path) {\n\t url += aParsedUrl.path;\n\t }\n\t return url;\n\t}\n\texports.urlGenerate = urlGenerate;\n\t\n\t/**\n\t * Normalizes a path, or the path portion of a URL:\n\t *\n\t * - Replaces consecutive slashes with one slash.\n\t * - Removes unnecessary '.' parts.\n\t * - Removes unnecessary '/..' parts.\n\t *\n\t * Based on code in the Node.js 'path' core module.\n\t *\n\t * @param aPath The path or url to normalize.\n\t */\n\tfunction normalize(aPath) {\n\t var path = aPath;\n\t var url = urlParse(aPath);\n\t if (url) {\n\t if (!url.path) {\n\t return aPath;\n\t }\n\t path = url.path;\n\t }\n\t var isAbsolute = exports.isAbsolute(path);\n\t\n\t var parts = path.split(/\\/+/);\n\t for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n\t part = parts[i];\n\t if (part === '.') {\n\t parts.splice(i, 1);\n\t } else if (part === '..') {\n\t up++;\n\t } else if (up > 0) {\n\t if (part === '') {\n\t // The first part is blank if the path is absolute. Trying to go\n\t // above the root is a no-op. Therefore we can remove all '..' parts\n\t // directly after the root.\n\t parts.splice(i + 1, up);\n\t up = 0;\n\t } else {\n\t parts.splice(i, 2);\n\t up--;\n\t }\n\t }\n\t }\n\t path = parts.join('/');\n\t\n\t if (path === '') {\n\t path = isAbsolute ? '/' : '.';\n\t }\n\t\n\t if (url) {\n\t url.path = path;\n\t return urlGenerate(url);\n\t }\n\t return path;\n\t}\n\texports.normalize = normalize;\n\t\n\t/**\n\t * Joins two paths/URLs.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be joined with the root.\n\t *\n\t * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n\t * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n\t * first.\n\t * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n\t * is updated with the result and aRoot is returned. Otherwise the result\n\t * is returned.\n\t * - If aPath is absolute, the result is aPath.\n\t * - Otherwise the two paths are joined with a slash.\n\t * - Joining for example 'http://' and 'www.example.com' is also supported.\n\t */\n\tfunction join(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t if (aPath === \"\") {\n\t aPath = \".\";\n\t }\n\t var aPathUrl = urlParse(aPath);\n\t var aRootUrl = urlParse(aRoot);\n\t if (aRootUrl) {\n\t aRoot = aRootUrl.path || '/';\n\t }\n\t\n\t // `join(foo, '//www.example.org')`\n\t if (aPathUrl && !aPathUrl.scheme) {\n\t if (aRootUrl) {\n\t aPathUrl.scheme = aRootUrl.scheme;\n\t }\n\t return urlGenerate(aPathUrl);\n\t }\n\t\n\t if (aPathUrl || aPath.match(dataUrlRegexp)) {\n\t return aPath;\n\t }\n\t\n\t // `join('http://', 'www.example.com')`\n\t if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n\t aRootUrl.host = aPath;\n\t return urlGenerate(aRootUrl);\n\t }\n\t\n\t var joined = aPath.charAt(0) === '/'\n\t ? aPath\n\t : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\t\n\t if (aRootUrl) {\n\t aRootUrl.path = joined;\n\t return urlGenerate(aRootUrl);\n\t }\n\t return joined;\n\t}\n\texports.join = join;\n\t\n\texports.isAbsolute = function (aPath) {\n\t return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n\t};\n\t\n\t/**\n\t * Make a path relative to a URL or another path.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be made relative to aRoot.\n\t */\n\tfunction relative(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t\n\t aRoot = aRoot.replace(/\\/$/, '');\n\t\n\t // It is possible for the path to be above the root. In this case, simply\n\t // checking whether the root is a prefix of the path won't work. Instead, we\n\t // need to remove components from the root one by one, until either we find\n\t // a prefix that fits, or we run out of components to remove.\n\t var level = 0;\n\t while (aPath.indexOf(aRoot + '/') !== 0) {\n\t var index = aRoot.lastIndexOf(\"/\");\n\t if (index < 0) {\n\t return aPath;\n\t }\n\t\n\t // If the only part of the root that is left is the scheme (i.e. http://,\n\t // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n\t // have exhausted all components, so the path is not relative to the root.\n\t aRoot = aRoot.slice(0, index);\n\t if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n\t return aPath;\n\t }\n\t\n\t ++level;\n\t }\n\t\n\t // Make sure we add a \"../\" for each component we removed from the root.\n\t return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n\t}\n\texports.relative = relative;\n\t\n\tvar supportsNullProto = (function () {\n\t var obj = Object.create(null);\n\t return !('__proto__' in obj);\n\t}());\n\t\n\tfunction identity (s) {\n\t return s;\n\t}\n\t\n\t/**\n\t * Because behavior goes wacky when you set `__proto__` on objects, we\n\t * have to prefix all the strings in our set with an arbitrary character.\n\t *\n\t * See https://github.com/mozilla/source-map/pull/31 and\n\t * https://github.com/mozilla/source-map/issues/30\n\t *\n\t * @param String aStr\n\t */\n\tfunction toSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return '$' + aStr;\n\t }\n\t\n\t return aStr;\n\t}\n\texports.toSetString = supportsNullProto ? identity : toSetString;\n\t\n\tfunction fromSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return aStr.slice(1);\n\t }\n\t\n\t return aStr;\n\t}\n\texports.fromSetString = supportsNullProto ? identity : fromSetString;\n\t\n\tfunction isProtoString(s) {\n\t if (!s) {\n\t return false;\n\t }\n\t\n\t var length = s.length;\n\t\n\t if (length < 9 /* \"__proto__\".length */) {\n\t return false;\n\t }\n\t\n\t if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n\t s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n\t s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n\t s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 9) !== 95 /* '_' */) {\n\t return false;\n\t }\n\t\n\t for (var i = length - 10; i >= 0; i--) {\n\t if (s.charCodeAt(i) !== 36 /* '$' */) {\n\t return false;\n\t }\n\t }\n\t\n\t return true;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings where the original positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same original source/line/column, but different generated\n\t * line and column the same. Useful when searching for a mapping with a\n\t * stubbed out mapping.\n\t */\n\tfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n\t var cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0 || onlyCompareOriginal) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByOriginalPositions = compareByOriginalPositions;\n\t\n\t/**\n\t * Comparator between two mappings with deflated source and name indices where\n\t * the generated positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same generated line and column, but different\n\t * source/name/original line and column the same. Useful when searching for a\n\t * mapping with a stubbed out mapping.\n\t */\n\tfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0 || onlyCompareGenerated) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\t\n\tfunction strcmp(aStr1, aStr2) {\n\t if (aStr1 === aStr2) {\n\t return 0;\n\t }\n\t\n\t if (aStr1 === null) {\n\t return 1; // aStr2 !== null\n\t }\n\t\n\t if (aStr2 === null) {\n\t return -1; // aStr1 !== null\n\t }\n\t\n\t if (aStr1 > aStr2) {\n\t return 1;\n\t }\n\t\n\t return -1;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings with inflated source and name strings where\n\t * the generated positions are compared.\n\t */\n\tfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\t\n\t/**\n\t * Strip any JSON XSSI avoidance prefix from the string (as documented\n\t * in the source maps specification), and then parse the string as\n\t * JSON.\n\t */\n\tfunction parseSourceMapInput(str) {\n\t return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n\t}\n\texports.parseSourceMapInput = parseSourceMapInput;\n\t\n\t/**\n\t * Compute the URL of a source given the the source root, the source's\n\t * URL, and the source map's URL.\n\t */\n\tfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n\t sourceURL = sourceURL || '';\n\t\n\t if (sourceRoot) {\n\t // This follows what Chrome does.\n\t if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n\t sourceRoot += '/';\n\t }\n\t // The spec says:\n\t // Line 4: An optional source root, useful for relocating source\n\t // files on a server or removing repeated values in the\n\t // “sources” entry. This value is prepended to the individual\n\t // entries in the “source” field.\n\t sourceURL = sourceRoot + sourceURL;\n\t }\n\t\n\t // Historically, SourceMapConsumer did not take the sourceMapURL as\n\t // a parameter. This mode is still somewhat supported, which is why\n\t // this code block is conditional. However, it's preferable to pass\n\t // the source map URL to SourceMapConsumer, so that this function\n\t // can implement the source URL resolution algorithm as outlined in\n\t // the spec. This block is basically the equivalent of:\n\t // new URL(sourceURL, sourceMapURL).toString()\n\t // ... except it avoids using URL, which wasn't available in the\n\t // older releases of node still supported by this library.\n\t //\n\t // The spec says:\n\t // If the sources are not absolute URLs after prepending of the\n\t // “sourceRoot”, the sources are resolved relative to the\n\t // SourceMap (like resolving script src in a html document).\n\t if (sourceMapURL) {\n\t var parsed = urlParse(sourceMapURL);\n\t if (!parsed) {\n\t throw new Error(\"sourceMapURL could not be parsed\");\n\t }\n\t if (parsed.path) {\n\t // Strip the last path component, but keep the \"/\".\n\t var index = parsed.path.lastIndexOf('/');\n\t if (index >= 0) {\n\t parsed.path = parsed.path.substring(0, index + 1);\n\t }\n\t }\n\t sourceURL = join(urlGenerate(parsed), sourceURL);\n\t }\n\t\n\t return normalize(sourceURL);\n\t}\n\texports.computeSourceURL = computeSourceURL;\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar has = Object.prototype.hasOwnProperty;\n\tvar hasNativeMap = typeof Map !== \"undefined\";\n\t\n\t/**\n\t * A data structure which is a combination of an array and a set. Adding a new\n\t * member is O(1), testing for membership is O(1), and finding the index of an\n\t * element is O(1). Removing elements from the set is not supported. Only\n\t * strings are supported for membership.\n\t */\n\tfunction ArraySet() {\n\t this._array = [];\n\t this._set = hasNativeMap ? new Map() : Object.create(null);\n\t}\n\t\n\t/**\n\t * Static method for creating ArraySet instances from an existing array.\n\t */\n\tArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n\t var set = new ArraySet();\n\t for (var i = 0, len = aArray.length; i < len; i++) {\n\t set.add(aArray[i], aAllowDuplicates);\n\t }\n\t return set;\n\t};\n\t\n\t/**\n\t * Return how many unique items are in this ArraySet. If duplicates have been\n\t * added, than those do not count towards the size.\n\t *\n\t * @returns Number\n\t */\n\tArraySet.prototype.size = function ArraySet_size() {\n\t return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n\t};\n\t\n\t/**\n\t * Add the given string to this set.\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n\t var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n\t var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n\t var idx = this._array.length;\n\t if (!isDuplicate || aAllowDuplicates) {\n\t this._array.push(aStr);\n\t }\n\t if (!isDuplicate) {\n\t if (hasNativeMap) {\n\t this._set.set(aStr, idx);\n\t } else {\n\t this._set[sStr] = idx;\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Is the given string a member of this set?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.has = function ArraySet_has(aStr) {\n\t if (hasNativeMap) {\n\t return this._set.has(aStr);\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t return has.call(this._set, sStr);\n\t }\n\t};\n\t\n\t/**\n\t * What is the index of the given string in the array?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n\t if (hasNativeMap) {\n\t var idx = this._set.get(aStr);\n\t if (idx >= 0) {\n\t return idx;\n\t }\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t if (has.call(this._set, sStr)) {\n\t return this._set[sStr];\n\t }\n\t }\n\t\n\t throw new Error('\"' + aStr + '\" is not in the set.');\n\t};\n\t\n\t/**\n\t * What is the element at the given index?\n\t *\n\t * @param Number aIdx\n\t */\n\tArraySet.prototype.at = function ArraySet_at(aIdx) {\n\t if (aIdx >= 0 && aIdx < this._array.length) {\n\t return this._array[aIdx];\n\t }\n\t throw new Error('No element indexed by ' + aIdx);\n\t};\n\t\n\t/**\n\t * Returns the array representation of this set (which has the proper indices\n\t * indicated by indexOf). Note that this is a copy of the internal array used\n\t * for storing the members so that no one can mess with internal state.\n\t */\n\tArraySet.prototype.toArray = function ArraySet_toArray() {\n\t return this._array.slice();\n\t};\n\t\n\texports.ArraySet = ArraySet;\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2014 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\t\n\t/**\n\t * Determine whether mappingB is after mappingA with respect to generated\n\t * position.\n\t */\n\tfunction generatedPositionAfter(mappingA, mappingB) {\n\t // Optimized for most common case\n\t var lineA = mappingA.generatedLine;\n\t var lineB = mappingB.generatedLine;\n\t var columnA = mappingA.generatedColumn;\n\t var columnB = mappingB.generatedColumn;\n\t return lineB > lineA || lineB == lineA && columnB >= columnA ||\n\t util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n\t}\n\t\n\t/**\n\t * A data structure to provide a sorted view of accumulated mappings in a\n\t * performance conscious manner. It trades a neglibable overhead in general\n\t * case for a large speedup in case of mappings being added in order.\n\t */\n\tfunction MappingList() {\n\t this._array = [];\n\t this._sorted = true;\n\t // Serves as infimum\n\t this._last = {generatedLine: -1, generatedColumn: 0};\n\t}\n\t\n\t/**\n\t * Iterate through internal items. This method takes the same arguments that\n\t * `Array.prototype.forEach` takes.\n\t *\n\t * NOTE: The order of the mappings is NOT guaranteed.\n\t */\n\tMappingList.prototype.unsortedForEach =\n\t function MappingList_forEach(aCallback, aThisArg) {\n\t this._array.forEach(aCallback, aThisArg);\n\t };\n\t\n\t/**\n\t * Add the given source mapping.\n\t *\n\t * @param Object aMapping\n\t */\n\tMappingList.prototype.add = function MappingList_add(aMapping) {\n\t if (generatedPositionAfter(this._last, aMapping)) {\n\t this._last = aMapping;\n\t this._array.push(aMapping);\n\t } else {\n\t this._sorted = false;\n\t this._array.push(aMapping);\n\t }\n\t};\n\t\n\t/**\n\t * Returns the flat, sorted array of mappings. The mappings are sorted by\n\t * generated position.\n\t *\n\t * WARNING: This method returns internal data without copying, for\n\t * performance. The return value must NOT be mutated, and should be treated as\n\t * an immutable borrow. If you want to take ownership, you must make your own\n\t * copy.\n\t */\n\tMappingList.prototype.toArray = function MappingList_toArray() {\n\t if (!this._sorted) {\n\t this._array.sort(util.compareByGeneratedPositionsInflated);\n\t this._sorted = true;\n\t }\n\t return this._array;\n\t};\n\t\n\texports.MappingList = MappingList;\n\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar binarySearch = __webpack_require__(8);\n\tvar ArraySet = __webpack_require__(5).ArraySet;\n\tvar base64VLQ = __webpack_require__(2);\n\tvar quickSort = __webpack_require__(9).quickSort;\n\t\n\tfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t return sourceMap.sections != null\n\t ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n\t : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n\t}\n\t\n\tSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n\t return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n\t}\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tSourceMapConsumer.prototype._version = 3;\n\t\n\t// `__generatedMappings` and `__originalMappings` are arrays that hold the\n\t// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n\t// are lazily instantiated, accessed via the `_generatedMappings` and\n\t// `_originalMappings` getters respectively, and we only parse the mappings\n\t// and create these arrays once queried for a source location. We jump through\n\t// these hoops because there can be many thousands of mappings, and parsing\n\t// them is expensive, so we only want to do it if we must.\n\t//\n\t// Each object in the arrays is of the form:\n\t//\n\t// {\n\t// generatedLine: The line number in the generated code,\n\t// generatedColumn: The column number in the generated code,\n\t// source: The path to the original source file that generated this\n\t// chunk of code,\n\t// originalLine: The line number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// originalColumn: The column number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// name: The name of the original symbol which generated this chunk of\n\t// code.\n\t// }\n\t//\n\t// All properties except for `generatedLine` and `generatedColumn` can be\n\t// `null`.\n\t//\n\t// `_generatedMappings` is ordered by the generated positions.\n\t//\n\t// `_originalMappings` is ordered by the original positions.\n\t\n\tSourceMapConsumer.prototype.__generatedMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__generatedMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__generatedMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype.__originalMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__originalMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__originalMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype._charIsMappingSeparator =\n\t function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n\t var c = aStr.charAt(index);\n\t return c === \";\" || c === \",\";\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t throw new Error(\"Subclasses must implement _parseMappings\");\n\t };\n\t\n\tSourceMapConsumer.GENERATED_ORDER = 1;\n\tSourceMapConsumer.ORIGINAL_ORDER = 2;\n\t\n\tSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\n\tSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Iterate over each mapping between an original source/line/column and a\n\t * generated line/column in this source map.\n\t *\n\t * @param Function aCallback\n\t * The function that is called with each mapping.\n\t * @param Object aContext\n\t * Optional. If specified, this object will be the value of `this` every\n\t * time that `aCallback` is called.\n\t * @param aOrder\n\t * Either `SourceMapConsumer.GENERATED_ORDER` or\n\t * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n\t * iterate over the mappings sorted by the generated file's line/column\n\t * order or the original's source/line/column order, respectively. Defaults to\n\t * `SourceMapConsumer.GENERATED_ORDER`.\n\t */\n\tSourceMapConsumer.prototype.eachMapping =\n\t function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n\t var context = aContext || null;\n\t var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\t\n\t var mappings;\n\t switch (order) {\n\t case SourceMapConsumer.GENERATED_ORDER:\n\t mappings = this._generatedMappings;\n\t break;\n\t case SourceMapConsumer.ORIGINAL_ORDER:\n\t mappings = this._originalMappings;\n\t break;\n\t default:\n\t throw new Error(\"Unknown order of iteration.\");\n\t }\n\t\n\t var sourceRoot = this.sourceRoot;\n\t mappings.map(function (mapping) {\n\t var source = mapping.source === null ? null : this._sources.at(mapping.source);\n\t source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n\t return {\n\t source: source,\n\t generatedLine: mapping.generatedLine,\n\t generatedColumn: mapping.generatedColumn,\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: mapping.name === null ? null : this._names.at(mapping.name)\n\t };\n\t }, this).forEach(aCallback, context);\n\t };\n\t\n\t/**\n\t * Returns all generated line and column information for the original source,\n\t * line, and column provided. If no column is provided, returns all mappings\n\t * corresponding to a either the line we are searching for or the next\n\t * closest line that has any mappings. Otherwise, returns all mappings\n\t * corresponding to the given line and either the column we are searching for\n\t * or the next closest column that has any offsets.\n\t *\n\t * The only argument is an object with the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number is 1-based.\n\t * - column: Optional. the column number in the original source.\n\t * The column number is 0-based.\n\t *\n\t * and an array of objects is returned, each with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tSourceMapConsumer.prototype.allGeneratedPositionsFor =\n\t function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n\t var line = util.getArg(aArgs, 'line');\n\t\n\t // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n\t // returns the index of the closest mapping less than the needle. By\n\t // setting needle.originalColumn to 0, we thus find the last mapping for\n\t // the given line, provided such a mapping exists.\n\t var needle = {\n\t source: util.getArg(aArgs, 'source'),\n\t originalLine: line,\n\t originalColumn: util.getArg(aArgs, 'column', 0)\n\t };\n\t\n\t needle.source = this._findSourceIndex(needle.source);\n\t if (needle.source < 0) {\n\t return [];\n\t }\n\t\n\t var mappings = [];\n\t\n\t var index = this._findMapping(needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t binarySearch.LEAST_UPPER_BOUND);\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (aArgs.column === undefined) {\n\t var originalLine = mapping.originalLine;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we found. Since\n\t // mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we found.\n\t while (mapping && mapping.originalLine === originalLine) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t } else {\n\t var originalColumn = mapping.originalColumn;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we were searching for.\n\t // Since mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we are searching for.\n\t while (mapping &&\n\t mapping.originalLine === line &&\n\t mapping.originalColumn == originalColumn) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t }\n\t }\n\t\n\t return mappings;\n\t };\n\t\n\texports.SourceMapConsumer = SourceMapConsumer;\n\t\n\t/**\n\t * A BasicSourceMapConsumer instance represents a parsed source map which we can\n\t * query for information about the original file positions by giving it a file\n\t * position in the generated source.\n\t *\n\t * The first parameter is the raw source map (either as a JSON string, or\n\t * already parsed to an object). According to the spec, source maps have the\n\t * following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - sources: An array of URLs to the original source files.\n\t * - names: An array of identifiers which can be referrenced by individual mappings.\n\t * - sourceRoot: Optional. The URL root from which all sources are relative.\n\t * - sourcesContent: Optional. An array of contents of the original source files.\n\t * - mappings: A string of base64 VLQs which contain the actual mappings.\n\t * - file: Optional. The generated file this source map is associated with.\n\t *\n\t * Here is an example source map, taken from the source map spec[0]:\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"out.js\",\n\t * sourceRoot : \"\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AA,AB;;ABCDE;\"\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n\t */\n\tfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sources = util.getArg(sourceMap, 'sources');\n\t // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n\t // requires the array) to play nice here.\n\t var names = util.getArg(sourceMap, 'names', []);\n\t var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n\t var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n\t var mappings = util.getArg(sourceMap, 'mappings');\n\t var file = util.getArg(sourceMap, 'file', null);\n\t\n\t // Once again, Sass deviates from the spec and supplies the version as a\n\t // string rather than a number, so we use loose equality checking here.\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t if (sourceRoot) {\n\t sourceRoot = util.normalize(sourceRoot);\n\t }\n\t\n\t sources = sources\n\t .map(String)\n\t // Some source maps produce relative source paths like \"./foo.js\" instead of\n\t // \"foo.js\". Normalize these first so that future comparisons will succeed.\n\t // See bugzil.la/1090768.\n\t .map(util.normalize)\n\t // Always ensure that absolute sources are internally stored relative to\n\t // the source root, if the source root is absolute. Not doing this would\n\t // be particularly problematic when the source root is a prefix of the\n\t // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n\t .map(function (source) {\n\t return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n\t ? util.relative(sourceRoot, source)\n\t : source;\n\t });\n\t\n\t // Pass `true` below to allow duplicate names and sources. While source maps\n\t // are intended to be compressed and deduplicated, the TypeScript compiler\n\t // sometimes generates source maps with duplicates in them. See Github issue\n\t // #72 and bugzil.la/889492.\n\t this._names = ArraySet.fromArray(names.map(String), true);\n\t this._sources = ArraySet.fromArray(sources, true);\n\t\n\t this._absoluteSources = this._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t this.sourceRoot = sourceRoot;\n\t this.sourcesContent = sourcesContent;\n\t this._mappings = mappings;\n\t this._sourceMapURL = aSourceMapURL;\n\t this.file = file;\n\t}\n\t\n\tBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\t\n\t/**\n\t * Utility function to find the index of a source. Returns -1 if not\n\t * found.\n\t */\n\tBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t if (this._sources.has(relativeSource)) {\n\t return this._sources.indexOf(relativeSource);\n\t }\n\t\n\t // Maybe aSource is an absolute URL as returned by |sources|. In\n\t // this case we can't simply undo the transform.\n\t var i;\n\t for (i = 0; i < this._absoluteSources.length; ++i) {\n\t if (this._absoluteSources[i] == aSource) {\n\t return i;\n\t }\n\t }\n\t\n\t return -1;\n\t};\n\t\n\t/**\n\t * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n\t *\n\t * @param SourceMapGenerator aSourceMap\n\t * The source map that will be consumed.\n\t * @param String aSourceMapURL\n\t * The URL at which the source map can be found (optional)\n\t * @returns BasicSourceMapConsumer\n\t */\n\tBasicSourceMapConsumer.fromSourceMap =\n\t function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n\t var smc = Object.create(BasicSourceMapConsumer.prototype);\n\t\n\t var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n\t var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n\t smc.sourceRoot = aSourceMap._sourceRoot;\n\t smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n\t smc.sourceRoot);\n\t smc.file = aSourceMap._file;\n\t smc._sourceMapURL = aSourceMapURL;\n\t smc._absoluteSources = smc._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t // Because we are modifying the entries (by converting string sources and\n\t // names to indices into the sources and names ArraySets), we have to make\n\t // a copy of the entry or else bad things happen. Shared mutable state\n\t // strikes again! See github issue #191.\n\t\n\t var generatedMappings = aSourceMap._mappings.toArray().slice();\n\t var destGeneratedMappings = smc.__generatedMappings = [];\n\t var destOriginalMappings = smc.__originalMappings = [];\n\t\n\t for (var i = 0, length = generatedMappings.length; i < length; i++) {\n\t var srcMapping = generatedMappings[i];\n\t var destMapping = new Mapping;\n\t destMapping.generatedLine = srcMapping.generatedLine;\n\t destMapping.generatedColumn = srcMapping.generatedColumn;\n\t\n\t if (srcMapping.source) {\n\t destMapping.source = sources.indexOf(srcMapping.source);\n\t destMapping.originalLine = srcMapping.originalLine;\n\t destMapping.originalColumn = srcMapping.originalColumn;\n\t\n\t if (srcMapping.name) {\n\t destMapping.name = names.indexOf(srcMapping.name);\n\t }\n\t\n\t destOriginalMappings.push(destMapping);\n\t }\n\t\n\t destGeneratedMappings.push(destMapping);\n\t }\n\t\n\t quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\t\n\t return smc;\n\t };\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tBasicSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t return this._absoluteSources.slice();\n\t }\n\t});\n\t\n\t/**\n\t * Provide the JIT with a nice shape / hidden class.\n\t */\n\tfunction Mapping() {\n\t this.generatedLine = 0;\n\t this.generatedColumn = 0;\n\t this.source = null;\n\t this.originalLine = null;\n\t this.originalColumn = null;\n\t this.name = null;\n\t}\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tBasicSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t var generatedLine = 1;\n\t var previousGeneratedColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousOriginalColumn = 0;\n\t var previousSource = 0;\n\t var previousName = 0;\n\t var length = aStr.length;\n\t var index = 0;\n\t var cachedSegments = {};\n\t var temp = {};\n\t var originalMappings = [];\n\t var generatedMappings = [];\n\t var mapping, str, segment, end, value;\n\t\n\t while (index < length) {\n\t if (aStr.charAt(index) === ';') {\n\t generatedLine++;\n\t index++;\n\t previousGeneratedColumn = 0;\n\t }\n\t else if (aStr.charAt(index) === ',') {\n\t index++;\n\t }\n\t else {\n\t mapping = new Mapping();\n\t mapping.generatedLine = generatedLine;\n\t\n\t // Because each offset is encoded relative to the previous one,\n\t // many segments often have the same encoding. We can exploit this\n\t // fact by caching the parsed variable length fields of each segment,\n\t // allowing us to avoid a second parse if we encounter the same\n\t // segment again.\n\t for (end = index; end < length; end++) {\n\t if (this._charIsMappingSeparator(aStr, end)) {\n\t break;\n\t }\n\t }\n\t str = aStr.slice(index, end);\n\t\n\t segment = cachedSegments[str];\n\t if (segment) {\n\t index += str.length;\n\t } else {\n\t segment = [];\n\t while (index < end) {\n\t base64VLQ.decode(aStr, index, temp);\n\t value = temp.value;\n\t index = temp.rest;\n\t segment.push(value);\n\t }\n\t\n\t if (segment.length === 2) {\n\t throw new Error('Found a source, but no line and column');\n\t }\n\t\n\t if (segment.length === 3) {\n\t throw new Error('Found a source and line, but no column');\n\t }\n\t\n\t cachedSegments[str] = segment;\n\t }\n\t\n\t // Generated column.\n\t mapping.generatedColumn = previousGeneratedColumn + segment[0];\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (segment.length > 1) {\n\t // Original source.\n\t mapping.source = previousSource + segment[1];\n\t previousSource += segment[1];\n\t\n\t // Original line.\n\t mapping.originalLine = previousOriginalLine + segment[2];\n\t previousOriginalLine = mapping.originalLine;\n\t // Lines are stored 0-based\n\t mapping.originalLine += 1;\n\t\n\t // Original column.\n\t mapping.originalColumn = previousOriginalColumn + segment[3];\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (segment.length > 4) {\n\t // Original name.\n\t mapping.name = previousName + segment[4];\n\t previousName += segment[4];\n\t }\n\t }\n\t\n\t generatedMappings.push(mapping);\n\t if (typeof mapping.originalLine === 'number') {\n\t originalMappings.push(mapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t this.__generatedMappings = generatedMappings;\n\t\n\t quickSort(originalMappings, util.compareByOriginalPositions);\n\t this.__originalMappings = originalMappings;\n\t };\n\t\n\t/**\n\t * Find the mapping that best matches the hypothetical \"needle\" mapping that\n\t * we are searching for in the given \"haystack\" of mappings.\n\t */\n\tBasicSourceMapConsumer.prototype._findMapping =\n\t function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n\t aColumnName, aComparator, aBias) {\n\t // To return the position we are searching for, we must first find the\n\t // mapping for the given position and then return the opposite position it\n\t // points to. Because the mappings are sorted, we can use binary search to\n\t // find the best mapping.\n\t\n\t if (aNeedle[aLineName] <= 0) {\n\t throw new TypeError('Line must be greater than or equal to 1, got '\n\t + aNeedle[aLineName]);\n\t }\n\t if (aNeedle[aColumnName] < 0) {\n\t throw new TypeError('Column must be greater than or equal to 0, got '\n\t + aNeedle[aColumnName]);\n\t }\n\t\n\t return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n\t };\n\t\n\t/**\n\t * Compute the last column for each generated mapping. The last column is\n\t * inclusive.\n\t */\n\tBasicSourceMapConsumer.prototype.computeColumnSpans =\n\t function SourceMapConsumer_computeColumnSpans() {\n\t for (var index = 0; index < this._generatedMappings.length; ++index) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t // Mappings do not contain a field for the last generated columnt. We\n\t // can come up with an optimistic estimate, however, by assuming that\n\t // mappings are contiguous (i.e. given two consecutive mappings, the\n\t // first mapping ends where the second one starts).\n\t if (index + 1 < this._generatedMappings.length) {\n\t var nextMapping = this._generatedMappings[index + 1];\n\t\n\t if (mapping.generatedLine === nextMapping.generatedLine) {\n\t mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n\t continue;\n\t }\n\t }\n\t\n\t // The last mapping for each line spans the entire line.\n\t mapping.lastGeneratedColumn = Infinity;\n\t }\n\t };\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tBasicSourceMapConsumer.prototype.originalPositionFor =\n\t function SourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._generatedMappings,\n\t \"generatedLine\",\n\t \"generatedColumn\",\n\t util.compareByGeneratedPositionsDeflated,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t if (mapping.generatedLine === needle.generatedLine) {\n\t var source = util.getArg(mapping, 'source', null);\n\t if (source !== null) {\n\t source = this._sources.at(source);\n\t source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n\t }\n\t var name = util.getArg(mapping, 'name', null);\n\t if (name !== null) {\n\t name = this._names.at(name);\n\t }\n\t return {\n\t source: source,\n\t line: util.getArg(mapping, 'originalLine', null),\n\t column: util.getArg(mapping, 'originalColumn', null),\n\t name: name\n\t };\n\t }\n\t }\n\t\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function BasicSourceMapConsumer_hasContentsOfAllSources() {\n\t if (!this.sourcesContent) {\n\t return false;\n\t }\n\t return this.sourcesContent.length >= this._sources.size() &&\n\t !this.sourcesContent.some(function (sc) { return sc == null; });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tBasicSourceMapConsumer.prototype.sourceContentFor =\n\t function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t if (!this.sourcesContent) {\n\t return null;\n\t }\n\t\n\t var index = this._findSourceIndex(aSource);\n\t if (index >= 0) {\n\t return this.sourcesContent[index];\n\t }\n\t\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t var url;\n\t if (this.sourceRoot != null\n\t && (url = util.urlParse(this.sourceRoot))) {\n\t // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n\t // many users. We can help them out when they expect file:// URIs to\n\t // behave like it would if they were running a local HTTP server. See\n\t // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n\t var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n\t if (url.scheme == \"file\"\n\t && this._sources.has(fileUriAbsPath)) {\n\t return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n\t }\n\t\n\t if ((!url.path || url.path == \"/\")\n\t && this._sources.has(\"/\" + relativeSource)) {\n\t return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n\t }\n\t }\n\t\n\t // This function is used recursively from\n\t // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n\t // don't want to throw if we can't find the source - we just want to\n\t // return null, so we provide a flag to exit gracefully.\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tBasicSourceMapConsumer.prototype.generatedPositionFor =\n\t function SourceMapConsumer_generatedPositionFor(aArgs) {\n\t var source = util.getArg(aArgs, 'source');\n\t source = this._findSourceIndex(source);\n\t if (source < 0) {\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t }\n\t\n\t var needle = {\n\t source: source,\n\t originalLine: util.getArg(aArgs, 'line'),\n\t originalColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (mapping.source === needle.source) {\n\t return {\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t };\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t };\n\t\n\texports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\t\n\t/**\n\t * An IndexedSourceMapConsumer instance represents a parsed source map which\n\t * we can query for information. It differs from BasicSourceMapConsumer in\n\t * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n\t * input.\n\t *\n\t * The first parameter is a raw source map (either as a JSON string, or already\n\t * parsed to an object). According to the spec for indexed source maps, they\n\t * have the following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - file: Optional. The generated file this source map is associated with.\n\t * - sections: A list of section definitions.\n\t *\n\t * Each value under the \"sections\" field has two fields:\n\t * - offset: The offset into the original specified at which this section\n\t * begins to apply, defined as an object with a \"line\" and \"column\"\n\t * field.\n\t * - map: A source map definition. This source map could also be indexed,\n\t * but doesn't have to be.\n\t *\n\t * Instead of the \"map\" field, it's also possible to have a \"url\" field\n\t * specifying a URL to retrieve a source map from, but that's currently\n\t * unsupported.\n\t *\n\t * Here's an example source map, taken from the source map spec[0], but\n\t * modified to omit a section which uses the \"url\" field.\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"app.js\",\n\t * sections: [{\n\t * offset: {line:100, column:10},\n\t * map: {\n\t * version : 3,\n\t * file: \"section.js\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AAAA,E;;ABCDE;\"\n\t * }\n\t * }],\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n\t */\n\tfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sections = util.getArg(sourceMap, 'sections');\n\t\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t this._sources = new ArraySet();\n\t this._names = new ArraySet();\n\t\n\t var lastOffset = {\n\t line: -1,\n\t column: 0\n\t };\n\t this._sections = sections.map(function (s) {\n\t if (s.url) {\n\t // The url field will require support for asynchronicity.\n\t // See https://github.com/mozilla/source-map/issues/16\n\t throw new Error('Support for url field in sections not implemented.');\n\t }\n\t var offset = util.getArg(s, 'offset');\n\t var offsetLine = util.getArg(offset, 'line');\n\t var offsetColumn = util.getArg(offset, 'column');\n\t\n\t if (offsetLine < lastOffset.line ||\n\t (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n\t throw new Error('Section offsets must be ordered and non-overlapping.');\n\t }\n\t lastOffset = offset;\n\t\n\t return {\n\t generatedOffset: {\n\t // The offset fields are 0-based, but we use 1-based indices when\n\t // encoding/decoding from VLQ.\n\t generatedLine: offsetLine + 1,\n\t generatedColumn: offsetColumn + 1\n\t },\n\t consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n\t }\n\t });\n\t}\n\t\n\tIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tIndexedSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t var sources = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n\t sources.push(this._sections[i].consumer.sources[j]);\n\t }\n\t }\n\t return sources;\n\t }\n\t});\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tIndexedSourceMapConsumer.prototype.originalPositionFor =\n\t function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t // Find the section containing the generated position we're trying to map\n\t // to an original position.\n\t var sectionIndex = binarySearch.search(needle, this._sections,\n\t function(needle, section) {\n\t var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n\t if (cmp) {\n\t return cmp;\n\t }\n\t\n\t return (needle.generatedColumn -\n\t section.generatedOffset.generatedColumn);\n\t });\n\t var section = this._sections[sectionIndex];\n\t\n\t if (!section) {\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t }\n\t\n\t return section.consumer.originalPositionFor({\n\t line: needle.generatedLine -\n\t (section.generatedOffset.generatedLine - 1),\n\t column: needle.generatedColumn -\n\t (section.generatedOffset.generatedLine === needle.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t bias: aArgs.bias\n\t });\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n\t return this._sections.every(function (s) {\n\t return s.consumer.hasContentsOfAllSources();\n\t });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tIndexedSourceMapConsumer.prototype.sourceContentFor =\n\t function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t var content = section.consumer.sourceContentFor(aSource, true);\n\t if (content) {\n\t return content;\n\t }\n\t }\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based. \n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tIndexedSourceMapConsumer.prototype.generatedPositionFor =\n\t function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t // Only consider this section if the requested source is in the list of\n\t // sources of the consumer.\n\t if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n\t continue;\n\t }\n\t var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n\t if (generatedPosition) {\n\t var ret = {\n\t line: generatedPosition.line +\n\t (section.generatedOffset.generatedLine - 1),\n\t column: generatedPosition.column +\n\t (section.generatedOffset.generatedLine === generatedPosition.line\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0)\n\t };\n\t return ret;\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null\n\t };\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tIndexedSourceMapConsumer.prototype._parseMappings =\n\t function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t this.__generatedMappings = [];\n\t this.__originalMappings = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t var sectionMappings = section.consumer._generatedMappings;\n\t for (var j = 0; j < sectionMappings.length; j++) {\n\t var mapping = sectionMappings[j];\n\t\n\t var source = section.consumer._sources.at(mapping.source);\n\t source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n\t this._sources.add(source);\n\t source = this._sources.indexOf(source);\n\t\n\t var name = null;\n\t if (mapping.name) {\n\t name = section.consumer._names.at(mapping.name);\n\t this._names.add(name);\n\t name = this._names.indexOf(name);\n\t }\n\t\n\t // The mappings coming from the consumer for the section have\n\t // generated positions relative to the start of the section, so we\n\t // need to offset them to be relative to the start of the concatenated\n\t // generated file.\n\t var adjustedMapping = {\n\t source: source,\n\t generatedLine: mapping.generatedLine +\n\t (section.generatedOffset.generatedLine - 1),\n\t generatedColumn: mapping.generatedColumn +\n\t (section.generatedOffset.generatedLine === mapping.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: name\n\t };\n\t\n\t this.__generatedMappings.push(adjustedMapping);\n\t if (typeof adjustedMapping.originalLine === 'number') {\n\t this.__originalMappings.push(adjustedMapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t quickSort(this.__originalMappings, util.compareByOriginalPositions);\n\t };\n\t\n\texports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\texports.GREATEST_LOWER_BOUND = 1;\n\texports.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Recursive implementation of binary search.\n\t *\n\t * @param aLow Indices here and lower do not contain the needle.\n\t * @param aHigh Indices here and higher do not contain the needle.\n\t * @param aNeedle The element being searched for.\n\t * @param aHaystack The non-empty array being searched.\n\t * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t */\n\tfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n\t // This function terminates when one of the following is true:\n\t //\n\t // 1. We find the exact element we are looking for.\n\t //\n\t // 2. We did not find the exact element, but we can return the index of\n\t // the next-closest element.\n\t //\n\t // 3. We did not find the exact element, and there is no next-closest\n\t // element than the one we are searching for, so we return -1.\n\t var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n\t var cmp = aCompare(aNeedle, aHaystack[mid], true);\n\t if (cmp === 0) {\n\t // Found the element we are looking for.\n\t return mid;\n\t }\n\t else if (cmp > 0) {\n\t // Our needle is greater than aHaystack[mid].\n\t if (aHigh - mid > 1) {\n\t // The element is in the upper half.\n\t return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // The exact needle element was not found in this haystack. Determine if\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return aHigh < aHaystack.length ? aHigh : -1;\n\t } else {\n\t return mid;\n\t }\n\t }\n\t else {\n\t // Our needle is less than aHaystack[mid].\n\t if (mid - aLow > 1) {\n\t // The element is in the lower half.\n\t return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return mid;\n\t } else {\n\t return aLow < 0 ? -1 : aLow;\n\t }\n\t }\n\t}\n\t\n\t/**\n\t * This is an implementation of binary search which will always try and return\n\t * the index of the closest element if there is no exact hit. This is because\n\t * mappings between original and generated line/col pairs are single points,\n\t * and there is an implicit region between each of them, so a miss just means\n\t * that you aren't on the very start of a region.\n\t *\n\t * @param aNeedle The element you are looking for.\n\t * @param aHaystack The array that is being searched.\n\t * @param aCompare A function which takes the needle and an element in the\n\t * array and returns -1, 0, or 1 depending on whether the needle is less\n\t * than, equal to, or greater than the element, respectively.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n\t */\n\texports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n\t if (aHaystack.length === 0) {\n\t return -1;\n\t }\n\t\n\t var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n\t aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n\t if (index < 0) {\n\t return -1;\n\t }\n\t\n\t // We have found either the exact element, or the next-closest element than\n\t // the one we are searching for. However, there may be more than one such\n\t // element. Make sure we always return the smallest of these.\n\t while (index - 1 >= 0) {\n\t if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n\t break;\n\t }\n\t --index;\n\t }\n\t\n\t return index;\n\t};\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t// It turns out that some (most?) JavaScript engines don't self-host\n\t// `Array.prototype.sort`. This makes sense because C++ will likely remain\n\t// faster than JS when doing raw CPU-intensive sorting. However, when using a\n\t// custom comparator function, calling back and forth between the VM's C++ and\n\t// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n\t// worse generated code for the comparator function than would be optimal. In\n\t// fact, when sorting with a comparator, these costs outweigh the benefits of\n\t// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n\t// a ~3500ms mean speed-up in `bench/bench.html`.\n\t\n\t/**\n\t * Swap the elements indexed by `x` and `y` in the array `ary`.\n\t *\n\t * @param {Array} ary\n\t * The array.\n\t * @param {Number} x\n\t * The index of the first item.\n\t * @param {Number} y\n\t * The index of the second item.\n\t */\n\tfunction swap(ary, x, y) {\n\t var temp = ary[x];\n\t ary[x] = ary[y];\n\t ary[y] = temp;\n\t}\n\t\n\t/**\n\t * Returns a random integer within the range `low .. high` inclusive.\n\t *\n\t * @param {Number} low\n\t * The lower bound on the range.\n\t * @param {Number} high\n\t * The upper bound on the range.\n\t */\n\tfunction randomIntInRange(low, high) {\n\t return Math.round(low + (Math.random() * (high - low)));\n\t}\n\t\n\t/**\n\t * The Quick Sort algorithm.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t * @param {Number} p\n\t * Start index of the array\n\t * @param {Number} r\n\t * End index of the array\n\t */\n\tfunction doQuickSort(ary, comparator, p, r) {\n\t // If our lower bound is less than our upper bound, we (1) partition the\n\t // array into two pieces and (2) recurse on each half. If it is not, this is\n\t // the empty array and our base case.\n\t\n\t if (p < r) {\n\t // (1) Partitioning.\n\t //\n\t // The partitioning chooses a pivot between `p` and `r` and moves all\n\t // elements that are less than or equal to the pivot to the before it, and\n\t // all the elements that are greater than it after it. The effect is that\n\t // once partition is done, the pivot is in the exact place it will be when\n\t // the array is put in sorted order, and it will not need to be moved\n\t // again. This runs in O(n) time.\n\t\n\t // Always choose a random pivot so that an input array which is reverse\n\t // sorted does not cause O(n^2) running time.\n\t var pivotIndex = randomIntInRange(p, r);\n\t var i = p - 1;\n\t\n\t swap(ary, pivotIndex, r);\n\t var pivot = ary[r];\n\t\n\t // Immediately after `j` is incremented in this loop, the following hold\n\t // true:\n\t //\n\t // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n\t //\n\t // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n\t for (var j = p; j < r; j++) {\n\t if (comparator(ary[j], pivot) <= 0) {\n\t i += 1;\n\t swap(ary, i, j);\n\t }\n\t }\n\t\n\t swap(ary, i + 1, j);\n\t var q = i + 1;\n\t\n\t // (2) Recurse on each half.\n\t\n\t doQuickSort(ary, comparator, p, q - 1);\n\t doQuickSort(ary, comparator, q + 1, r);\n\t }\n\t}\n\t\n\t/**\n\t * Sort the given array in-place with the given comparator function.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t */\n\texports.quickSort = function (ary, comparator) {\n\t doQuickSort(ary, comparator, 0, ary.length - 1);\n\t};\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;\n\tvar util = __webpack_require__(4);\n\t\n\t// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n\t// operating systems these days (capturing the result).\n\tvar REGEX_NEWLINE = /(\\r?\\n)/;\n\t\n\t// Newline character code for charCodeAt() comparisons\n\tvar NEWLINE_CODE = 10;\n\t\n\t// Private symbol for identifying `SourceNode`s when multiple versions of\n\t// the source-map library are loaded. This MUST NOT CHANGE across\n\t// versions!\n\tvar isSourceNode = \"$$$isSourceNode$$$\";\n\t\n\t/**\n\t * SourceNodes provide a way to abstract over interpolating/concatenating\n\t * snippets of generated JavaScript source code while maintaining the line and\n\t * column information associated with the original source code.\n\t *\n\t * @param aLine The original line number.\n\t * @param aColumn The original column number.\n\t * @param aSource The original source's filename.\n\t * @param aChunks Optional. An array of strings which are snippets of\n\t * generated JS, or other SourceNodes.\n\t * @param aName The original identifier.\n\t */\n\tfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n\t this.children = [];\n\t this.sourceContents = {};\n\t this.line = aLine == null ? null : aLine;\n\t this.column = aColumn == null ? null : aColumn;\n\t this.source = aSource == null ? null : aSource;\n\t this.name = aName == null ? null : aName;\n\t this[isSourceNode] = true;\n\t if (aChunks != null) this.add(aChunks);\n\t}\n\t\n\t/**\n\t * Creates a SourceNode from generated code and a SourceMapConsumer.\n\t *\n\t * @param aGeneratedCode The generated code\n\t * @param aSourceMapConsumer The SourceMap for the generated code\n\t * @param aRelativePath Optional. The path that relative sources in the\n\t * SourceMapConsumer should be relative to.\n\t */\n\tSourceNode.fromStringWithSourceMap =\n\t function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n\t // The SourceNode we want to fill with the generated code\n\t // and the SourceMap\n\t var node = new SourceNode();\n\t\n\t // All even indices of this array are one line of the generated code,\n\t // while all odd indices are the newlines between two adjacent lines\n\t // (since `REGEX_NEWLINE` captures its match).\n\t // Processed fragments are accessed by calling `shiftNextLine`.\n\t var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n\t var remainingLinesIndex = 0;\n\t var shiftNextLine = function() {\n\t var lineContents = getNextLine();\n\t // The last line of a file might not have a newline.\n\t var newLine = getNextLine() || \"\";\n\t return lineContents + newLine;\n\t\n\t function getNextLine() {\n\t return remainingLinesIndex < remainingLines.length ?\n\t remainingLines[remainingLinesIndex++] : undefined;\n\t }\n\t };\n\t\n\t // We need to remember the position of \"remainingLines\"\n\t var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\t\n\t // The generate SourceNodes we need a code range.\n\t // To extract it current and last mapping is used.\n\t // Here we store the last mapping.\n\t var lastMapping = null;\n\t\n\t aSourceMapConsumer.eachMapping(function (mapping) {\n\t if (lastMapping !== null) {\n\t // We add the code from \"lastMapping\" to \"mapping\":\n\t // First check if there is a new line in between.\n\t if (lastGeneratedLine < mapping.generatedLine) {\n\t // Associate first line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t lastGeneratedLine++;\n\t lastGeneratedColumn = 0;\n\t // The remaining code is added without mapping\n\t } else {\n\t // There is no new line in between.\n\t // Associate the code between \"lastGeneratedColumn\" and\n\t // \"mapping.generatedColumn\" with \"lastMapping\"\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t var code = nextLine.substr(0, mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t addMappingWithCode(lastMapping, code);\n\t // No more remaining code, continue\n\t lastMapping = mapping;\n\t return;\n\t }\n\t }\n\t // We add the generated code until the first mapping\n\t // to the SourceNode without any mapping.\n\t // Each line is added as separate string.\n\t while (lastGeneratedLine < mapping.generatedLine) {\n\t node.add(shiftNextLine());\n\t lastGeneratedLine++;\n\t }\n\t if (lastGeneratedColumn < mapping.generatedColumn) {\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t node.add(nextLine.substr(0, mapping.generatedColumn));\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t }\n\t lastMapping = mapping;\n\t }, this);\n\t // We have processed all mappings.\n\t if (remainingLinesIndex < remainingLines.length) {\n\t if (lastMapping) {\n\t // Associate the remaining code in the current line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t }\n\t // and add the remaining lines without any mapping\n\t node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n\t }\n\t\n\t // Copy sourcesContent into SourceNode\n\t aSourceMapConsumer.sources.forEach(function (sourceFile) {\n\t var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n\t if (content != null) {\n\t if (aRelativePath != null) {\n\t sourceFile = util.join(aRelativePath, sourceFile);\n\t }\n\t node.setSourceContent(sourceFile, content);\n\t }\n\t });\n\t\n\t return node;\n\t\n\t function addMappingWithCode(mapping, code) {\n\t if (mapping === null || mapping.source === undefined) {\n\t node.add(code);\n\t } else {\n\t var source = aRelativePath\n\t ? util.join(aRelativePath, mapping.source)\n\t : mapping.source;\n\t node.add(new SourceNode(mapping.originalLine,\n\t mapping.originalColumn,\n\t source,\n\t code,\n\t mapping.name));\n\t }\n\t }\n\t };\n\t\n\t/**\n\t * Add a chunk of generated JS to this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.add = function SourceNode_add(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t aChunk.forEach(function (chunk) {\n\t this.add(chunk);\n\t }, this);\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t if (aChunk) {\n\t this.children.push(aChunk);\n\t }\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a chunk of generated JS to the beginning of this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t for (var i = aChunk.length-1; i >= 0; i--) {\n\t this.prepend(aChunk[i]);\n\t }\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t this.children.unshift(aChunk);\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Walk over the tree of JS snippets in this node and its children. The\n\t * walking function is called once for each snippet of JS and is passed that\n\t * snippet and the its original associated source's line/column location.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n\t var chunk;\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t chunk = this.children[i];\n\t if (chunk[isSourceNode]) {\n\t chunk.walk(aFn);\n\t }\n\t else {\n\t if (chunk !== '') {\n\t aFn(chunk, { source: this.source,\n\t line: this.line,\n\t column: this.column,\n\t name: this.name });\n\t }\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n\t * each of `this.children`.\n\t *\n\t * @param aSep The separator.\n\t */\n\tSourceNode.prototype.join = function SourceNode_join(aSep) {\n\t var newChildren;\n\t var i;\n\t var len = this.children.length;\n\t if (len > 0) {\n\t newChildren = [];\n\t for (i = 0; i < len-1; i++) {\n\t newChildren.push(this.children[i]);\n\t newChildren.push(aSep);\n\t }\n\t newChildren.push(this.children[i]);\n\t this.children = newChildren;\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Call String.prototype.replace on the very right-most source snippet. Useful\n\t * for trimming whitespace from the end of a source node, etc.\n\t *\n\t * @param aPattern The pattern to replace.\n\t * @param aReplacement The thing to replace the pattern with.\n\t */\n\tSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n\t var lastChild = this.children[this.children.length - 1];\n\t if (lastChild[isSourceNode]) {\n\t lastChild.replaceRight(aPattern, aReplacement);\n\t }\n\t else if (typeof lastChild === 'string') {\n\t this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n\t }\n\t else {\n\t this.children.push(''.replace(aPattern, aReplacement));\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Set the source content for a source file. This will be added to the SourceMapGenerator\n\t * in the sourcesContent field.\n\t *\n\t * @param aSourceFile The filename of the source file\n\t * @param aSourceContent The content of the source file\n\t */\n\tSourceNode.prototype.setSourceContent =\n\t function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n\t this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n\t };\n\t\n\t/**\n\t * Walk over the tree of SourceNodes. The walking function is called for each\n\t * source file content and is passed the filename and source content.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walkSourceContents =\n\t function SourceNode_walkSourceContents(aFn) {\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t if (this.children[i][isSourceNode]) {\n\t this.children[i].walkSourceContents(aFn);\n\t }\n\t }\n\t\n\t var sources = Object.keys(this.sourceContents);\n\t for (var i = 0, len = sources.length; i < len; i++) {\n\t aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n\t }\n\t };\n\t\n\t/**\n\t * Return the string representation of this source node. Walks over the tree\n\t * and concatenates all the various snippets together to one string.\n\t */\n\tSourceNode.prototype.toString = function SourceNode_toString() {\n\t var str = \"\";\n\t this.walk(function (chunk) {\n\t str += chunk;\n\t });\n\t return str;\n\t};\n\t\n\t/**\n\t * Returns the string representation of this source node along with a source\n\t * map.\n\t */\n\tSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n\t var generated = {\n\t code: \"\",\n\t line: 1,\n\t column: 0\n\t };\n\t var map = new SourceMapGenerator(aArgs);\n\t var sourceMappingActive = false;\n\t var lastOriginalSource = null;\n\t var lastOriginalLine = null;\n\t var lastOriginalColumn = null;\n\t var lastOriginalName = null;\n\t this.walk(function (chunk, original) {\n\t generated.code += chunk;\n\t if (original.source !== null\n\t && original.line !== null\n\t && original.column !== null) {\n\t if(lastOriginalSource !== original.source\n\t || lastOriginalLine !== original.line\n\t || lastOriginalColumn !== original.column\n\t || lastOriginalName !== original.name) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t lastOriginalSource = original.source;\n\t lastOriginalLine = original.line;\n\t lastOriginalColumn = original.column;\n\t lastOriginalName = original.name;\n\t sourceMappingActive = true;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t }\n\t });\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t }\n\t for (var idx = 0, length = chunk.length; idx < length; idx++) {\n\t if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n\t generated.line++;\n\t generated.column = 0;\n\t // Mappings end at eol\n\t if (idx + 1 === length) {\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t } else {\n\t generated.column++;\n\t }\n\t }\n\t });\n\t this.walkSourceContents(function (sourceFile, sourceContent) {\n\t map.setSourceContent(sourceFile, sourceContent);\n\t });\n\t\n\t return { code: generated.code, map: map };\n\t};\n\t\n\texports.SourceNode = SourceNode;\n\n\n/***/ })\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// source-map.min.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 0fd5815da764db5fb9fe","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./source-map.js\n// module id = 0\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-generator.js\n// module id = 1\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64-vlq.js\n// module id = 2\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64.js\n// module id = 3\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/util.js\n// module id = 4\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/array-set.js\n// module id = 5\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/mapping-list.js\n// module id = 6\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-consumer.js\n// module id = 7\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/binary-search.js\n// module id = 8\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/quick-sort.js\n// module id = 9\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-node.js\n// module id = 10\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/source-map/lib/array-set.js b/node_modules/source-map/lib/array-set.js new file mode 100644 index 0000000..fbd5c81 --- /dev/null +++ b/node_modules/source-map/lib/array-set.js @@ -0,0 +1,121 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/node_modules/source-map/lib/base64-vlq.js b/node_modules/source-map/lib/base64-vlq.js new file mode 100644 index 0000000..612b404 --- /dev/null +++ b/node_modules/source-map/lib/base64-vlq.js @@ -0,0 +1,140 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/node_modules/source-map/lib/base64.js b/node_modules/source-map/lib/base64.js new file mode 100644 index 0000000..8aa86b3 --- /dev/null +++ b/node_modules/source-map/lib/base64.js @@ -0,0 +1,67 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/node_modules/source-map/lib/binary-search.js b/node_modules/source-map/lib/binary-search.js new file mode 100644 index 0000000..010ac94 --- /dev/null +++ b/node_modules/source-map/lib/binary-search.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/node_modules/source-map/lib/mapping-list.js b/node_modules/source-map/lib/mapping-list.js new file mode 100644 index 0000000..06d1274 --- /dev/null +++ b/node_modules/source-map/lib/mapping-list.js @@ -0,0 +1,79 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/node_modules/source-map/lib/quick-sort.js b/node_modules/source-map/lib/quick-sort.js new file mode 100644 index 0000000..6a7caad --- /dev/null +++ b/node_modules/source-map/lib/quick-sort.js @@ -0,0 +1,114 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; diff --git a/node_modules/source-map/lib/source-map-consumer.js b/node_modules/source-map/lib/source-map-consumer.js new file mode 100644 index 0000000..7b99d1d --- /dev/null +++ b/node_modules/source-map/lib/source-map-consumer.js @@ -0,0 +1,1145 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/node_modules/source-map/lib/source-map-generator.js b/node_modules/source-map/lib/source-map-generator.js new file mode 100644 index 0000000..508bcfb --- /dev/null +++ b/node_modules/source-map/lib/source-map-generator.js @@ -0,0 +1,425 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/node_modules/source-map/lib/source-node.js b/node_modules/source-map/lib/source-node.js new file mode 100644 index 0000000..8bcdbe3 --- /dev/null +++ b/node_modules/source-map/lib/source-node.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; diff --git a/node_modules/source-map/lib/util.js b/node_modules/source-map/lib/util.js new file mode 100644 index 0000000..3ca92e5 --- /dev/null +++ b/node_modules/source-map/lib/util.js @@ -0,0 +1,488 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/node_modules/source-map/package.json b/node_modules/source-map/package.json new file mode 100644 index 0000000..2466341 --- /dev/null +++ b/node_modules/source-map/package.json @@ -0,0 +1,73 @@ +{ + "name": "source-map", + "description": "Generates and consumes source maps", + "version": "0.6.1", + "homepage": "https://github.com/mozilla/source-map", + "author": "Nick Fitzgerald ", + "contributors": [ + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": { + "type": "git", + "url": "http://github.com/mozilla/source-map.git" + }, + "main": "./source-map.js", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/", + "dist/source-map.debug.js", + "dist/source-map.js", + "dist/source-map.min.js", + "dist/source-map.min.js.map" + ], + "engines": { + "node": ">=0.10.0" + }, + "license": "BSD-3-Clause", + "scripts": { + "test": "npm run build && node test/run-tests.js", + "build": "webpack --color", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "devDependencies": { + "doctoc": "^0.15.0", + "webpack": "^1.12.0" + }, + "typings": "source-map" +} diff --git a/node_modules/source-map/source-map.d.ts b/node_modules/source-map/source-map.d.ts new file mode 100644 index 0000000..8f972b0 --- /dev/null +++ b/node_modules/source-map/source-map.d.ts @@ -0,0 +1,98 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +export interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string; + generatedLine: number; + generatedColumn: number; + originalLine: number; + originalColumn: number; + name: string; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + constructor(rawSourceMap: RawSourceMap); + computeColumnSpans(): void; + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; + hasContentsOfAllSources(): boolean; + sourceContentFor(source: string, returnNullOnMissing?: boolean): string; + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface Mapping { + generated: Position; + original: Position; + source: string; + name?: string; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + toString(): string; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + add(chunk: string): void; + prepend(chunk: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; + toString(): string; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/node_modules/source-map/source-map.js b/node_modules/source-map/source-map.js new file mode 100644 index 0000000..bc88fe8 --- /dev/null +++ b/node_modules/source-map/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/node_modules/sourcemap-codec/CHANGELOG.md b/node_modules/sourcemap-codec/CHANGELOG.md new file mode 100644 index 0000000..e5ab34a --- /dev/null +++ b/node_modules/sourcemap-codec/CHANGELOG.md @@ -0,0 +1,64 @@ +# sourcemap-codec changelog + +## 1.4.8 + +* Performance boost ([#80](https://github.com/Rich-Harris/sourcemap-codec/pull/80)) + +## 1.4.7 + +* Include .map files in package ([#73](https://github.com/Rich-Harris/sourcemap-codec/issues/73)) + +## 1.4.6 + +* Use arrays instead of typed arrays ([#79](https://github.com/Rich-Harris/sourcemap-codec/pull/79)) + +## 1.4.5 + +* Handle overflow cases ([#78](https://github.com/Rich-Harris/sourcemap-codec/pull/78)) + +## 1.4.4 + +* Use Uint32Array, yikes ([#77](https://github.com/Rich-Harris/sourcemap-codec/pull/77)) + +## 1.4.3 + +* Use Uint16Array to prevent overflow ([#75](https://github.com/Rich-Harris/sourcemap-codec/pull/75)) + +## 1.4.2 + +* GO EVEN FASTER ([#74](https://github.com/Rich-Harris/sourcemap-codec/pull/74)) + +## 1.4.1 + +* GO FASTER ([#71](https://github.com/Rich-Harris/sourcemap-codec/pull/71)) + +## 1.4.0 + +* Add TypeScript declarations ([#70](https://github.com/Rich-Harris/sourcemap-codec/pull/70)) + +## 1.3.1 + +* Update build process, expose `pkg.module` + +## 1.3.0 + +* Update build process + +## 1.2.1 + +* Add dist files to npm package + +## 1.2.0 + +* Add ES6 build +* Update dependencies +* Add test coverage + +## 1.1.0 + +* Fix bug with lines containing single-character segments +* Add tests + +## 1.0.0 + +* First release diff --git a/node_modules/sourcemap-codec/LICENSE b/node_modules/sourcemap-codec/LICENSE new file mode 100644 index 0000000..a331065 --- /dev/null +++ b/node_modules/sourcemap-codec/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2015 Rich Harris + +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/sourcemap-codec/README.md b/node_modules/sourcemap-codec/README.md new file mode 100644 index 0000000..e4373aa --- /dev/null +++ b/node_modules/sourcemap-codec/README.md @@ -0,0 +1,63 @@ +# sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from 'sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + + +# License + +MIT diff --git a/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js b/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js new file mode 100644 index 0000000..f5e7d06 --- /dev/null +++ b/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js @@ -0,0 +1,124 @@ +var charToInteger = {}; +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +for (var i = 0; i < chars.length; i++) { + charToInteger[chars.charCodeAt(i)] = i; +} +function decode(mappings) { + var decoded = []; + var line = []; + var segment = [ + 0, + 0, + 0, + 0, + 0, + ]; + var j = 0; + for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) { + var c = mappings.charCodeAt(i); + if (c === 44) { // "," + segmentify(line, segment, j); + j = 0; + } + else if (c === 59) { // ";" + segmentify(line, segment, j); + j = 0; + decoded.push(line); + line = []; + segment[0] = 0; + } + else { + var integer = charToInteger[c]; + if (integer === undefined) { + throw new Error('Invalid character (' + String.fromCharCode(c) + ')'); + } + var hasContinuationBit = integer & 32; + integer &= 31; + value += integer << shift; + if (hasContinuationBit) { + shift += 5; + } + else { + var shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = value === 0 ? -0x80000000 : -value; + } + segment[j] += value; + j++; + value = shift = 0; // reset + } + } + } + segmentify(line, segment, j); + decoded.push(line); + return decoded; +} +function segmentify(line, segment, j) { + // This looks ugly, but we're creating specialized arrays with a specific + // length. This is much faster than creating a new array (which v8 expands to + // a capacity of 17 after pushing the first item), or slicing out a subarray + // (which is slow). Length 4 is assumed to be the most frequent, followed by + // length 5 (since not everything will have an associated name), followed by + // length 1 (it's probably rare for a source substring to not have an + // associated segment data). + if (j === 4) + line.push([segment[0], segment[1], segment[2], segment[3]]); + else if (j === 5) + line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]); + else if (j === 1) + line.push([segment[0]]); +} +function encode(decoded) { + var sourceFileIndex = 0; // second field + var sourceCodeLine = 0; // third field + var sourceCodeColumn = 0; // fourth field + var nameIndex = 0; // fifth field + var mappings = ''; + for (var i = 0; i < decoded.length; i++) { + var line = decoded[i]; + if (i > 0) + mappings += ';'; + if (line.length === 0) + continue; + var generatedCodeColumn = 0; // first field + var lineMappings = []; + for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { + var segment = line_1[_i]; + var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn); + generatedCodeColumn = segment[0]; + if (segment.length > 1) { + segmentMappings += + encodeInteger(segment[1] - sourceFileIndex) + + encodeInteger(segment[2] - sourceCodeLine) + + encodeInteger(segment[3] - sourceCodeColumn); + sourceFileIndex = segment[1]; + sourceCodeLine = segment[2]; + sourceCodeColumn = segment[3]; + } + if (segment.length === 5) { + segmentMappings += encodeInteger(segment[4] - nameIndex); + nameIndex = segment[4]; + } + lineMappings.push(segmentMappings); + } + mappings += lineMappings.join(','); + } + return mappings; +} +function encodeInteger(num) { + var result = ''; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + var clamped = num & 31; + num >>>= 5; + if (num > 0) { + clamped |= 32; + } + result += chars[clamped]; + } while (num > 0); + return result; +} + +export { decode, encode }; +//# sourceMappingURL=sourcemap-codec.es.js.map diff --git a/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js.map b/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js.map new file mode 100644 index 0000000..f2cab32 --- /dev/null +++ b/node_modules/sourcemap-codec/dist/sourcemap-codec.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.es.js","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n\t| [number]\n\t| [number, number, number, number]\n\t| [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst charToInteger: { [charCode: number]: number } = {};\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfor (let i = 0; i < chars.length; i++) {\n\tcharToInteger[chars.charCodeAt(i)] = i;\n}\n\nexport function decode(mappings: string): SourceMapMappings {\n\tconst decoded: SourceMapMappings = [];\n\tlet line: SourceMapLine = [];\n\tconst segment: SourceMapSegment = [\n\t\t0, // generated code column\n\t\t0, // source file index\n\t\t0, // source code line\n\t\t0, // source code column\n\t\t0, // name index\n\t];\n\n\tlet j = 0;\n\tfor (let i = 0, shift = 0, value = 0; i < mappings.length; i++) {\n\t\tconst c = mappings.charCodeAt(i);\n\n\t\tif (c === 44) { // \",\"\n\t\t\tsegmentify(line, segment, j);\n\t\t\tj = 0;\n\n\t\t} else if (c === 59) { // \";\"\n\t\t\tsegmentify(line, segment, j);\n\t\t\tj = 0;\n\t\t\tdecoded.push(line);\n\t\t\tline = [];\n\t\t\tsegment[0] = 0;\n\n\t\t} else {\n\t\t\tlet integer = charToInteger[c];\n\t\t\tif (integer === undefined) {\n\t\t\t\tthrow new Error('Invalid character (' + String.fromCharCode(c) + ')');\n\t\t\t}\n\n\t\t\tconst hasContinuationBit = integer & 32;\n\n\t\t\tinteger &= 31;\n\t\t\tvalue += integer << shift;\n\n\t\t\tif (hasContinuationBit) {\n\t\t\t\tshift += 5;\n\t\t\t} else {\n\t\t\t\tconst shouldNegate = value & 1;\n\t\t\t\tvalue >>>= 1;\n\n\t\t\t\tif (shouldNegate) {\n\t\t\t\t\tvalue = value === 0 ? -0x80000000 : -value;\n\t\t\t\t}\n\n\t\t\t\tsegment[j] += value;\n\t\t\t\tj++;\n\t\t\t\tvalue = shift = 0; // reset\n\t\t\t}\n\t\t}\n\t}\n\n\tsegmentify(line, segment, j);\n\tdecoded.push(line);\n\n\treturn decoded;\n}\n\nfunction segmentify(line: SourceMapSegment[], segment: SourceMapSegment, j: number) {\n\t// This looks ugly, but we're creating specialized arrays with a specific\n\t// length. This is much faster than creating a new array (which v8 expands to\n\t// a capacity of 17 after pushing the first item), or slicing out a subarray\n\t// (which is slow). Length 4 is assumed to be the most frequent, followed by\n\t// length 5 (since not everything will have an associated name), followed by\n\t// length 1 (it's probably rare for a source substring to not have an\n\t// associated segment data).\n\tif (j === 4) line.push([segment[0], segment[1], segment[2], segment[3]]);\n\telse if (j === 5) line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);\n\telse if (j === 1) line.push([segment[0]]);\n}\n\nexport function encode(decoded: SourceMapMappings): string {\n\tlet sourceFileIndex = 0; // second field\n\tlet sourceCodeLine = 0; // third field\n\tlet sourceCodeColumn = 0; // fourth field\n\tlet nameIndex = 0; // fifth field\n\tlet mappings = '';\n\n\tfor (let i = 0; i < decoded.length; i++) {\n\t\tconst line = decoded[i];\n\t\tif (i > 0) mappings += ';';\n\t\tif (line.length === 0) continue;\n\n\t\tlet generatedCodeColumn = 0; // first field\n\n\t\tconst lineMappings: string[] = [];\n\n\t\tfor (const segment of line) {\n\t\t\tlet segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);\n\t\t\tgeneratedCodeColumn = segment[0];\n\n\t\t\tif (segment.length > 1) {\n\t\t\t\tsegmentMappings +=\n\t\t\t\t\tencodeInteger(segment[1] - sourceFileIndex) +\n\t\t\t\t\tencodeInteger(segment[2] - sourceCodeLine) +\n\t\t\t\t\tencodeInteger(segment[3] - sourceCodeColumn);\n\n\t\t\t\tsourceFileIndex = segment[1];\n\t\t\t\tsourceCodeLine = segment[2];\n\t\t\t\tsourceCodeColumn = segment[3];\n\t\t\t}\n\n\t\t\tif (segment.length === 5) {\n\t\t\t\tsegmentMappings += encodeInteger(segment[4] - nameIndex);\n\t\t\t\tnameIndex = segment[4];\n\t\t\t}\n\n\t\t\tlineMappings.push(segmentMappings);\n\t\t}\n\n\t\tmappings += lineMappings.join(',');\n\t}\n\n\treturn mappings;\n}\n\nfunction encodeInteger(num: number): string {\n\tvar result = '';\n\tnum = num < 0 ? (-num << 1) | 1 : num << 1;\n\tdo {\n\t\tvar clamped = num & 31;\n\t\tnum >>>= 5;\n\t\tif (num > 0) {\n\t\t\tclamped |= 32;\n\t\t}\n\t\tresult += chars[clamped];\n\t} while (num > 0);\n\n\treturn result;\n}\n"],"names":[],"mappings":"AAOA,IAAM,aAAa,GAAmC,EAAE,CAAC;AACzD,IAAM,KAAK,GAAG,mEAAmE,CAAC;AAElF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,E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CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;gBACzD,SAAS,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;aACvB;YAED,YAAY,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;SACnC;QAED,QAAQ,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;KACnC;IAED,OAAO,QAAQ,CAAC;CAChB;AAED,SAAS,aAAa,CAAC,GAAW;IACjC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;IAC3C,GAAG;QACF,IAAI,OAAO,GAAG,GAAG,GAAG,EAAE,CAAC;QACvB,GAAG,MAAM,CAAC,CAAC;QACX,IAAI,GAAG,GAAG,CAAC,EAAE;YACZ,OAAO,IAAI,EAAE,CAAC;SACd;QACD,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;KACzB,QAAQ,GAAG,GAAG,CAAC,EAAE;IAElB,OAAO,MAAM,CAAC;CACd;;;;"} \ No newline at end of file diff --git a/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..e305147 --- /dev/null +++ b/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,135 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.sourcemapCodec = {})); +}(this, function (exports) { 'use strict'; + + var charToInteger = {}; + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + for (var i = 0; i < chars.length; i++) { + charToInteger[chars.charCodeAt(i)] = i; + } + function decode(mappings) { + var decoded = []; + var line = []; + var segment = [ + 0, + 0, + 0, + 0, + 0, + ]; + var j = 0; + for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) { + var c = mappings.charCodeAt(i); + if (c === 44) { // "," + segmentify(line, segment, j); + j = 0; + } + else if (c === 59) { // ";" + segmentify(line, segment, j); + j = 0; + decoded.push(line); + line = []; + segment[0] = 0; + } + else { + var integer = charToInteger[c]; + if (integer === undefined) { + throw new Error('Invalid character (' + String.fromCharCode(c) + ')'); + } + var hasContinuationBit = integer & 32; + integer &= 31; + value += integer << shift; + if (hasContinuationBit) { + shift += 5; + } + else { + var shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = value === 0 ? -0x80000000 : -value; + } + segment[j] += value; + j++; + value = shift = 0; // reset + } + } + } + segmentify(line, segment, j); + decoded.push(line); + return decoded; + } + function segmentify(line, segment, j) { + // This looks ugly, but we're creating specialized arrays with a specific + // length. This is much faster than creating a new array (which v8 expands to + // a capacity of 17 after pushing the first item), or slicing out a subarray + // (which is slow). Length 4 is assumed to be the most frequent, followed by + // length 5 (since not everything will have an associated name), followed by + // length 1 (it's probably rare for a source substring to not have an + // associated segment data). + if (j === 4) + line.push([segment[0], segment[1], segment[2], segment[3]]); + else if (j === 5) + line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]); + else if (j === 1) + line.push([segment[0]]); + } + function encode(decoded) { + var sourceFileIndex = 0; // second field + var sourceCodeLine = 0; // third field + var sourceCodeColumn = 0; // fourth field + var nameIndex = 0; // fifth field + var mappings = ''; + for (var i = 0; i < decoded.length; i++) { + var line = decoded[i]; + if (i > 0) + mappings += ';'; + if (line.length === 0) + continue; + var generatedCodeColumn = 0; // first field + var lineMappings = []; + for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { + var segment = line_1[_i]; + var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn); + generatedCodeColumn = segment[0]; + if (segment.length > 1) { + segmentMappings += + encodeInteger(segment[1] - sourceFileIndex) + + encodeInteger(segment[2] - sourceCodeLine) + + encodeInteger(segment[3] - sourceCodeColumn); + sourceFileIndex = segment[1]; + sourceCodeLine = segment[2]; + sourceCodeColumn = segment[3]; + } + if (segment.length === 5) { + segmentMappings += encodeInteger(segment[4] - nameIndex); + nameIndex = segment[4]; + } + lineMappings.push(segmentMappings); + } + mappings += lineMappings.join(','); + } + return mappings; + } + function encodeInteger(num) { + var result = ''; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + var clamped = num & 31; + num >>>= 5; + if (num > 0) { + clamped |= 32; + } + result += chars[clamped]; + } while (num > 0); + return result; + } + + exports.decode = decode; + exports.encode = encode; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..6ea33e0 --- /dev/null +++ b/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.umd.js","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n\t| [number]\n\t| [number, number, number, number]\n\t| [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst charToInteger: { [charCode: number]: number } = {};\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfor (let i = 0; i < chars.length; i++) {\n\tcharToInteger[chars.charCodeAt(i)] = i;\n}\n\nexport function decode(mappings: string): SourceMapMappings {\n\tconst decoded: SourceMapMappings = [];\n\tlet line: SourceMapLine = [];\n\tconst segment: SourceMapSegment = [\n\t\t0, // generated code column\n\t\t0, // source file index\n\t\t0, // source code line\n\t\t0, // source code column\n\t\t0, // name index\n\t];\n\n\tlet j = 0;\n\tfor (let i = 0, shift = 0, value = 0; i < mappings.length; i++) {\n\t\tconst c = mappings.charCodeAt(i);\n\n\t\tif (c === 44) { // \",\"\n\t\t\tsegmentify(line, segment, j);\n\t\t\tj = 0;\n\n\t\t} else if (c === 59) { // \";\"\n\t\t\tsegmentify(line, segment, j);\n\t\t\tj = 0;\n\t\t\tdecoded.push(line);\n\t\t\tline = [];\n\t\t\tsegment[0] = 0;\n\n\t\t} else {\n\t\t\tlet integer = charToInteger[c];\n\t\t\tif (integer === undefined) {\n\t\t\t\tthrow new Error('Invalid character (' + String.fromCharCode(c) + ')');\n\t\t\t}\n\n\t\t\tconst hasContinuationBit = integer & 32;\n\n\t\t\tinteger &= 31;\n\t\t\tvalue += integer << shift;\n\n\t\t\tif (hasContinuationBit) {\n\t\t\t\tshift += 5;\n\t\t\t} else {\n\t\t\t\tconst shouldNegate = value & 1;\n\t\t\t\tvalue >>>= 1;\n\n\t\t\t\tif (shouldNegate) {\n\t\t\t\t\tvalue = value === 0 ? -0x80000000 : -value;\n\t\t\t\t}\n\n\t\t\t\tsegment[j] += value;\n\t\t\t\tj++;\n\t\t\t\tvalue = shift = 0; // reset\n\t\t\t}\n\t\t}\n\t}\n\n\tsegmentify(line, segment, j);\n\tdecoded.push(line);\n\n\treturn decoded;\n}\n\nfunction segmentify(line: SourceMapSegment[], segment: SourceMapSegment, j: number) {\n\t// This looks ugly, but we're creating specialized arrays with a specific\n\t// length. This is much faster than creating a new array (which v8 expands to\n\t// a capacity of 17 after pushing the first item), or slicing out a subarray\n\t// (which is slow). Length 4 is assumed to be the most frequent, followed by\n\t// length 5 (since not everything will have an associated name), followed by\n\t// length 1 (it's probably rare for a source substring to not have an\n\t// associated segment data).\n\tif (j === 4) line.push([segment[0], segment[1], segment[2], segment[3]]);\n\telse if (j === 5) line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);\n\telse if (j === 1) line.push([segment[0]]);\n}\n\nexport function encode(decoded: SourceMapMappings): string {\n\tlet sourceFileIndex = 0; // second field\n\tlet sourceCodeLine = 0; // third field\n\tlet sourceCodeColumn = 0; // fourth field\n\tlet nameIndex = 0; // fifth field\n\tlet mappings = '';\n\n\tfor (let i = 0; i < decoded.length; i++) {\n\t\tconst line = decoded[i];\n\t\tif (i > 0) mappings += ';';\n\t\tif (line.length === 0) continue;\n\n\t\tlet generatedCodeColumn = 0; // first field\n\n\t\tconst lineMappings: string[] = [];\n\n\t\tfor (const segment of line) {\n\t\t\tlet segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);\n\t\t\tgeneratedCodeColumn = segment[0];\n\n\t\t\tif (segment.length > 1) {\n\t\t\t\tsegmentMappings +=\n\t\t\t\t\tencodeInteger(segment[1] - sourceFileIndex) +\n\t\t\t\t\tencodeInteger(segment[2] - sourceCodeLine) +\n\t\t\t\t\tencodeInteger(segment[3] - sourceCodeColumn);\n\n\t\t\t\tsourceFileIndex = segment[1];\n\t\t\t\tsourceCodeLine = segment[2];\n\t\t\t\tsourceCodeColumn = segment[3];\n\t\t\t}\n\n\t\t\tif (segment.length === 5) {\n\t\t\t\tsegmentMappings += encodeInteger(segment[4] - nameIndex);\n\t\t\t\tnameIndex = segment[4];\n\t\t\t}\n\n\t\t\tlineMappings.push(segmentMappings);\n\t\t}\n\n\t\tmappings += lineMappings.join(',');\n\t}\n\n\treturn mappings;\n}\n\nfunction encodeInteger(num: number): string {\n\tvar result = '';\n\tnum = num < 0 ? (-num << 1) | 1 : num << 1;\n\tdo {\n\t\tvar clamped = num & 31;\n\t\tnum >>>= 5;\n\t\tif (num > 0) {\n\t\t\tclamped |= 32;\n\t\t}\n\t\tresult += chars[clamped];\n\t} while (num > 0);\n\n\treturn result;\n}\n"],"names":[],"mappings":";;;;;;CAOA,IAAM,aAAa,GAAmC,EAAE,CAAC;CACzD,IAAM,KAAK,GAAG,mEAAmE,CAAC;CAElF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;KACtC,aAAa,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;EACvC;AAED,UAAgB,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vB;aAED,YAAY,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;UACnC;SAED,QAAQ,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;MACnC;KAED,OAAO,QAAQ,CAAC;CACjB,CAAC;CAED,SAAS,aAAa,CAAC,GAAW;KACjC,IAAI,MAAM,GAAG,EAAE,CAAC;KAChB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;KAC3C,GAAG;SACF,IAAI,OAAO,GAAG,GAAG,GAAG,EAAE,CAAC;SACvB,GAAG,MAAM,CAAC,CAAC;SACX,IAAI,GAAG,GAAG,CAAC,EAAE;aACZ,OAAO,IAAI,EAAE,CAAC;UACd;SACD,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;MACzB,QAAQ,GAAG,GAAG,CAAC,EAAE;KAElB,OAAO,MAAM,CAAC;CACf,CAAC;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/sourcemap-codec/dist/types/sourcemap-codec.d.ts b/node_modules/sourcemap-codec/dist/types/sourcemap-codec.d.ts new file mode 100644 index 0000000..6ac3c1d --- /dev/null +++ b/node_modules/sourcemap-codec/dist/types/sourcemap-codec.d.ts @@ -0,0 +1,5 @@ +export declare type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export declare type SourceMapLine = SourceMapSegment[]; +export declare type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; diff --git a/node_modules/sourcemap-codec/package.json b/node_modules/sourcemap-codec/package.json new file mode 100644 index 0000000..4b2d219 --- /dev/null +++ b/node_modules/sourcemap-codec/package.json @@ -0,0 +1,53 @@ +{ + "name": "sourcemap-codec", + "version": "1.4.8", + "description": "Encode/decode sourcemap mappings", + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.es.js", + "types": "dist/types/sourcemap-codec.d.ts", + "scripts": { + "test": "mocha", + "build": "rm -rf dist && rollup -c && tsc", + "pretest": "npm run build", + "prepublish": "npm test", + "lint": "eslint src", + "pretest-coverage": "npm run build", + "test-coverage": "rm -rf coverage/* && istanbul cover --report json node_modules/.bin/_mocha -- -u exports -R spec test/test.js", + "posttest-coverage": "remap-istanbul -i coverage/coverage-final.json -o coverage/coverage-remapped.json -b dist && remap-istanbul -i coverage/coverage-final.json -o coverage/coverage-remapped.lcov -t lcovonly -b dist && remap-istanbul -i coverage/coverage-final.json -o coverage/coverage-remapped -t html -b dist", + "ci": "npm run test-coverage && codecov < coverage/coverage-remapped.lcov" + }, + "repository": { + "type": "git", + "url": "https://github.com/Rich-Harris/sourcemap-codec" + }, + "keywords": [ + "sourcemap", + "vlq" + ], + "author": "Rich Harris", + "license": "MIT", + "bugs": { + "url": "https://github.com/Rich-Harris/sourcemap-codec/issues" + }, + "homepage": "https://github.com/Rich-Harris/sourcemap-codec", + "dependencies": {}, + "devDependencies": { + "codecov.io": "^0.1.6", + "console-group": "^0.3.3", + "eslint": "^6.0.1", + "eslint-plugin-import": "^2.18.0", + "istanbul": "^0.4.5", + "mocha": "^6.1.4", + "remap-istanbul": "^0.13.0", + "rollup": "^1.16.4", + "rollup-plugin-node-resolve": "^5.2.0", + "rollup-plugin-typescript": "^1.0.1", + "typescript": "^3.5.2" + }, + "files": [ + "dist/*.js", + "dist/*.js.map", + "dist/**/*.d.ts", + "README.md" + ] +} diff --git a/node_modules/string-hash/.npmignore b/node_modules/string-hash/.npmignore new file mode 100644 index 0000000..07e6e47 --- /dev/null +++ b/node_modules/string-hash/.npmignore @@ -0,0 +1 @@ +/node_modules diff --git a/node_modules/string-hash/README.md b/node_modules/string-hash/README.md new file mode 100644 index 0000000..fd0d12f --- /dev/null +++ b/node_modules/string-hash/README.md @@ -0,0 +1,22 @@ +string-hash +=========== + +A fast string hashing function for Node.JS. The particular algorithm is quite +similar to `djb2`, by Dan Bernstein and available +[here](http://www.cse.yorku.ca/~oz/hash.html). Differences include iterating +over the string *backwards* (as that is faster in JavaScript) and using the XOR +operator instead of the addition operator (as described at that page and +because it obviates the need for modular arithmetic in JavaScript). + +The hashing function returns a number between 0 and 4294967295 (inclusive). + +Thanks to [cscott](https://github.com/cscott) for reminding us how integers +work in JavaScript. + +License +------- + +To the extend possible by law, The Dark Sky Company, LLC has [waived all +copyright and related or neighboring rights][cc0] to this library. + +[cc0]: http://creativecommons.org/publicdomain/zero/1.0/ diff --git a/node_modules/string-hash/component.json b/node_modules/string-hash/component.json new file mode 100644 index 0000000..487554a --- /dev/null +++ b/node_modules/string-hash/component.json @@ -0,0 +1,20 @@ +{ + "name": "string-hash", + "repo": "darkskyapp/string-hash", + "description": "fast string hashing function", + "version": "1.1.1", + "keywords": [ + "string", + "hashing" + ], + "dependencies": {}, + "development": { + "mocha": "1.3.x" + }, + "license": "CC0", + "main": "index.js", + "scripts": [ + "index.js" + ], + "remotes": [] +} \ No newline at end of file diff --git a/node_modules/string-hash/index.js b/node_modules/string-hash/index.js new file mode 100644 index 0000000..3bc4a82 --- /dev/null +++ b/node_modules/string-hash/index.js @@ -0,0 +1,17 @@ +"use strict"; + +function hash(str) { + var hash = 5381, + i = str.length; + + while(i) { + hash = (hash * 33) ^ str.charCodeAt(--i); + } + + /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed + * integers. Since we want the results to be always positive, convert the + * signed int to an unsigned by doing an unsigned bitshift. */ + return hash >>> 0; +} + +module.exports = hash; diff --git a/node_modules/string-hash/package.json b/node_modules/string-hash/package.json new file mode 100644 index 0000000..4eff969 --- /dev/null +++ b/node_modules/string-hash/package.json @@ -0,0 +1,27 @@ +{ + "name": "string-hash", + "version": "1.1.3", + "description": "fast string hashing function", + "license": "CC0-1.0", + "keywords": [ + "string", + "hashing" + ], + "author": { + "name": "The Dark Sky Company", + "email": "developer@darksky.net" + }, + "repository": { + "type": "git", + "url": "git://github.com/darkskyapp/string-hash.git" + }, + "main": "./index", + "dependencies": { + }, + "devDependencies": { + "mocha": "*" + }, + "scripts": { + "test": "mocha" + } +} diff --git a/node_modules/string-hash/test.js b/node_modules/string-hash/test.js new file mode 100644 index 0000000..ad193c6 --- /dev/null +++ b/node_modules/string-hash/test.js @@ -0,0 +1,13 @@ +"use strict"; +var assert = require("assert"), + hash = require("./"); + +describe("hash", function() { + it("should hash \"Mary had a little lamb.\" to 1766333550", function() { + assert.equal(hash("Mary had a little lamb."), 1766333550); + }); + + it("should hash \"Hello, world!\" to 343662184", function() { + assert.equal(hash("Hello, world!"), 343662184); + }); +}); diff --git a/node_modules/to-fast-properties/index.js b/node_modules/to-fast-properties/index.js new file mode 100644 index 0000000..028c88a --- /dev/null +++ b/node_modules/to-fast-properties/index.js @@ -0,0 +1,27 @@ +'use strict'; + +let fastProto = null; + +// Creates an object with permanently fast properties in V8. See Toon Verwaest's +// post https://medium.com/@tverwaes/setting-up-prototypes-in-v8-ec9c9491dfe2#5f62 +// for more details. Use %HasFastProperties(object) and the Node.js flag +// --allow-natives-syntax to check whether an object has fast properties. +function FastObject(o) { + // A prototype object will have "fast properties" enabled once it is checked + // against the inline property cache of a function, e.g. fastProto.property: + // https://github.com/v8/v8/blob/6.0.122/test/mjsunit/fast-prototype.js#L48-L63 + if (fastProto !== null && typeof fastProto.property) { + const result = fastProto; + fastProto = FastObject.prototype = null; + return result; + } + fastProto = FastObject.prototype = o == null ? Object.create(null) : o; + return new FastObject; +} + +// Initialize the inline property cache of FastObject +FastObject(); + +module.exports = function toFastproperties(o) { + return FastObject(o); +}; diff --git a/node_modules/to-fast-properties/license b/node_modules/to-fast-properties/license new file mode 100644 index 0000000..cef79ef --- /dev/null +++ b/node_modules/to-fast-properties/license @@ -0,0 +1,10 @@ +MIT License + +Copyright (c) 2014 Petka Antonov + 2015 Sindre Sorhus + +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/to-fast-properties/package.json b/node_modules/to-fast-properties/package.json new file mode 100644 index 0000000..7a64b2c --- /dev/null +++ b/node_modules/to-fast-properties/package.json @@ -0,0 +1,35 @@ +{ + "name": "to-fast-properties", + "version": "2.0.0", + "description": "Force V8 to use fast properties for an object", + "license": "MIT", + "repository": "sindresorhus/to-fast-properties", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "node --allow-natives-syntax test.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "obj", + "properties", + "props", + "v8", + "optimize", + "fast", + "convert", + "mode" + ], + "devDependencies": { + "ava": "0.0.4" + } +} diff --git a/node_modules/to-fast-properties/readme.md b/node_modules/to-fast-properties/readme.md new file mode 100644 index 0000000..692101d --- /dev/null +++ b/node_modules/to-fast-properties/readme.md @@ -0,0 +1,37 @@ +# to-fast-properties [![Build Status](https://travis-ci.org/sindresorhus/to-fast-properties.svg?branch=master)](https://travis-ci.org/sindresorhus/to-fast-properties) + +> Force V8 to use fast properties for an object + +[Read more.](http://stackoverflow.com/questions/24987896/) + +Use `%HasFastProperties(object)` and `--allow-natives-syntax` to check whether an object already has fast properties. + + +## Install + +``` +$ npm install --save to-fast-properties +``` + + +## Usage + +```js +const toFastProperties = require('to-fast-properties'); + +const obj = { + foo: true, + bar: true +}; + +delete obj.foo; +// `obj` now has slow properties + +toFastProperties(obj); +// `obj` now has fast properties +``` + + +## License + +MIT © Petka Antonov, John-David Dalton, Sindre Sorhus diff --git a/node_modules/util-deprecate/History.md b/node_modules/util-deprecate/History.md new file mode 100644 index 0000000..acc8675 --- /dev/null +++ b/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/node_modules/util-deprecate/LICENSE b/node_modules/util-deprecate/LICENSE new file mode 100644 index 0000000..6a60e8c --- /dev/null +++ b/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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/util-deprecate/README.md b/node_modules/util-deprecate/README.md new file mode 100644 index 0000000..75622fa --- /dev/null +++ b/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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/util-deprecate/browser.js b/node_modules/util-deprecate/browser.js new file mode 100644 index 0000000..549ae2f --- /dev/null +++ b/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * 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'; +} diff --git a/node_modules/util-deprecate/node.js b/node_modules/util-deprecate/node.js new file mode 100644 index 0000000..5e6fcff --- /dev/null +++ b/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/node_modules/util-deprecate/package.json b/node_modules/util-deprecate/package.json new file mode 100644 index 0000000..2e79f89 --- /dev/null +++ b/node_modules/util-deprecate/package.json @@ -0,0 +1,27 @@ +{ + "name": "util-deprecate", + "version": "1.0.2", + "description": "The Node.js `util.deprecate()` function with browser support", + "main": "node.js", + "browser": "browser.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "homepage": "https://github.com/TooTallNate/util-deprecate" +} diff --git a/node_modules/vite/CHANGELOG.md b/node_modules/vite/CHANGELOG.md new file mode 100644 index 0000000..d66af44 --- /dev/null +++ b/node_modules/vite/CHANGELOG.md @@ -0,0 +1,2047 @@ +## [2.5.3](https://github.com/vitejs/vite/compare/v2.5.2...v2.5.3) (2021-09-01) + + +### Bug Fixes + +* apply SSR externalization heuristic to devDependencies ([#4699](https://github.com/vitejs/vite/issues/4699)) ([0f1d6be](https://github.com/vitejs/vite/commit/0f1d6be100e3d6fda391b024ec14d2b4091993cb)) +* **resolve:** normalize optimized resolved path ([#4813](https://github.com/vitejs/vite/issues/4813)) ([fa6475f](https://github.com/vitejs/vite/commit/fa6475fd4230fb2ab200485bc35b136b2474abfd)) + + + +## [2.5.2](https://github.com/vitejs/vite/compare/v2.5.1...v2.5.2) (2021-08-31) + + +### Bug Fixes + +* decode url for middleware ([#4728](https://github.com/vitejs/vite/issues/4728)) ([824d042](https://github.com/vitejs/vite/commit/824d042535033a5c3d7006978c0d05c201cd1c25)) +* don't transform new URL(url, import.meta.url) in comments ([#4732](https://github.com/vitejs/vite/issues/4732)) ([bf0b631](https://github.com/vitejs/vite/commit/bf0b631e7479ed70d02b98b780cf7e4b02d0344b)) +* prevent pre-bundling @vite/client and @vite/env ([#4716](https://github.com/vitejs/vite/issues/4716)) ([e8c1906](https://github.com/vitejs/vite/commit/e8c19069984835114084dbc650f2a01335d6365f)) +* special handling for ssr.noExternal in mergeConfig ([#4766](https://github.com/vitejs/vite/issues/4766)) ([689a2c8](https://github.com/vitejs/vite/commit/689a2c8cbab0887dba0994dd0e9dc5515ab9d461)) +* **ssr:** resolve .cjs file extensions ([#4772](https://github.com/vitejs/vite/issues/4772)) ([96712ad](https://github.com/vitejs/vite/commit/96712adf5a404dbafa9b6ca4abd83ac98d5ce356)) +* unexpected file request with custom publicDir, fix [#4629](https://github.com/vitejs/vite/issues/4629) ([#4631](https://github.com/vitejs/vite/issues/4631)) ([7be6c0c](https://github.com/vitejs/vite/commit/7be6c0c90a6224d3525af9c44b29ba48ef63ebf2)) + + +### Features + +* add `.pdf` to list of known asset types ([#4752](https://github.com/vitejs/vite/issues/4752)) ([d891641](https://github.com/vitejs/vite/commit/d891641ab2be85e151d86dfd1720c05a63dec51d)) +* allow custom vite env prefix ([#4676](https://github.com/vitejs/vite/issues/4676)) ([dfdb9cc](https://github.com/vitejs/vite/commit/dfdb9cc41197a750850b60c36a9f6855c4481168)) +* allow use of clientPort without middlewareMode ([#4332](https://github.com/vitejs/vite/issues/4332)) ([da0abc5](https://github.com/vitejs/vite/commit/da0abc59935febdd7522941100d235c84c08d5b4)) +* **optimizer:** nested optimization ([#4634](https://github.com/vitejs/vite/issues/4634)) ([f61ec46](https://github.com/vitejs/vite/commit/f61ec46a077b92f5b1ce99bdac472a4c32052a13)) + + + +## [2.5.1](https://github.com/vitejs/vite/compare/v2.5.0...v2.5.1) (2021-08-24) + + +### Bug Fixes + +* __DEFINES__ is not defined is env ([#4694](https://github.com/vitejs/vite/issues/4694)) ([ff50c22](https://github.com/vitejs/vite/commit/ff50c22f9c71ac968f0fc4503e892452ccdf5ef5)) +* `Matcher` for chokidar WatchOptions#ignored ([#4616](https://github.com/vitejs/vite/issues/4616)) ([89e7a41](https://github.com/vitejs/vite/commit/89e7a419d7108dc3344d0bc5690798f695a46fd1)) +* enable failing dependencies to be optimised by pre-processing them with esbuild ([#4275](https://github.com/vitejs/vite/issues/4275)) ([ea98a1a](https://github.com/vitejs/vite/commit/ea98a1a1d257d235d3f12948d049c66e6a941362)) +* **css:** minify css will transform rgba to #rrggbbaa ([#4658](https://github.com/vitejs/vite/issues/4658)) ([632a50a](https://github.com/vitejs/vite/commit/632a50acd693f4ba79af7d22f1df14cf20e66538)) +* CSS dependencies are tracked incorrectly when base is set ([#4592](https://github.com/vitejs/vite/issues/4592)) ([633c03a](https://github.com/vitejs/vite/commit/633c03aa05755da47c2f2e00aa52f3f6460ac382)) +* **css:** dynamic import css abnormal after build ([#3333](https://github.com/vitejs/vite/issues/3333)) ([b572f57](https://github.com/vitejs/vite/commit/b572f57ec067abfaa1355cab3efdadf306592202)) +* **scan:** do not match 'export default' in comments ([#4602](https://github.com/vitejs/vite/issues/4602)) ([8b85f5f](https://github.com/vitejs/vite/commit/8b85f5f5cc72b8d50416ab0ab5ae045119e944be)) +* **vite:** unexptected overwriting for default export fix([#4553](https://github.com/vitejs/vite/issues/4553)) ([#4596](https://github.com/vitejs/vite/issues/4596)) ([c7929ad](https://github.com/vitejs/vite/commit/c7929ad1f96f1dd4f59e55626cedd6254add8538)) +* surface exception when failing to resolve package entry ([#4426](https://github.com/vitejs/vite/issues/4426)) ([f75e508](https://github.com/vitejs/vite/commit/f75e5080c0e479c4b8d66f48da06417e0a180016)) + + +### Features + +* Add `ssr.noExternal = true` option ([#4490](https://github.com/vitejs/vite/issues/4490)) ([963387a](https://github.com/vitejs/vite/commit/963387adbbceaf0336f8b4c9661f76511c0094ac)) +* make redirect easier when visit a non-based page ([#4618](https://github.com/vitejs/vite/issues/4618)) ([b97afa7](https://github.com/vitejs/vite/commit/b97afa76ec0b6ccd6e7dd99a254e109f67692bf7)) + + + +# [2.5.0](https://github.com/vitejs/vite/compare/v2.5.0-beta.3...v2.5.0) (2021-08-16) + + + +# [2.5.0-beta.3](https://github.com/vitejs/vite/compare/v2.5.0-beta.2...v2.5.0-beta.3) (2021-08-14) + + +### Bug Fixes + +* add ?inline css query typings ([#4570](https://github.com/vitejs/vite/issues/4570)) ([c8a17a2](https://github.com/vitejs/vite/commit/c8a17a23de4cde5d8d523ebc1b437e5b191446dd)) +* skip optimizer run on non-JS script tags ([#4565](https://github.com/vitejs/vite/issues/4565)) ([270bd3a](https://github.com/vitejs/vite/commit/270bd3a72dbf8dfb839909545659dde1d14e1e38)) +* support dangling comma and throw on circular dependency in tsconfig ([#4590](https://github.com/vitejs/vite/issues/4590)) ([f318416](https://github.com/vitejs/vite/commit/f3184161fde7df614b584520ddef5d7f049a5ff0)) + + + +# [2.5.0-beta.2](https://github.com/vitejs/vite/compare/v2.5.0-beta.1...v2.5.0-beta.2) (2021-08-09) + + +### Bug Fixes + +* **client:** vite-error-overlay customElement is registered twice ([#4475](https://github.com/vitejs/vite/issues/4475)) ([28a9612](https://github.com/vitejs/vite/commit/28a9612d65f9004d6a3c698f86f7b22796347768)) +* add missing assets to `packages/vite/client.d.ts` ([#4516](https://github.com/vitejs/vite/issues/4516)) ([420d82d](https://github.com/vitejs/vite/commit/420d82dc31c930fd82c28612e3dd864f35278503)) +* avoid crash when a file imported in SCSS does not exist ([#4505](https://github.com/vitejs/vite/issues/4505)) ([a03e944](https://github.com/vitejs/vite/commit/a03e94419ef4da3b842f0211536afb1501bc0919)) + + +### Features + +* add asset name ([#3028](https://github.com/vitejs/vite/issues/3028)) ([#3050](https://github.com/vitejs/vite/issues/3050)) ([a055938](https://github.com/vitejs/vite/commit/a05593894bb76ac46897c6833dffed04de71b960)) +* import `.webmanifest` assets as URL ([#4515](https://github.com/vitejs/vite/issues/4515)) ([8c5ac3f](https://github.com/vitejs/vite/commit/8c5ac3f89c69717b3bddedc229b77fabb9239085)) +* log a warning if dependency pre-bundling cannot be run ([#4546](https://github.com/vitejs/vite/issues/4546)) ([120f3b9](https://github.com/vitejs/vite/commit/120f3b97456597998b29413e8eec5e7ad41f2e7a)) + + + +# [2.5.0-beta.1](https://github.com/vitejs/vite/compare/v2.5.0-beta.0...v2.5.0-beta.1) (2021-08-04) + + +### Bug Fixes + +* change the preview default mode from `development` to `production` ([#4483](https://github.com/vitejs/vite/issues/4483)) ([77933ba](https://github.com/vitejs/vite/commit/77933ba86e7b15cb32ba80c27ae707db2a598cec)) +* close vite dev server before creating new one ([#4374](https://github.com/vitejs/vite/issues/4374)) ([9e4572e](https://github.com/vitejs/vite/commit/9e4572edf5a21db9ed2d5ffa9c1a54dbea3687b3)) +* register files added by addWatchFile() as current module's dependency ([db4ba56](https://github.com/vitejs/vite/commit/db4ba56e38a2ce7fa4a4ecf52d9eb0f375073560)), closes [#3216](https://github.com/vitejs/vite/issues/3216) + + +### Features + +* add `logger.hasErrorLogged(error)` method ([#3957](https://github.com/vitejs/vite/issues/3957)) ([fb406ce](https://github.com/vitejs/vite/commit/fb406ce4c0fe6da3333c9d1c00477b2880d46352)) + + + +# [2.5.0-beta.0](https://github.com/vitejs/vite/compare/v2.4.4...v2.5.0-beta.0) (2021-08-03) + + +### Bug Fixes + +* mixed match result of importMetaUrl ([#4482](https://github.com/vitejs/vite/issues/4482)) ([86f673a](https://github.com/vitejs/vite/commit/86f673abf4af38ab7a1e408f96e3447fdfcc5396)) +* **build:** respect rollup output.assetFileNames, fix [#2944](https://github.com/vitejs/vite/issues/2944) ([#4352](https://github.com/vitejs/vite/issues/4352)) ([cbd0458](https://github.com/vitejs/vite/commit/cbd04588a2fe62e689fc5f7bb0b71610b88f2a3e)) +* **deps:** update all non-major dependencies ([#4468](https://github.com/vitejs/vite/issues/4468)) ([cd54a22](https://github.com/vitejs/vite/commit/cd54a22b8d5048f5d25a9954697f49b6d65dcc1f)) +* **html:** cover more cases in bodyPrependInjectRE ([#4474](https://github.com/vitejs/vite/issues/4474)) ([40c51e1](https://github.com/vitejs/vite/commit/40c51e16802d39fef03d145bfc3a5089867dd8cb)) +* **server:** keep port when modifying the config file ([#4460](https://github.com/vitejs/vite/issues/4460)) ([056b17e](https://github.com/vitejs/vite/commit/056b17eb82becd08217346dddb47f8ecbf55fe3f)) +* config port timing, fix [#4094](https://github.com/vitejs/vite/issues/4094) ([#4104](https://github.com/vitejs/vite/issues/4104)) ([6b98fdd](https://github.com/vitejs/vite/commit/6b98fddd84545a8500ac7767c514c6ce3bf3bf96)) +* overwrite configEnv.mode if the user explicitly set mode option (fix [#4441](https://github.com/vitejs/vite/issues/4441)) ([#4437](https://github.com/vitejs/vite/issues/4437)) ([7d340a6](https://github.com/vitejs/vite/commit/7d340a6339cb5497ef54d3684697c4660ab97302)) +* update dependency @rollup/plugin-commonjs to v20, fix [#2623](https://github.com/vitejs/vite/issues/2623) ([#4469](https://github.com/vitejs/vite/issues/4469)) ([f9e5d63](https://github.com/vitejs/vite/commit/f9e5d638431dc27619d0cafdd7ea0dd8543133d3)) +* **scan:** improve import regex and allow multiline comments ([#4088](https://github.com/vitejs/vite/issues/4088)) ([76dbef6](https://github.com/vitejs/vite/commit/76dbef62741d4a53be1e6e8a0e04d3727759cc93)) +* @vite/client http request is 404 not found ([#4187](https://github.com/vitejs/vite/issues/4187)) ([21ecdac](https://github.com/vitejs/vite/commit/21ecdacb40ba4fd1b8d248e1a1c99c21257f238d)) +* import sass file even if not listed in package.json ([#3627](https://github.com/vitejs/vite/issues/3627)) ([a5b2b4f](https://github.com/vitejs/vite/commit/a5b2b4f11c5335828fd8179721aee73191df46e9)) +* the return value of resolve by adding a namespace when processing a '@' in filter ([#3534](https://github.com/vitejs/vite/issues/3534)) ([d4e979f](https://github.com/vitejs/vite/commit/d4e979fbe70e2e7ab03407bd601b813e1671c144)) +* **build:** fix define plugin spread operations ([#4397](https://github.com/vitejs/vite/issues/4397)) ([bd7c148](https://github.com/vitejs/vite/commit/bd7c1481cecf5eecc87a69ff8e8f54fa4bf4bfed)) +* preserve base in HMR for CSS referenced in link tags ([#4407](https://github.com/vitejs/vite/issues/4407)) ([a06b26b](https://github.com/vitejs/vite/commit/a06b26b461dd05451c6c1ca20fce3b0e392c086e)) + + +### Features + +* **ssr:** tolerate circular imports ([#3950](https://github.com/vitejs/vite/issues/3950)) ([69f91a1](https://github.com/vitejs/vite/commit/69f91a1c03a129ab324c20fddfd2a07e729add96)) +* implement custom logger ([#2521](https://github.com/vitejs/vite/issues/2521)) ([59841f0](https://github.com/vitejs/vite/commit/59841f0b65a2e554db964e530b18dcdc9b3b9586)) +* **css:** support css module compose/from path resolution ([#4378](https://github.com/vitejs/vite/issues/4378)) ([690b35e](https://github.com/vitejs/vite/commit/690b35e857cea833ed4f1782e5c87b2b7064d072)) +* minify css with esbuild, deprecate build.cleanCssOptions ([#4371](https://github.com/vitejs/vite/issues/4371)) ([4454688](https://github.com/vitejs/vite/commit/4454688bd8eda0217ec3c7397038bf3ece39b5b0)) +* modulepreload polyfill ([#4058](https://github.com/vitejs/vite/issues/4058)) ([cb75dbd](https://github.com/vitejs/vite/commit/cb75dbd4a2b1c56e2a7aeaf1625818a4d1865f00)) +* respect tsconfig options that affects compilation results ([#4279](https://github.com/vitejs/vite/issues/4279)) ([2986f6e](https://github.com/vitejs/vite/commit/2986f6ec78818910675b7d4f81b3dbd6ca51143a)) + + + +## [2.4.4](https://github.com/vitejs/vite/compare/v2.4.3...v2.4.4) (2021-07-27) + + +### Bug Fixes + +* **deps:** update all non-major dependencies ([#4387](https://github.com/vitejs/vite/issues/4387)) ([2f900ba](https://github.com/vitejs/vite/commit/2f900ba4d4ad8061e0046898e8d1de3129e7f784)) +* --https get ignored in preview ([#4318](https://github.com/vitejs/vite/issues/4318)) ([a870584](https://github.com/vitejs/vite/commit/a8705846f7f604263a64aece67deb7593c498dcd)) +* don't interact with res if refresh has happened ([#4370](https://github.com/vitejs/vite/issues/4370)) ([c90b7d9](https://github.com/vitejs/vite/commit/c90b7d9d89a803b51d56f2885e5e61bbcf1c1c43)) +* fix pre-bundling executes multiple times ([#3640](https://github.com/vitejs/vite/issues/3640)) ([41a00df](https://github.com/vitejs/vite/commit/41a00dff62ee2ae60099953b1d3cc91f7bad0d7d)) +* handle imports from dot directories ([#3739](https://github.com/vitejs/vite/issues/3739)) ([f4f0100](https://github.com/vitejs/vite/commit/f4f0100649220453d961b6c66531c58026885680)) +* ignore ENOENT in `injectSourcesContent` ([#2904](https://github.com/vitejs/vite/issues/2904)) ([0693d03](https://github.com/vitejs/vite/commit/0693d038e096dd4db3140507269c6aaeefd2186e)) +* provide build load fallback for arbitrary request with queries ([f097aa1](https://github.com/vitejs/vite/commit/f097aa10c17faf0b73b239a34ca72934d38188d7)) +* **css:** cachedPostcssConfig reused for multiple builds ([#3906](https://github.com/vitejs/vite/issues/3906)) ([3a97644](https://github.com/vitejs/vite/commit/3a9764403722a32b8d51222025e6516ef557e178)) + + +### Features + +* support ?inline css query to avoid css insertion ([e1de8a8](https://github.com/vitejs/vite/commit/e1de8a888ea9adb9dc415cf74aec43dfa83aa526)) + + + +## [2.4.3](https://github.com/vitejs/vite/compare/v2.4.2...v2.4.3) (2021-07-20) + + +### Bug Fixes + +* call createFileOnlyEntry() only for CSS deps, fix [#4150](https://github.com/vitejs/vite/issues/4150) ([#4267](https://github.com/vitejs/vite/issues/4267)) ([89e3160](https://github.com/vitejs/vite/commit/89e3160d86bc8c27d6d33b82adec7c44016c3fc3)) +* **dev:** only rewrite SSR stacktrace when possible ([#4248](https://github.com/vitejs/vite/issues/4248)) ([887c247](https://github.com/vitejs/vite/commit/887c247984abc0f80d8b19a1d681855944f6d01a)) +* **util:** copyDir may cause an infinite loop ([#4310](https://github.com/vitejs/vite/issues/4310)) ([da64197](https://github.com/vitejs/vite/commit/da64197bc8bcd8f848aef3ae7a87a2d0d56ebd55)) +* correctly ignore optional deps when bundling vite deps ([#4223](https://github.com/vitejs/vite/issues/4223)) ([b5ab77d](https://github.com/vitejs/vite/commit/b5ab77d878d7bdc5c68dbbf144395f2a590f7d99)), closes [#3977](https://github.com/vitejs/vite/issues/3977) [#3850](https://github.com/vitejs/vite/issues/3850) +* do not end process in middleware mode, fix [#4196](https://github.com/vitejs/vite/issues/4196) ([#4232](https://github.com/vitejs/vite/issues/4232)) ([1c994f8](https://github.com/vitejs/vite/commit/1c994f840e707e1085ee1e1aed0986bb92e39422)) +* improve indent of built html file ([#4227](https://github.com/vitejs/vite/issues/4227)) ([0316f14](https://github.com/vitejs/vite/commit/0316f14eddb6854321ed0c1bbeb29c2668c6f08c)) +* nested dependencies from sub node_modules, fix [#3254](https://github.com/vitejs/vite/issues/3254) ([#4091](https://github.com/vitejs/vite/issues/4091)) ([b465d3e](https://github.com/vitejs/vite/commit/b465d3eb87d415b2f484dae77daab57adc3415bf)) + + +### Features + +* `vite preview` port is used automatically `+1` ([#4219](https://github.com/vitejs/vite/issues/4219)) ([179a057](https://github.com/vitejs/vite/commit/179a0576b2b8da4fc0c32a574b8ae487b8b5265a)) +* enable usage of function as library fileName, close [#3585](https://github.com/vitejs/vite/issues/3585) ([#3625](https://github.com/vitejs/vite/issues/3625)) ([772b2f7](https://github.com/vitejs/vite/commit/772b2f73b0da08181a7cc29e0eb50073ff3cc464)) +* extract `config.base` in `importAnalysisBuild.ts` ([#4096](https://github.com/vitejs/vite/issues/4096)) ([ab59598](https://github.com/vitejs/vite/commit/ab59598f4e07a466d8319e6d81047f75517085db)) +* library mode does not include preload ([#4097](https://github.com/vitejs/vite/issues/4097)) ([decc7d8](https://github.com/vitejs/vite/commit/decc7d885d108a3e96ffc82abcb4057f54aa6db5)) + + + +## [2.4.2](https://github.com/vitejs/vite/compare/v2.4.1...v2.4.2) (2021-07-12) + + +### Bug Fixes + +* __VITE_PRELOAD__ replacement error ([#4163](https://github.com/vitejs/vite/issues/4163)) ([d377aae](https://github.com/vitejs/vite/commit/d377aae05f73779869ba84c91e050fe0a9f50dce)), closes [#3051](https://github.com/vitejs/vite/issues/3051) +* shutdown process after closing server ([#4082](https://github.com/vitejs/vite/issues/4082)) ([eac779c](https://github.com/vitejs/vite/commit/eac779c3d7c306288b01a35239e9eaaa2273c1a5)) +* **build:** resolve license files correctly ([#4149](https://github.com/vitejs/vite/issues/4149)) ([bf32b41](https://github.com/vitejs/vite/commit/bf32b41bc4ac89e1fd39c27fb22c3bfa0a150152)) +* **utils:** add dot-all flag to match all characters, fix [#3761](https://github.com/vitejs/vite/issues/3761) ([#3780](https://github.com/vitejs/vite/issues/3780)) ([b9cdfbe](https://github.com/vitejs/vite/commit/b9cdfbeedcd74d33c30cab9d38b1a9ca6d1cd8c2)) + + +### Features + +* cache certificate ([#3642](https://github.com/vitejs/vite/issues/3642)) ([5dd670f](https://github.com/vitejs/vite/commit/5dd670f06dc2b0928771d571ce6ca5164b0db8e9)) + + + +## [2.4.1](https://github.com/vitejs/vite/compare/v2.4.0...v2.4.1) (2021-07-06) + + +### Bug Fixes + +* **hmr:** html registered as a PostCSS dependency, fix [#3716](https://github.com/vitejs/vite/issues/3716) ([#4127](https://github.com/vitejs/vite/issues/4127)) ([09c6c94](https://github.com/vitejs/vite/commit/09c6c94690ea3fc8b66bb6781995b3e15faedf8f)) +* specify full filepath to importMeta.d.ts, fix [#4125](https://github.com/vitejs/vite/issues/4125) ([#4138](https://github.com/vitejs/vite/issues/4138)) ([3bc1d78](https://github.com/vitejs/vite/commit/3bc1d78843d970d367e235f6c30fd7996cf7335a)) + + + +# [2.4.0](https://github.com/vitejs/vite/compare/v2.4.0-beta.3...v2.4.0) (2021-07-05) + + + +# [2.4.0-beta.3](https://github.com/vitejs/vite/compare/v2.4.0-beta.2...v2.4.0-beta.3) (2021-07-02) + + +### Bug Fixes + +* **ssr:** Transform named default exports without altering scope ([#4053](https://github.com/vitejs/vite/issues/4053)) ([5211aaf](https://github.com/vitejs/vite/commit/5211aaf9b71022a1153dd3ccdef540fd51be72c0)) +* add `type: "module"` hint to cache directory ([#4063](https://github.com/vitejs/vite/issues/4063)) ([58a29b2](https://github.com/vitejs/vite/commit/58a29b241662f77dbf971967b913f4e75f91fe26)) +* allow preprocessor to be installed outside of the root directory ([#3988](https://github.com/vitejs/vite/issues/3988)) ([a0a80f8](https://github.com/vitejs/vite/commit/a0a80f8e992393f01b4b7377e7dc53059ddf1fe1)) +* Avoid importing in source that __vitePreload has declared (close [#4016](https://github.com/vitejs/vite/issues/4016)) ([#4041](https://github.com/vitejs/vite/issues/4041)) ([bd34203](https://github.com/vitejs/vite/commit/bd34203bc40d6a406dfac3ab6cb41f5dfed63a77)) +* ensure that esbuild uses the same working directory as Vite ([#4001](https://github.com/vitejs/vite/issues/4001)) ([19abafe](https://github.com/vitejs/vite/commit/19abafeedda8008f4cc9eeda4cf8cb46e57de8b9)) +* fix esbuild break when importRe matches multiline import ([#4054](https://github.com/vitejs/vite/issues/4054)) ([eb2e41b](https://github.com/vitejs/vite/commit/eb2e41b098fb3d5f367c1f4fdfcad12f7538ac16)) +* skip redirect and error fallback on middleware mode ([#4057](https://github.com/vitejs/vite/issues/4057)) ([d156a9f](https://github.com/vitejs/vite/commit/d156a9f364dddcfc41338f83e39db38a00a2ceb0)) +* the current main branch code build the vite project error ([#4059](https://github.com/vitejs/vite/issues/4059)) ([4adc970](https://github.com/vitejs/vite/commit/4adc9706874581d2d5048fb48c135154591360cf)) +* use `.mjs` extension for injected client modules ([#4061](https://github.com/vitejs/vite/issues/4061)) ([cca92c4](https://github.com/vitejs/vite/commit/cca92c47d54e0f96b56964f13fbe0b2d050c5ed9)) +* use path type import, fix [#4028](https://github.com/vitejs/vite/issues/4028) ([#4031](https://github.com/vitejs/vite/issues/4031)) ([e092e89](https://github.com/vitejs/vite/commit/e092e899dad28f50aaa004419e9da50cf31db72d)) + + + +# [2.4.0-beta.2](https://github.com/vitejs/vite/compare/v2.4.0-beta.1...v2.4.0-beta.2) (2021-06-29) + + +### Bug Fixes + +* revert resolve nested dependencies [#3753](https://github.com/vitejs/vite/issues/3753) ([#4019](https://github.com/vitejs/vite/issues/4019)) ([b6f4293](https://github.com/vitejs/vite/commit/b6f4293435bf90c9a64476d8bfbb022f4f2af9a9)), closes [#4005](https://github.com/vitejs/vite/issues/4005) +* **commonjs:** `ignoreDynamicRequires` should default to `false` ([#4015](https://github.com/vitejs/vite/issues/4015)) ([c08069c](https://github.com/vitejs/vite/commit/c08069cb3bdf7e7aa16d9cfaef4c1aea3a29cfa2)), closes [/github.com/vitejs/vite/pull/3353#issuecomment-851520683](https://github.com//github.com/vitejs/vite/pull/3353/issues/issuecomment-851520683) [#3426](https://github.com/vitejs/vite/issues/3426) [#3997](https://github.com/vitejs/vite/issues/3997) +* **css:** skip comma when matching css url ([#4004](https://github.com/vitejs/vite/issues/4004)) ([7d0bc26](https://github.com/vitejs/vite/commit/7d0bc2691f0291c3a9b0df992554f18bf85c8892)) + + + +# [2.4.0-beta.1](https://github.com/vitejs/vite/compare/v2.4.0-beta.0...v2.4.0-beta.1) (2021-06-29) + + +### Bug Fixes + +* **hmr:** entry mod's importers contains css mod invalidate hmr ([#3929](https://github.com/vitejs/vite/issues/3929)) ([d97b33a](https://github.com/vitejs/vite/commit/d97b33a8cb9a72ed64244f239900a9a862b6ba68)) +* **types:** correct import of types ([#4003](https://github.com/vitejs/vite/issues/4003)) ([4954636](https://github.com/vitejs/vite/commit/4954636c859fbfce76d02aea7881e59435fa3211)) + + +### Features + +* allow passing options to rollupjs dynamic import vars plugin ([#3047](https://github.com/vitejs/vite/issues/3047)) ([5507b4c](https://github.com/vitejs/vite/commit/5507b4c912d2e0e36e63488f5db8e9d1bb0a80f6)) + + + +# [2.4.0-beta.0](https://github.com/vitejs/vite/compare/v2.3.8...v2.4.0-beta.0) (2021-06-27) + +### BREAKING CHANGES + +- **server:** `server.fsServe` renamed to `server.fs` ([#3965](https://github.com/vitejs/vite/pull/3965)) +- **server:** `server.fs.root` deprecated in favor of `server.fs.allow` ([#3968](https://github.com/vitejs/vite/pull/3968)) + +### Security + +We have improved the file serving boundaries detection with ([#3784](https://github.com/vitejs/vite/issues/3784)). While it's still experimental and **disabled by default**, you can opt-in it by + +```js +// vite.config.js +export default { + server: { + fs: { + strict: true + } + } +} +``` + +It should smartly serve the files related to your project (directly imported, linked deps, etc.) while denying the rest. If you find any false-negative, please [open an issue](https://github.com/vitejs/vite/issues/new?assignees=&labels=pending+triage&template=bug_report.yml) with reproduction to report. + +### Bug Fixes + +* **build:** bundle non-inlined workers with rollup ([#2494](https://github.com/vitejs/vite/issues/2494)) ([18a2208](https://github.com/vitejs/vite/commit/18a22089df34c32daddf3b280c58f25cae73f722)) +* resolve nested dependencies ([#3254](https://github.com/vitejs/vite/issues/3254)) ([#3753](https://github.com/vitejs/vite/issues/3753)) ([8467f64](https://github.com/vitejs/vite/commit/8467f64aee218dcb3135bb832ccaed36d647052f)) +* **css:** file or contents missing error in build watch ([#3742](https://github.com/vitejs/vite/issues/3742)) ([#3747](https://github.com/vitejs/vite/issues/3747)) ([26b1b99](https://github.com/vitejs/vite/commit/26b1b9988db1ab980ca816d1914b26d6d3424502)) +* **deps:** update all non-major dependencies ([#3878](https://github.com/vitejs/vite/issues/3878)) ([a66a805](https://github.com/vitejs/vite/commit/a66a8053e9520d20bcf95fce870570c5195bcc91)) +* **scan:** 'for await' support in script setup for dev server ([#3889](https://github.com/vitejs/vite/issues/3889)) ([dd46cd1](https://github.com/vitejs/vite/commit/dd46cd1d030dcfffcbb2f20aff2b388cd18700f4)) +* **scan:** avoid breaking html comment regex inside script of scanned html-like files ([bb095db](https://github.com/vitejs/vite/commit/bb095db11db5c7a12db6dcee866694f1f68d1e15)) +* **ssr:** fix binding overwrite at nested function, fix [#3856](https://github.com/vitejs/vite/issues/3856) ([#3869](https://github.com/vitejs/vite/issues/3869)) ([85f51c1](https://github.com/vitejs/vite/commit/85f51c191d4d3317c5796e6c614ade6f7c21dddf)) +* **ssr:** normalize manifest filenames ([#3706](https://github.com/vitejs/vite/issues/3706)) ([aa8ca3f](https://github.com/vitejs/vite/commit/aa8ca3f35218c9fb48f87d3f6f4681d379ee45ca)), closes [#3303](https://github.com/vitejs/vite/issues/3303) +* **ssr:** not flatten export * as (fix [#3934](https://github.com/vitejs/vite/issues/3934)) ([#3954](https://github.com/vitejs/vite/issues/3954)) ([7381d27](https://github.com/vitejs/vite/commit/7381d27564045a05cffbe4229d71d64b5a791042)) +* **ssr:** not importing browser exports, fix [#3772](https://github.com/vitejs/vite/issues/3772) ([#3933](https://github.com/vitejs/vite/issues/3933)) ([f623ba3](https://github.com/vitejs/vite/commit/f623ba37dbc517656a7ffb10bc1b3cb221a4bc72)) +* do not end server process in CI ([#3659](https://github.com/vitejs/vite/issues/3659)) ([5999444](https://github.com/vitejs/vite/commit/5999444496b6309460687b0769afad018aa21859)) +* missing styles with build watch ([#3742](https://github.com/vitejs/vite/issues/3742)) ([#3887](https://github.com/vitejs/vite/issues/3887)) ([c9a6efe](https://github.com/vitejs/vite/commit/c9a6efe17108a899e1d1f4cb490973486223da99)) +* multiple css url separation (fix [#3922](https://github.com/vitejs/vite/issues/3922)) ([#3926](https://github.com/vitejs/vite/issues/3926)) ([2d01e62](https://github.com/vitejs/vite/commit/2d01e62a70e534694ee1d87f4a328e796ae4c8fe)) +* only downgrade target to es2019 when actually using terser ([bd8723e](https://github.com/vitejs/vite/commit/bd8723eb36be368b4a45240e1f0159fbd40a81a4)) + + +### Features + +* add client events to import.meta.hot.on ([#3638](https://github.com/vitejs/vite/issues/3638)) ([de1ddd4](https://github.com/vitejs/vite/commit/de1ddd401802784a74f5106c5173945e760d3f03)) +* fs-serve import graph awareness ([#3784](https://github.com/vitejs/vite/issues/3784)) ([c45a02f](https://github.com/vitejs/vite/commit/c45a02f0279103be922a2d24b8cd05141e0ff165)) +* generate inline sourcemaps for bundled vite.config.js files ([#3949](https://github.com/vitejs/vite/issues/3949)) ([cff2fcd](https://github.com/vitejs/vite/commit/cff2fcd8db98bb1c046816fd2e01dcbffbe86629)) +* support for regex for ssr.noExternal ([#3819](https://github.com/vitejs/vite/issues/3819)) ([330c94c](https://github.com/vitejs/vite/commit/330c94c4355e4f091e6e4f46c6a47dbfba410e40)) +* support new URL(url, import.meta.url) usage ([4cbb40d](https://github.com/vitejs/vite/commit/4cbb40d2f1a4050c9944e7e1d9e0f5b204b7e37b)) + + + +## [2.3.8](https://github.com/vitejs/vite/compare/v2.3.7...v2.3.8) (2021-06-19) + + +### Bug Fixes + +* **css:** filter out function name suffixes with url ([#3752](https://github.com/vitejs/vite/issues/3752)) ([9aa255a](https://github.com/vitejs/vite/commit/9aa255a0abcb9f5b23c34607b2188f796f4b6c94)) +* **deps:** update all non-major dependencies ([#3791](https://github.com/vitejs/vite/issues/3791)) ([74d409e](https://github.com/vitejs/vite/commit/74d409eafca8d74ec4a6ece621ea2895bc1f2a32)) +* **hmr:** always invalidate all affected modules ([e048114](https://github.com/vitejs/vite/commit/e048114d3657fc8e2fec645eba3f5f2fe230ceb7)) +* **hmr:** avoid css propagation infinite loop ([7362e6e](https://github.com/vitejs/vite/commit/7362e6e9a7a0f0177b467f1cf80552acf22c46a0)) +* **hmr:** avoid duplicated modules for css dependency ([385ced9](https://github.com/vitejs/vite/commit/385ced9c2e9b5f06e9c06669fe19a0a98cc82c8b)) +* **hmr/css:** check CSS importers for hmr boundaries - fix Tailwind 2.2 compat ([6eaec3a](https://github.com/vitejs/vite/commit/6eaec3ab74d126310d93f8a93f8577bed1c3f474)) +* **hmr/css:** fix infinite recursion on hmr ([#3865](https://github.com/vitejs/vite/issues/3865)) ([0d5726f](https://github.com/vitejs/vite/commit/0d5726fff2fe724ffec3c0621e3dcd6775b0fe8b)) +* ?import with trailing = added by some servers ([#3805](https://github.com/vitejs/vite/issues/3805)) ([460d1cd](https://github.com/vitejs/vite/commit/460d1cda317e4c4d03434f2b3d8de9152620005b)) +* don't replace `process.env` if `process` not global variable ([#3703](https://github.com/vitejs/vite/issues/3703)) ([5aeadb7](https://github.com/vitejs/vite/commit/5aeadb719944152be7ed9f9472aa2238ea3557c0)) +* upgrade esbuild for esm compatibility ([#3718](https://github.com/vitejs/vite/issues/3718)) ([dbb5eab](https://github.com/vitejs/vite/commit/dbb5eabe246747abab187a6c8d90cd418856e048)), closes [#3399](https://github.com/vitejs/vite/issues/3399) [#3413](https://github.com/vitejs/vite/issues/3413) + + +### Features + +* allow 'hidden' sourcemap to remove //# sourceMappingURL from generated maps ([#3684](https://github.com/vitejs/vite/issues/3684)) ([19e479b](https://github.com/vitejs/vite/commit/19e479ba0dd1da4d1de075bdf11edabe00af6cb6)) + + + +## [2.3.7](https://github.com/vitejs/vite/compare/v2.3.6...v2.3.7) (2021-06-08) + + +### Bug Fixes + +* Include src files in vite npm bundle (for sourcemaps) ([#3656](https://github.com/vitejs/vite/issues/3656)) ([294d8b4](https://github.com/vitejs/vite/commit/294d8b472ca5d5079d8fe35ecb1b0bf6cf7720db)) +* show error message above the stack when HMR overlay is disabled ([#3677](https://github.com/vitejs/vite/issues/3677)) ([6b4c355](https://github.com/vitejs/vite/commit/6b4c3550f673253ca175a1e2ca2efb8d1ec85b3b)) +* tolerant fs error in formatError ([#3665](https://github.com/vitejs/vite/issues/3665)) ([5146cc5](https://github.com/vitejs/vite/commit/5146cc5eb2bfe4317e3a7c8590963cbebaa5b3e9)) +* update `sirv` to decode url in preview ([#3680](https://github.com/vitejs/vite/issues/3680)) ([0430127](https://github.com/vitejs/vite/commit/0430127b7b7216d92a351fcb9c80753563a318e6)) + + +### Features + +* **css:** support postcss dir-dependency message type ([#3707](https://github.com/vitejs/vite/issues/3707)) ([665d438](https://github.com/vitejs/vite/commit/665d43872914c7a79a5a79aa4b6349961e68a10d)) + + + +## [2.3.6](https://github.com/vitejs/vite/compare/v2.3.5...v2.3.6) (2021-06-02) + + +### Bug Fixes + +* revert avoid css leaking into emitted javascript ([#3402](https://github.com/vitejs/vite/issues/3402)) ([#3630](https://github.com/vitejs/vite/issues/3630)) ([91eb2a6](https://github.com/vitejs/vite/commit/91eb2a6bc30103569cce05f6da1acdd72d5f71f0)) +* **types:** add '*?.sharedworker' typing ([#3618](https://github.com/vitejs/vite/issues/3618)) ([690ff99](https://github.com/vitejs/vite/commit/690ff999cdebf390a84506c5b62a17e6e8f47c17)) + + + +## [2.3.5](https://github.com/vitejs/vite/compare/v2.3.4...v2.3.5) (2021-06-01) + + +### Bug Fixes + +* cannot recognize JS url correctly([#3568](https://github.com/vitejs/vite/issues/3568)) ([#3572](https://github.com/vitejs/vite/issues/3572)) ([ab08652](https://github.com/vitejs/vite/commit/ab0865223f2fd8c460ee9b5108dbe67b9ad534a1)) +* **tests:** fix tests run fail in the Chinese directory ([#3586](https://github.com/vitejs/vite/issues/3586)) ([3cab2c2](https://github.com/vitejs/vite/commit/3cab2c2202c2c7188b4f76d872c94a9f6acaf122)) +* update esbuild to 0.12 ([#3570](https://github.com/vitejs/vite/issues/3570)) ([421c530](https://github.com/vitejs/vite/commit/421c530eae668f0ddadd9b4ef6d366a58d74febc)) + + +### Features + +* **config:** add `envDir` option ([#3407](https://github.com/vitejs/vite/issues/3407)) ([472ba5d](https://github.com/vitejs/vite/commit/472ba5d7198e5db631ddafc1fd2adf78ce26003e)) +* **plugins/worker:** support SharedWorker (resolve [#2093](https://github.com/vitejs/vite/issues/2093)) ([#2505](https://github.com/vitejs/vite/issues/2505)) ([d78191c](https://github.com/vitejs/vite/commit/d78191c5ce5f9c0e5a2329c7b113fc25b27535b9)) +* **ssr:** include non-CSS assets in the manifest ([#3556](https://github.com/vitejs/vite/issues/3556)) ([adc7170](https://github.com/vitejs/vite/commit/adc7170dac0b08f3cffd49fa4844a6fa871067dc)) +* added clientPort to HmrOptions ([#3578](https://github.com/vitejs/vite/issues/3578)) ([7db69a3](https://github.com/vitejs/vite/commit/7db69a3c284d58ebb51f91c5f44da9890d056b19)) + + + +## [2.3.4](https://github.com/vitejs/vite/compare/v2.3.3...v2.3.4) (2021-05-25) + + +### Bug Fixes + +* allow passing an array as sass / scss importer ([#3529](https://github.com/vitejs/vite/issues/3529)) ([e344cdd](https://github.com/vitejs/vite/commit/e344cdd28425e08b2481b1a6289b820764f25928)) +* avoid css leaking into emitted javascript ([#3402](https://github.com/vitejs/vite/issues/3402)) ([65d333d](https://github.com/vitejs/vite/commit/65d333d8eb95ea3ab3d611d9c21d05de9657f134)) +* clean manifest plugin state at build start ([#3530](https://github.com/vitejs/vite/issues/3530)) ([c9da635](https://github.com/vitejs/vite/commit/c9da635841cc20e65df6a51c3f0b7a7fb79a814f)) +* data-uri plugin cache reset at buildStart ([#3537](https://github.com/vitejs/vite/issues/3537)) ([9d97b6d](https://github.com/vitejs/vite/commit/9d97b6d0084a543b6e692890d8a095e4bee5dfac)) +* do not cache module while the file contains import.meta.glob ([#3005](https://github.com/vitejs/vite/issues/3005)) ([e7b8f41](https://github.com/vitejs/vite/commit/e7b8f41c45ea95cfd12801dfd22fa9be99de8ac8)) +* ensure new assets cache at build start, fix [#3271](https://github.com/vitejs/vite/issues/3271) ([#3512](https://github.com/vitejs/vite/issues/3512)) ([9484c0f](https://github.com/vitejs/vite/commit/9484c0f392407d71efad64b585b8656202c9b411)) +* ensure new CSS modules cache at build start ([#3516](https://github.com/vitejs/vite/issues/3516)) ([07ad2b4](https://github.com/vitejs/vite/commit/07ad2b494b14701f54376afe6ce49bf24a3e7cd9)) +* **preview:** [#3487](https://github.com/vitejs/vite/issues/3487) preview should serve latest content by default ([#3488](https://github.com/vitejs/vite/issues/3488)) ([9a4183d](https://github.com/vitejs/vite/commit/9a4183dbc0d4dcf278ac829b96230b3d2b24bd5e)) +* **preview:** allow to disable HTTPS ([#3514](https://github.com/vitejs/vite/issues/3514)) ([cf1632e](https://github.com/vitejs/vite/commit/cf1632ea525b4e3230afaee908ef42f0e7321fe8)) +* **preview:** support custom hostname ([#3506](https://github.com/vitejs/vite/issues/3506)) ([5979d0e](https://github.com/vitejs/vite/commit/5979d0e3b2c071ee15408aa67974af04f7bb1c3d)) +* **types:** add .module.pcss typings, fix [#3518](https://github.com/vitejs/vite/issues/3518) ([#3519](https://github.com/vitejs/vite/issues/3519)) ([3475351](https://github.com/vitejs/vite/commit/3475351a371df2e17689a99968fdee827b0b2d16)) +* handle HMR for files with more than one glob import ([#3497](https://github.com/vitejs/vite/issues/3497)) ([05bd96e](https://github.com/vitejs/vite/commit/05bd96e21ced682251378c4ad7ae0dee59195eae)) +* inline webworker safari support ([#3468](https://github.com/vitejs/vite/issues/3468)) ([2671546](https://github.com/vitejs/vite/commit/26715465f7430e6fd9a0cf2ae9e49fb099cced3a)) +* invalidate import globs upon new/removed files (fix [#3499](https://github.com/vitejs/vite/issues/3499)) ([#3500](https://github.com/vitejs/vite/issues/3500)) ([b31604e](https://github.com/vitejs/vite/commit/b31604e08c4333bed5a3c4cc6876d1eb337a100b)) +* track deps for css [@import](https://github.com/import) in build watch mode, fix [#3387](https://github.com/vitejs/vite/issues/3387) ([#3478](https://github.com/vitejs/vite/issues/3478)) ([13bda33](https://github.com/vitejs/vite/commit/13bda3368e73ade311f1c113894c2dcb329cef8d)) + + +### Features + +* support serving `index.html` in middleware mode ([#2871](https://github.com/vitejs/vite/issues/2871)) ([b1598ce](https://github.com/vitejs/vite/commit/b1598cec7ee185f796d8679f0a97d36b80fe1949)) + + + +## [2.3.3](https://github.com/vitejs/vite/compare/v2.3.2...v2.3.3) (2021-05-17) + + +### Bug Fixes + +* ignore ids that start with \0 in plugin asset, fix [#3424](https://github.com/vitejs/vite/issues/3424) ([#3436](https://github.com/vitejs/vite/issues/3436)) ([f6cfe30](https://github.com/vitejs/vite/commit/f6cfe30abfc5179262aea807173d7591fd4dc876)) +* restore dynamic-import-polyfill ([#3434](https://github.com/vitejs/vite/issues/3434)) ([4112c5d](https://github.com/vitejs/vite/commit/4112c5d103673b83c50d446096086617dfaac5a3)) +* sass importer can't be undefined (fix: [#3390](https://github.com/vitejs/vite/issues/3390)) ([#3395](https://github.com/vitejs/vite/issues/3395)) ([30ff5a2](https://github.com/vitejs/vite/commit/30ff5a235d2a832cb45a761a03c5947460417b40)) +* skip fs fallback for out of root urls, fix [#3364](https://github.com/vitejs/vite/issues/3364) ([#3431](https://github.com/vitejs/vite/issues/3431)) ([19dae99](https://github.com/vitejs/vite/commit/19dae997f91607424af2d0e159ae2570463bbcb3)) +* warn about dynamic import polyfill only during build ([#3446](https://github.com/vitejs/vite/issues/3446)) ([5fe0550](https://github.com/vitejs/vite/commit/5fe05507dd28bbd863469628bc61b45a04f938bd)) + + + +## [2.3.2](https://github.com/vitejs/vite/compare/v2.3.1...v2.3.2) (2021-05-12) + + +### Bug Fixes + +* **css:** fix sass importer error ([#3368](https://github.com/vitejs/vite/issues/3368)) ([3f04abf](https://github.com/vitejs/vite/commit/3f04abf0ff21c7b2969902c3d8d87f4b1b93740f)) +* **server:** hostname defaults to localhost, fix [#3355](https://github.com/vitejs/vite/issues/3355) ([#3383](https://github.com/vitejs/vite/issues/3383)) ([8b5a6a8](https://github.com/vitejs/vite/commit/8b5a6a855091e6f744cc7b886cf927d14dc74d50)) + + + +## [2.3.1](https://github.com/vitejs/vite/compare/v2.3.0...v2.3.1) (2021-05-12) + +### Notable Changes + +We introduced a security fix in v2.3.0 to restrict file access outside of the workspace root. We received reports of issues with symlinks and monorepo setups, so we are marking this feature as experimental and disabling it by default to avoid disruption in the ecosystem. + +A new experimental option `server.fsServe.strict` was added defaulting to `false`. This **disables the restrictions by default**. The `fsServe` restrictions are going to be enabled by default in a future version, once the issues are been resolved and the logic becomes more robust. You can opt-in to this security change using (experimental) + +```js +// vite.config.js +export default { + server: { + fsServe: { + strict: true + } + } +} +``` + +### Bug Fixes + +* bump @rollup/plugin-commonjs to v19, fix [#3312](https://github.com/vitejs/vite/issues/3312) ([#3353](https://github.com/vitejs/vite/issues/3353)) ([c6ef6d0](https://github.com/vitejs/vite/commit/c6ef6d084c2368f6c73e03cc18bcab05aea9cfa6)) +* disable fsServe restrictions by default ([#3377](https://github.com/vitejs/vite/issues/3377)) ([5433a65](https://github.com/vitejs/vite/commit/5433a655534cd4c716c2eba2f89f20bfa328e812)) +* normalize url in `ensureServingAccess` ([#3350](https://github.com/vitejs/vite/issues/3350)) ([deb465b](https://github.com/vitejs/vite/commit/deb465ba412312ccae2d5b767de327d6f8562e7e)) +* use the closest package.json as root when workspace not found fo… ([#3374](https://github.com/vitejs/vite/issues/3374)) ([42b35ac](https://github.com/vitejs/vite/commit/42b35ac567b02b8142a7a51df320d7deb2ec4ac1)) + + + +# [2.3.0](https://github.com/vitejs/vite/compare/v2.2.4...v2.3.0) (2021-05-11) + +## BREAKING CHANGES + +- Browser default targets changed (PR [#2976](https://github.com/vitejs/vite/pull/2976)) + - Default browser support range has changed. The minimum requirement is now [native dynamic import support](https://caniuse.com/es6-module-dynamic-import). Most notably, this means support for legacy Microsoft Edge (16-18) has been dropped. + - `vite/dynamic-import-polyfill` removed and no longer required in custom entries + +### Why are there breaking changes in a minor? + +- **Limited impact:** The affected target browsers are ones that natively support [ES6 modules](https://caniuse.com/es6-module) (92.83% of global usage) but do not support [native dynamic imports](https://caniuse.com/es6-module-dynamic-import) (92.34% of global usage). So this is a small range affecting only 0.49% of global usage. + + This number should continue to decrease in the future as most modern browsers are evergreen. You are also not affected if you are already targeting legacy browsers using `@vitejs/plugin-legacy`. + +- **Easy migration:** if you do intend to support browsers that fall into this category, you can use [dynamic-import-polyfill](https://github.com/GoogleChromeLabs/dynamic-import-polyfill). + + To make the polyfill work, you will also need to use a plugin with [`renderDynamicImport`](https://rollupjs.org/guide/en/#renderdynamicimport) to change the import calls to `__import__`. You can follow the installation guide in [this example](https://github.com/antfu/vite-dynamic-import-polyfill-example). + +- **Required for bug fixes:** This change is required for upgrading esbuild from v0.9 to [v0.11](https://github.com/evanw/esbuild/releases/tag/v0.11.0), which includes a lot of bug fixes and improvements. And it also allows us to remove the complexity of the dynamic import polyfill. + +## Security Fixes + +- Dev server only listens to localhost by default now (PR [#2977](https://github.com/vitejs/vite/pull/2977)) + - Pass `--host 0.0.0.0` to change back to the previous behavior. +- Dev server only serves files under workspace root by defualt (PR [#2850](https://github.com/vitejs/vite/pull/2850), [#3321](https://github.com/vitejs/vite/pull/3321)) + - Accessing files outside of workspace root will result in a 403 response. + - Vite will try to search up for workspace root defined in `package.json` or `pnpm-workspace.yaml` + - To set the workspace root explicitly, see [configurations](https://vitejs.dev/config/#server-fsserve-root) + +### Bug Fixes + +* **dev:** rewrite importee path at html files at spa fallback ([#3239](https://github.com/vitejs/vite/issues/3239)) ([13d41d8](https://github.com/vitejs/vite/commit/13d41d864219bcc0e952f42f69adb97147e15520)) +* **hmr:** respect server https options when running as middleware ([#1992](https://github.com/vitejs/vite/issues/1992)) ([24178b0](https://github.com/vitejs/vite/commit/24178b05825245b9f36b5a8e4730996184cc7e8e)) +* **serve:** prevent serving unrestricted files ([#3321](https://github.com/vitejs/vite/issues/3321)) ([7231b5a](https://github.com/vitejs/vite/commit/7231b5a882a2db8dd2d9cb88a0f446edb5e2cf43)) +* only provide npm package names to resolveSSRExternal ([#2717](https://github.com/vitejs/vite/issues/2717)) ([6dde32a](https://github.com/vitejs/vite/commit/6dde32a1641e91470da73315272f14e62369b65b)) +* prevent serving unrestricted files (fix [#2820](https://github.com/vitejs/vite/issues/2820)) ([#2850](https://github.com/vitejs/vite/issues/2850)) ([792a6e1](https://github.com/vitejs/vite/commit/792a6e1ee8fa288ce8e641f7fa378fe8d76e52d4)) +* type error by [#3151](https://github.com/vitejs/vite/issues/3151) ([#3292](https://github.com/vitejs/vite/issues/3292)) ([fd4146b](https://github.com/vitejs/vite/commit/fd4146b8624100a609ae43b2d73681d260dfe131)) +* upgrade to esbuild@0.11.19 ([#3282](https://github.com/vitejs/vite/issues/3282)) ([b0dd69d](https://github.com/vitejs/vite/commit/b0dd69d305c268b2ea326ec4f344da7f7b989e69)) +* warning for vite/dynamic-import-polyfill ([#3328](https://github.com/vitejs/vite/issues/3328)) ([8b80512](https://github.com/vitejs/vite/commit/8b80512c03bc053e101b1047bfd142260a15e2ac)) +* **ci:** fix ci lint step ([#2988](https://github.com/vitejs/vite/issues/2988)) ([4e8ffd8](https://github.com/vitejs/vite/commit/4e8ffd8865e6303d19b5a5ea4501fc54bff4e180)) +* **resolve:** normalize node_modules and bare imports, fix [#2503](https://github.com/vitejs/vite/issues/2503) ([#2848](https://github.com/vitejs/vite/issues/2848)) ([0c97412](https://github.com/vitejs/vite/commit/0c9741222532b9fa7818e0a2ce9c918bda03c6a0)) +* **server:** Listen only to 127.0.0.1 by default ([#2977](https://github.com/vitejs/vite/issues/2977)) ([1e604d5](https://github.com/vitejs/vite/commit/1e604d5b60900098f201f90394445fea55642e74)) +* **ssr:** resolve dynamic import vars modules ([#3177](https://github.com/vitejs/vite/issues/3177)) ([b1e7395](https://github.com/vitejs/vite/commit/b1e73951ed402a64882fb771bf433938ad171e19)) + + +### Features + +* add optimizeDeps.esbuildOptions ([#2991](https://github.com/vitejs/vite/issues/2991)) ([77a882a](https://github.com/vitejs/vite/commit/77a882a385147957b3100b3ec21de7cb212887bf)) +* set publicDir to false to disable copied static assets to build dist dir ([#3152](https://github.com/vitejs/vite/issues/3152)) ([f4ab90a](https://github.com/vitejs/vite/commit/f4ab90a79f3ff56647631fa8891dc665081b45a2)) +* webworker ssr target ([#3151](https://github.com/vitejs/vite/issues/3151)) ([1c59ef1](https://github.com/vitejs/vite/commit/1c59ef14dec3b60c67e70800af9d88a2255a54ae)) + + + +## [2.2.4](https://github.com/vitejs/vite/compare/v2.2.3...v2.2.4) (2021-05-03) + + +### Bug Fixes + +* **dev:** strip utf-8 bom ([#3162](https://github.com/vitejs/vite/issues/3162)) ([#3171](https://github.com/vitejs/vite/issues/3171)) ([19a2869](https://github.com/vitejs/vite/commit/19a28692209564202ce7303a5664696cfbf3ef28)) +* call `buildStart` hook in middleware mode ([#3080](https://github.com/vitejs/vite/issues/3080)) ([c374a54](https://github.com/vitejs/vite/commit/c374a5405050a6ed9013082027774fa275c2d324)) +* **scan:** improve script regular matching (fixes [#2942](https://github.com/vitejs/vite/issues/2942)) ([#2961](https://github.com/vitejs/vite/issues/2961)) ([1e785d1](https://github.com/vitejs/vite/commit/1e785d1af54ae5e305dd1bef9af513f2c3a91ad3)) +* dependencies are analyzed multiple times ([#3154](https://github.com/vitejs/vite/issues/3154)) ([28a67ad](https://github.com/vitejs/vite/commit/28a67ad023fd7e43e3024d1a698c49a0f7156b59)) +* **emptyOutDir:** never remove .git ([#3043](https://github.com/vitejs/vite/issues/3043)) ([82dc588](https://github.com/vitejs/vite/commit/82dc5880c97daca2b7b8d55c27c30a6d810849a1)) + + +### Features + +* Allow overwrite `TerserOptions.safari10` from `UserConfig` ([#3113](https://github.com/vitejs/vite/issues/3113)) ([7cd8d78](https://github.com/vitejs/vite/commit/7cd8d7832e12e2facf7dfc163320a8798e19c6fd)) + + + +## [2.2.3](https://github.com/vitejs/vite/compare/v2.2.2...v2.2.3) (2021-04-25) + + +### Bug Fixes + +* revert [#2541](https://github.com/vitejs/vite/issues/2541), fix [#3084](https://github.com/vitejs/vite/issues/3084) [#3101](https://github.com/vitejs/vite/issues/3101) ([#3144](https://github.com/vitejs/vite/issues/3144)) ([f4e7918](https://github.com/vitejs/vite/commit/f4e7918d0784d4f20f7f9a5575cd7e4a9cfd69fb)) +* **build:** vendor chunk strategy uses static imports, fix [#2672](https://github.com/vitejs/vite/issues/2672) ([#2934](https://github.com/vitejs/vite/issues/2934)) ([949b818](https://github.com/vitejs/vite/commit/949b8184310ac073faf7f5271301ad0d9a884487)) +* add .svelte to list of known js src files ([#3128](https://github.com/vitejs/vite/issues/3128)) ([0f09eaf](https://github.com/vitejs/vite/commit/0f09eaff374065a866c0f23db1217704eeb637a6)) +* await bundle close in worker plugin ([#2997](https://github.com/vitejs/vite/issues/2997)) ([0e7125a](https://github.com/vitejs/vite/commit/0e7125a0480d2a50cd1d88c7a8d046af75be3a75)) +* dymamic import polyfill path when base is a URL ([#3132](https://github.com/vitejs/vite/issues/3132)) ([02ba4ba](https://github.com/vitejs/vite/commit/02ba4ba32cd40f1cc3943781022c05f9df3b57e6)) +* handle null/empty sources in source maps ([#3074](https://github.com/vitejs/vite/issues/3074)) ([3e9f128](https://github.com/vitejs/vite/commit/3e9f128d15f154a2e140fa65c5f617824f0c4916)) +* support postcss .pcss extension ([#3130](https://github.com/vitejs/vite/issues/3130)) ([6d602a0](https://github.com/vitejs/vite/commit/6d602a0a4d2c1e77ded1344d59733eb93d4009c3)) + + + +## [2.2.2](https://github.com/vitejs/vite/compare/v2.2.1...v2.2.2) (2021-04-24) + + +### Bug Fixes + +* **ssr:** skip resolving browser field for SSR build, fix [#3036](https://github.com/vitejs/vite/issues/3036) ([#3039](https://github.com/vitejs/vite/issues/3039)) ([61ea320](https://github.com/vitejs/vite/commit/61ea32056048e902ca69d88e1b0a2d21660dae2a)) + + +### Features + +* add marko file extensions ([#3073](https://github.com/vitejs/vite/issues/3073)) ([d34fd88](https://github.com/vitejs/vite/commit/d34fd88e46cdcbbfbc266f431f47af285b1e8702)) + + + +## [2.2.1](https://github.com/vitejs/vite/compare/v2.2.0...v2.2.1) (2021-04-19) + + +### Bug Fixes + +* **optimizer:** depScan resolve with flatIdDeps ([#3053](https://github.com/vitejs/vite/issues/3053)) ([cb441ef](https://github.com/vitejs/vite/commit/cb441ef0f5c4a21117ea42d3fcee110a62371196)) + + + +# [2.2.0](https://github.com/vitejs/vite/compare/v2.1.5...v2.2.0) (2021-04-19) + + +### Bug Fixes + +* require.resolve to correct sub node_modules ([#3003](https://github.com/vitejs/vite/issues/3003)) ([da11d43](https://github.com/vitejs/vite/commit/da11d43d9a246b0e721d6c33cd6a47a0675843cf)) +* **optimizer:** ensure consistency with replace define ([#2929](https://github.com/vitejs/vite/issues/2929)) ([ddb7a91](https://github.com/vitejs/vite/commit/ddb7a91f0085f832d438f9523397c8a55f3d0764)), closes [#2893](https://github.com/vitejs/vite/issues/2893) +* A static and dynamically imported module is loaded twice ([#2935](https://github.com/vitejs/vite/issues/2935)) ([266fb55](https://github.com/vitejs/vite/commit/266fb55adc1e3580bab86d30fcd1dfd1d80748a9)) +* avoid endless loop in resolveSSRExternal (fix [#2635](https://github.com/vitejs/vite/issues/2635)) ([#2636](https://github.com/vitejs/vite/issues/2636)) ([59871ef](https://github.com/vitejs/vite/commit/59871ef16142412d78ec79fe5ed06390d86c49e6)) +* don't resolve import using browser during SSR (fix [#2995](https://github.com/vitejs/vite/issues/2995)) ([#2996](https://github.com/vitejs/vite/issues/2996)) ([fd1c9ba](https://github.com/vitejs/vite/commit/fd1c9ba11bff634c10e23a9cad2e5d639145ccf6)) +* filter out empty srcset, fix [#2863](https://github.com/vitejs/vite/issues/2863) ([#2888](https://github.com/vitejs/vite/issues/2888)) ([0d4f803](https://github.com/vitejs/vite/commit/0d4f803d6edc51f31a5e20a161aa77688823b689)) +* **build:** avoid import duplicate chunks, fix [#2906](https://github.com/vitejs/vite/issues/2906) ([#2940](https://github.com/vitejs/vite/issues/2940)) ([8b02abf](https://github.com/vitejs/vite/commit/8b02abf537cb731fcfe84cf8e93ba3e923e83114)) +* **build:** properly handle alias key in config merge ([#2847](https://github.com/vitejs/vite/issues/2847)) ([41261c7](https://github.com/vitejs/vite/commit/41261c70e6d65ddf1dca52a6e94e5aa555539581)) +* **build:** support `cssCodeSplit` for cjs format, fix [#2575](https://github.com/vitejs/vite/issues/2575) ([#2621](https://github.com/vitejs/vite/issues/2621)) ([2a89c57](https://github.com/vitejs/vite/commit/2a89c57d3fb2dedbe595c4d49c454f3d138e6414)) +* **css:** properly pass options to stylus compiler, fix [#2587](https://github.com/vitejs/vite/issues/2587) ([#2860](https://github.com/vitejs/vite/issues/2860)) ([8dbebee](https://github.com/vitejs/vite/commit/8dbebeed4c1dd13e13aa7201ad6922d4d4c20368)) +* **define:** ensure the normal use of NODE_ENV, fix [#2759](https://github.com/vitejs/vite/issues/2759) ([#2764](https://github.com/vitejs/vite/issues/2764)) ([fa85749](https://github.com/vitejs/vite/commit/fa8574921195dd03b539c150a2ae5f97121a0aea)) +* **scan:** avoid crawling type only import ([#2810](https://github.com/vitejs/vite/issues/2810)) ([daf7838](https://github.com/vitejs/vite/commit/daf783866b744c09e2b10234ced853c6f9a84dff)) +* **ssr:** fix ssrTransform catch clause error (fix [#2667](https://github.com/vitejs/vite/issues/2667)) ([#2966](https://github.com/vitejs/vite/issues/2966)) ([c9e0bcf](https://github.com/vitejs/vite/commit/c9e0bcf5653c31ffa00819083a9ce58a24e0bd17)) +* **types:** clean-css types ([#2971](https://github.com/vitejs/vite/issues/2971)) ([9be7449](https://github.com/vitejs/vite/commit/9be7449544b078d572b93e7df463a0c4756a84f5)) +* chunks are analysed multiple times ([#2541](https://github.com/vitejs/vite/issues/2541)) ([1451b78](https://github.com/vitejs/vite/commit/1451b78e7b1a34b89e2768315832087c686fb5aa)) +* serve .js, .jsx, .ts, .tsx as application/javascript, fix [#2642](https://github.com/vitejs/vite/issues/2642) ([#2769](https://github.com/vitejs/vite/issues/2769)) ([b08e973](https://github.com/vitejs/vite/commit/b08e973da0477481970cdf6d49532bb6129aaa24)) + + +### Features + +* **createLogger:** allow custom prefix for logger ([#2019](https://github.com/vitejs/vite/issues/2019)) ([344d77e](https://github.com/vitejs/vite/commit/344d77e9735bc907b9383ad729afb0a8daa2af5f)) +* add async support for vite config file ([#2758](https://github.com/vitejs/vite/issues/2758)) ([aee8b37](https://github.com/vitejs/vite/commit/aee8b3770cd081632fefb327b38ab704b97aa860)) +* add inlineConfig.envFile option ([#2475](https://github.com/vitejs/vite/issues/2475)) ([81b80c6](https://github.com/vitejs/vite/commit/81b80c69d6bb00f54aae0481ea78f869db35725d)) +* export manifest types ([#2901](https://github.com/vitejs/vite/issues/2901)) ([ffcb7ce](https://github.com/vitejs/vite/commit/ffcb7ce0ac4fe61fbd02da05090d48835a0dd1e4)) +* parameter settings when packaging the library ([#2750](https://github.com/vitejs/vite/issues/2750)) ([f17e19a](https://github.com/vitejs/vite/commit/f17e19a80ced16401d00fef266493dd11fc69f2f)) +* support cacheDir ([#2899](https://github.com/vitejs/vite/issues/2899)) ([57980d2](https://github.com/vitejs/vite/commit/57980d27ee10f1f92e532a0975d4ab39ce27d3ed)) +* watch the dependencies of config file ([#3031](https://github.com/vitejs/vite/issues/3031)) ([bb419cb](https://github.com/vitejs/vite/commit/bb419cb969fec2a752dc45ab43b34351fe771f3a)) +* **cli:** build watch mode, fix [#1434](https://github.com/vitejs/vite/issues/1434) ([#1449](https://github.com/vitejs/vite/issues/1449)) ([0dc6e37](https://github.com/vitejs/vite/commit/0dc6e37298e2e3efda74a1042f37bd70e3f5d3a5)) +* **plugin:** plugin config hook supports return promise ([#2800](https://github.com/vitejs/vite/issues/2800)) ([5dfd0e8](https://github.com/vitejs/vite/commit/5dfd0e85978f77c8d12f7b83f25a383ae9c2f7e9)) +* **plugin-api:** support async configResolved hooks (fixes [#2949](https://github.com/vitejs/vite/issues/2949)) ([#2951](https://github.com/vitejs/vite/issues/2951)) ([8b38168](https://github.com/vitejs/vite/commit/8b38168f7bc5be1d3417f3115ac723baec736ed6)) +* support globbing from dependencies ([#2519](https://github.com/vitejs/vite/issues/2519)) ([7121553](https://github.com/vitejs/vite/commit/71215533ac60e8ff566dc3467feabfc2c71a01e2)), closes [#2390](https://github.com/vitejs/vite/issues/2390) + + + +## [2.1.5](https://github.com/vitejs/vite/compare/v2.1.4...v2.1.5) (2021-03-31) + + +### Bug Fixes + +* do not inject ?import query to external urls ([be3a4f5](https://github.com/vitejs/vite/commit/be3a4f5beb39a83bb62aef19f9e18177047618fa)) +* replace __dirname and __filename in config file, fix [#2728](https://github.com/vitejs/vite/issues/2728) ([#2780](https://github.com/vitejs/vite/issues/2780)) ([eb57ac6](https://github.com/vitejs/vite/commit/eb57ac6ab1aa1256cadcea2bf8d31881023a568c)) + + + +## [2.1.4](https://github.com/vitejs/vite/compare/v2.1.3...v2.1.4) (2021-03-30) + + +### Bug Fixes + +* **scan:** properly crawl imports in lang=ts blocks in vue/svelte files ([8f527fd](https://github.com/vitejs/vite/commit/8f527fd09c494fd23121aded0b836ff60a62835c)) +* invalidate module cache on unlinked ([#2629](https://github.com/vitejs/vite/issues/2629)), fix [#2630](https://github.com/vitejs/vite/issues/2630) ([57f2a69](https://github.com/vitejs/vite/commit/57f2a698dcce47e11510bbff4c4716aac49a202b)) +* reload only once on socket reconnect ([#2340](https://github.com/vitejs/vite/issues/2340)) ([d73c1fa](https://github.com/vitejs/vite/commit/d73c1fa6824397515adaf42ec29732013c8c54de)) +* **client:** don't inject queries for data URLs ([#2703](https://github.com/vitejs/vite/issues/2703)), fix [#2658](https://github.com/vitejs/vite/issues/2658) ([86753d6](https://github.com/vitejs/vite/commit/86753d6e3d2be88f2f885c27fef8245c5d4b3b1b)) +* **resolve:** fix resolver not following node resolve algorithm ([#2718](https://github.com/vitejs/vite/issues/2718)), fix [#2695](https://github.com/vitejs/vite/issues/2695) ([669c591](https://github.com/vitejs/vite/commit/669c591696788df844e7b26e600df86ffc70792c)) +* **resolve:** improve browser filed substitutions ([#2701](https://github.com/vitejs/vite/issues/2701)), fix [#2598](https://github.com/vitejs/vite/issues/2598) ([cc213c6](https://github.com/vitejs/vite/commit/cc213c68d54db338ce0e6cf8fafe1b05a414fa6a)) +* fix types errors ([#2726](https://github.com/vitejs/vite/issues/2726)) ([9716582](https://github.com/vitejs/vite/commit/97165828ecbcea867e927c62033002359d83a0db)) + + +### Features + +* **dev:** support keepNames option for optimizeDependencies config ([#2742](https://github.com/vitejs/vite/issues/2742)) ([130bf5a](https://github.com/vitejs/vite/commit/130bf5a03af2733dff9a34ef74450740d7cdb991)) + + + +## [2.1.3](https://github.com/vitejs/vite/compare/v2.1.2...v2.1.3) (2021-03-25) + + +### Bug Fixes + +* add a timeout to the res.sep when discovering dependencies, fix [#2525](https://github.com/vitejs/vite/issues/2525) ([#2548](https://github.com/vitejs/vite/issues/2548)) ([31d10cb](https://github.com/vitejs/vite/commit/31d10cbacf292cbd1064f847673281745c977b0d)) +* handle paths with special characters in injectQuery (fix [#2585](https://github.com/vitejs/vite/issues/2585)) ([#2614](https://github.com/vitejs/vite/issues/2614)) ([ed321ba](https://github.com/vitejs/vite/commit/ed321ba3f3364c0d93097d0ecfeb22aee3daa909)) +* **css:** alias for background url in sass/less link error (fix [#2316](https://github.com/vitejs/vite/issues/2316)) ([#2323](https://github.com/vitejs/vite/issues/2323)) ([9499d26](https://github.com/vitejs/vite/commit/9499d26ead3214cebeab43cfb6f91adad69ae2a9)) +* **dev:** remove process listeners on server close ([#2619](https://github.com/vitejs/vite/issues/2619)) ([74b360b](https://github.com/vitejs/vite/commit/74b360b6c53149c04ab5472aac7e327793a8a493)) +* json should be bundled ([#2573](https://github.com/vitejs/vite/issues/2573)) ([2eb7682](https://github.com/vitejs/vite/commit/2eb76827a364f015727da521e55ec5fa54202a71)), closes [#2543](https://github.com/vitejs/vite/issues/2543) + + +### Features + +* let `plugins` array contain falsy values ([#1649](https://github.com/vitejs/vite/issues/1649)) ([be76a30](https://github.com/vitejs/vite/commit/be76a304aacb52ac5e333552d30024be34a8a6a9)) + + + +## [2.1.2](https://github.com/vitejs/vite/compare/v2.1.1...v2.1.2) (2021-03-17) + + +### Bug Fixes + +* update esbuild target to allow destructuring ([#2566](https://github.com/vitejs/vite/issues/2566)) ([da49782](https://github.com/vitejs/vite/commit/da497823e249aaf4d3a7da80e2211501f6159e1e)) +* **manifest:** do not fail when using rollupOtions.external ([#2532](https://github.com/vitejs/vite/issues/2532)) ([e44cc11](https://github.com/vitejs/vite/commit/e44cc11bcf265d0bc4eaf5679c3b84d4b31d10ad)) + + + +## [2.1.1](https://github.com/vitejs/vite/compare/v2.1.0...v2.1.1) (2021-03-16) + + +### Bug Fixes + +* decode path before reading sourcemap source content ([73b80d5](https://github.com/vitejs/vite/commit/73b80d5da99bbf35afe95c588d30c5b38655e225)), closes [#2524](https://github.com/vitejs/vite/issues/2524) +* **scan:** handle await replacement edge case ([cbfc3e9](https://github.com/vitejs/vite/commit/cbfc3e9dbabc4b4863a7f659b59d2e5115a81481)), closes [#2528](https://github.com/vitejs/vite/issues/2528) +* enable latest syntax when parsing for ssr ([407ce3b](https://github.com/vitejs/vite/commit/407ce3b7c5c07a51b5e20e97bc2fff2f173c74c0)), closes [#2526](https://github.com/vitejs/vite/issues/2526) + + + +# [2.1.0](https://github.com/vitejs/vite/compare/v2.0.5...v2.1.0) (2021-03-15) + + +### Bug Fixes + +* **json:** support importing json with ?url and ?raw queries ([fd0a0d9](https://github.com/vitejs/vite/commit/fd0a0d9bcaf0fd9098c5eb1a0c53226575fdcccb)), closes [#2455](https://github.com/vitejs/vite/issues/2455) +* **ssr:** fix mistakenly overwriting destructure variables as import bindings ([#2417](https://github.com/vitejs/vite/issues/2417)) ([24c866f](https://github.com/vitejs/vite/commit/24c866f0de4fddec45fd6aa757185d5e74d0e7f3)), closes [#2409](https://github.com/vitejs/vite/issues/2409) +* correctly handle explicit ts config file ([#2515](https://github.com/vitejs/vite/issues/2515)) ([e8f3c78](https://github.com/vitejs/vite/commit/e8f3c784b338a87a274dce44c73230d621cecb62)) +* **hmr:** never invalidate an accepting importer ([#2457](https://github.com/vitejs/vite/issues/2457)) ([63bd250](https://github.com/vitejs/vite/commit/63bd2502781b87a2c04a375d9e7b770f63d8857c)) +* **ssr:** handle empty sourcemaps (fix [#2391](https://github.com/vitejs/vite/issues/2391)) ([#2441](https://github.com/vitejs/vite/issues/2441)) ([103dec9](https://github.com/vitejs/vite/commit/103dec9fe80c333e1e8daec53fb08ab597f1120b)) +* fix early logger definiton in resolveConfig ([#2425](https://github.com/vitejs/vite/issues/2425)) ([96ea9f4](https://github.com/vitejs/vite/commit/96ea9f4ad4522548248a951ed0cded46413b6193)) +* Improve how [@fs](https://github.com/fs) urls are printed ([#2362](https://github.com/vitejs/vite/issues/2362)) ([5d4e82d](https://github.com/vitejs/vite/commit/5d4e82d90238b0d52ded1eea6359947eefc5e054)) +* Improve injectQuery path handling ([#2435](https://github.com/vitejs/vite/issues/2435)) ([a5412f8](https://github.com/vitejs/vite/commit/a5412f86be80fa55cf41ac286b0a9675098c6ab8)), closes [#2422](https://github.com/vitejs/vite/issues/2422) +* keep process running when fail to load config in restarting server ([#2510](https://github.com/vitejs/vite/issues/2510)) ([b18af15](https://github.com/vitejs/vite/commit/b18af15fe83d1fcea7800fab9b550018476f740f)), closes [#2496](https://github.com/vitejs/vite/issues/2496) +* make import resolution failures easier to track down ([#2450](https://github.com/vitejs/vite/issues/2450)) ([f6ac860](https://github.com/vitejs/vite/commit/f6ac8600d944a5ce92df92c0cbef162a165c6b94)) +* respect cors and proxy options in preview command ([f7d85ae](https://github.com/vitejs/vite/commit/f7d85ae4c25e7f9481261d691696554113c2d58b)), closes [#2279](https://github.com/vitejs/vite/issues/2279) +* url linked to wmr rollup-plugin-container.js found 404 ([#2368](https://github.com/vitejs/vite/issues/2368)) ([209232c](https://github.com/vitejs/vite/commit/209232cc0417f46ea73458650efa5bf6d9306e65)) +* **build:** respect rollupOtions.external at generate manifest([#2353](https://github.com/vitejs/vite/issues/2353)) ([b05a567](https://github.com/vitejs/vite/commit/b05a5676eb4c46852c0833cc5ff264533d8053ef)) + + +### Features + +* allow custom websocket server ([#2338](https://github.com/vitejs/vite/issues/2338)) ([9243cc9](https://github.com/vitejs/vite/commit/9243cc9e8ea6271eb5d548ff459eb7cc5f260598)) +* bundle vite config file with esbuild instead of rollup ([#2517](https://github.com/vitejs/vite/issues/2517)) ([e034ee2](https://github.com/vitejs/vite/commit/e034ee2d9c7ef1497d1c9248ef05cdd8e0efb6ad)) +* **dev:** support keepNames for dependencies ([#2376](https://github.com/vitejs/vite/issues/2376)) ([b5cd8c8](https://github.com/vitejs/vite/commit/b5cd8c8dc33e920a301ef03c097147d841d08200)) + + + +## [2.0.5](https://github.com/vitejs/vite/compare/v2.0.4...v2.0.5) (2021-03-02) + + +### Bug Fixes + +* serving static files from root ([#2309](https://github.com/vitejs/vite/issues/2309)) ([4f942be](https://github.com/vitejs/vite/commit/4f942bef3ee2dc496a3a6854de9ea7b208829ff6)) +* **scan:** handle race condition for tempDir removal ([#2299](https://github.com/vitejs/vite/issues/2299)) ([67e56e4](https://github.com/vitejs/vite/commit/67e56e48dac7875a2916845614bfb970722744a0)) +* await bundle close ([#2313](https://github.com/vitejs/vite/issues/2313)) ([c988574](https://github.com/vitejs/vite/commit/c988574c3253ff133c2395c1d3884945e67641aa)) + + + +## [2.0.4](https://github.com/vitejs/vite/compare/v2.0.3...v2.0.4) (2021-02-26) + + +### Bug Fixes + +* **build:** css tags injection priority ([#2272](https://github.com/vitejs/vite/issues/2272)) ([55ad23e](https://github.com/vitejs/vite/commit/55ad23ed44af35cb34c81881bdb12bff844c913e)) +* **css:** ignore css commonjs-proxy modules ([#2160](https://github.com/vitejs/vite/issues/2160)) ([de33d32](https://github.com/vitejs/vite/commit/de33d3233708088a94217045069b4a1d9d38d1a7)) +* **optimizer:** detect re-exports in dep entries ([a3abf99](https://github.com/vitejs/vite/commit/a3abf99a19e117fc71e6ea8596c6cda68a6a85ad)), closes [#2219](https://github.com/vitejs/vite/issues/2219) +* **sourcemap:** avoid cjs import interop line offset messing up sourcemap ([4ce972d](https://github.com/vitejs/vite/commit/4ce972df23dfe68543bd960ecf95091a6ffc4fdb)), closes [#2280](https://github.com/vitejs/vite/issues/2280) +* **sourcemap:** inject `sourcesContent` for .map requests ([#2283](https://github.com/vitejs/vite/issues/2283)) ([8d50b18](https://github.com/vitejs/vite/commit/8d50b18f64e3a342b2f1c4f79f306f0fb2b86f69)) +* **ssr:** allow ssr module export overwrites ([#2228](https://github.com/vitejs/vite/issues/2228)) ([6fae0b7](https://github.com/vitejs/vite/commit/6fae0b7d119cf97904ae276176f8bb4374aee300)) +* add source and sourcesContent to transformed SSR modules ([#2285](https://github.com/vitejs/vite/issues/2285)) ([72be67b](https://github.com/vitejs/vite/commit/72be67b70867fbbb2df63ce5484f56e6c95e2759)), closes [#2284](https://github.com/vitejs/vite/issues/2284) +* **optimizer:** fix deps aliased to cdns that are imported by optimized deps ([06d3244](https://github.com/vitejs/vite/commit/06d32447b465c045604d9f111d6fa46a98f7a7ea)), closes [#2268](https://github.com/vitejs/vite/issues/2268) +* **ssr:** handle imported binding being used as super class ([167a9c3](https://github.com/vitejs/vite/commit/167a9c31b9709f3c9627149fa5b6da378f8e09ad)), closes [#2221](https://github.com/vitejs/vite/issues/2221) +* **ssr:** handle ssrLoadModule failures in post pending ([#2253](https://github.com/vitejs/vite/issues/2253)) ([ea323cc](https://github.com/vitejs/vite/commit/ea323ccdfb5a2aef2128dd3ebd09a261d371a897)), closes [#2252](https://github.com/vitejs/vite/issues/2252) +* **ssr:** ssr transform method definition ([#2223](https://github.com/vitejs/vite/issues/2223)) ([8e0c0fa](https://github.com/vitejs/vite/commit/8e0c0fa8db5247fb1be94d5b8d3def2c4bc27923)) +* decode url before serving static files ([#2201](https://github.com/vitejs/vite/issues/2201)) ([1342108](https://github.com/vitejs/vite/commit/1342108a04f7e9068301ecd04a5b391c1ed8e15d)), closes [#2195](https://github.com/vitejs/vite/issues/2195) +* determine anonymous function wrapper offset at runtime ([#2266](https://github.com/vitejs/vite/issues/2266)) ([a2ee885](https://github.com/vitejs/vite/commit/a2ee885e52547703f66367fec589f372d2b9e8a8)), closes [#2265](https://github.com/vitejs/vite/issues/2265) + + + +## [2.0.3](https://github.com/vitejs/vite/compare/v2.0.2...v2.0.3) (2021-02-24) + + +### Bug Fixes + +* **resolve:** compat for babel 7.13 helper resolution ([39820b9](https://github.com/vitejs/vite/commit/39820b96cec2c672e849e160b92b42c979b85285)) +* **ssr:** fix ssr external check for mjs entries ([5095e04](https://github.com/vitejs/vite/commit/5095e041deaced2db8fc3c3af504367bc57bb93f)), closes [#2161](https://github.com/vitejs/vite/issues/2161) +* do not prepend base to double slash urls during dev ([#2143](https://github.com/vitejs/vite/issues/2143)) ([7a1b5c6](https://github.com/vitejs/vite/commit/7a1b5c670e2088a65f9866ecfe1b98f041980683)) +* handle escape sequences in import specifiers ([#2162](https://github.com/vitejs/vite/issues/2162)) ([bbda31e](https://github.com/vitejs/vite/commit/bbda31ef695d3f9b89160435f73fcb948c3b07f1)), closes [#2083](https://github.com/vitejs/vite/issues/2083) +* should transform the img tag's srcset arrtibute and css' image-set property ([#2188](https://github.com/vitejs/vite/issues/2188)) ([0f17a74](https://github.com/vitejs/vite/commit/0f17a74c64a6664c68f23c92d572c22d1a4de059)), closes [#2177](https://github.com/vitejs/vite/issues/2177) +* treat the watcher path as literal name ([#2211](https://github.com/vitejs/vite/issues/2211)) ([58bed16](https://github.com/vitejs/vite/commit/58bed165e996cf8131ba3439ef6d8bf8d33598af)), closes [#2179](https://github.com/vitejs/vite/issues/2179) +* use proper esbuild loader for .cjs and .mjs files ([#2215](https://github.com/vitejs/vite/issues/2215)) ([a0d922e](https://github.com/vitejs/vite/commit/a0d922e7d9790f998c246f8122bc339717b6088f)) +* **optimizer:** let esbuild resolve transitive deps ([0138ef3](https://github.com/vitejs/vite/commit/0138ef3eeec4bda73204ae68d5d068175335f38c)), closes [#2199](https://github.com/vitejs/vite/issues/2199) +* **scan:** avoid replacing await in import specifiers ([94e5b9a](https://github.com/vitejs/vite/commit/94e5b9a06f764d576eeeb7f35cae6bdc03b878be)), closes [#2210](https://github.com/vitejs/vite/issues/2210) + + + +## [2.0.2](https://github.com/vitejs/vite/compare/v2.0.1...v2.0.2) (2021-02-22) + + +### Bug Fixes + +* **build:** do not handle asset url when its url is "#" ([#2097](https://github.com/vitejs/vite/issues/2097)) ([0092a35](https://github.com/vitejs/vite/commit/0092a35632d31590409530639e33fc90274d6488)), closes [#2096](https://github.com/vitejs/vite/issues/2096) +* **cli:** fix short flags being ignored ([#2131](https://github.com/vitejs/vite/issues/2131)) ([cbb3eff](https://github.com/vitejs/vite/commit/cbb3eff96f54ed76c6ed7ca793d50914c96a67da)) +* **optimizer:** do not optimize deps w/ jsx entrypoints ([1857652](https://github.com/vitejs/vite/commit/1857652f6153f1cfd7d171e75d567dd05731c711)), closes [#2107](https://github.com/vitejs/vite/issues/2107) +* **optimizer:** externalize jsx/tsx files in dependencies ([37a103f](https://github.com/vitejs/vite/commit/37a103fd2aadd42b0cda0bdfa81e0624a64b1a09)) +* **optimizer:** fix .styl externalization ([87cfd9e](https://github.com/vitejs/vite/commit/87cfd9e556a0e633694805ae2497a656722d3abb)), closes [#2168](https://github.com/vitejs/vite/issues/2168) +* **resolve:** fix browser mapping fallback ([de58967](https://github.com/vitejs/vite/commit/de58967c570822e7a345bb63b81ca113ed8a8127)), closes [#2115](https://github.com/vitejs/vite/issues/2115) +* **scan:** set namespace when resolving to html ([#2174](https://github.com/vitejs/vite/issues/2174)) ([3be4fac](https://github.com/vitejs/vite/commit/3be4facebd383ea74db6274fc53848fb0149b902)), closes [#2163](https://github.com/vitejs/vite/issues/2163) +* **ssr:** avoid duplicate ssr module instantiation on shared imports ([a763ffd](https://github.com/vitejs/vite/commit/a763ffd5135fbd34bc1bdebe349e80b51884e1d4)), closes [#2060](https://github.com/vitejs/vite/issues/2060) +* **ssr:** fix ssr export * from ([8ed67cf](https://github.com/vitejs/vite/commit/8ed67cf6782bec72f8fbb4237fadfb415f86129d)), closes [#2158](https://github.com/vitejs/vite/issues/2158) +* typo ([#2149](https://github.com/vitejs/vite/issues/2149)) ([2b19e3c](https://github.com/vitejs/vite/commit/2b19e3c2d36f87e84d8bf34982a06f573a56c008)) +* **ssr:** reject ssrLoadModule promises if evaluation fails ([#2079](https://github.com/vitejs/vite/issues/2079)) ([e303c4e](https://github.com/vitejs/vite/commit/e303c4e9395e6770b1f00104f28dee03e37c26ac)), closes [#2078](https://github.com/vitejs/vite/issues/2078) +* stricter html fallback check in transformRequest ([d0eac2f](https://github.com/vitejs/vite/commit/d0eac2fca9bc16caca7b9043b9c614c7044fb9fa)), closes [#2051](https://github.com/vitejs/vite/issues/2051) + + + +## [2.0.1](https://github.com/vitejs/vite/compare/v2.0.0...v2.0.1) (2021-02-17) + + +### Bug Fixes + +* allow custom process.env.VAR defines ([#2055](https://github.com/vitejs/vite/issues/2055)) ([7def49a](https://github.com/vitejs/vite/commit/7def49a49c83539b6a65c895c276fa83f7c89349)) +* do not error on failed load for SPA html requests ([44a30d5](https://github.com/vitejs/vite/commit/44a30d5df8257bed9c59360b9751bf63151880b4)), closes [#2051](https://github.com/vitejs/vite/issues/2051) +* more inclusive config syntax error hanlding for Node 12.x ([27785f7](https://github.com/vitejs/vite/commit/27785f7fcc5b45987b5f0bf308137ddbdd9f79ea)), closes [#2050](https://github.com/vitejs/vite/issues/2050) + + + +# [2.0.0](https://github.com/vitejs/vite/compare/v2.0.0-beta.70...v2.0.0) (2021-02-16) + + +### Bug Fixes + +* **css/assets:** respect alias in css url() paths ([ad50060](https://github.com/vitejs/vite/commit/ad50060ed43c8d84c22a5c60592404a4e1180e2d)), closes [#2043](https://github.com/vitejs/vite/issues/2043) +* **resolve:** handle hash fragment in fs resolve ([34064c8](https://github.com/vitejs/vite/commit/34064c89aba3690667e4f5fedcbc564f6d759153)) +* **scan:** fix top level await handling in script setup ([24ed098](https://github.com/vitejs/vite/commit/24ed098eedf9e90da69c328bb4d2749fec957fb3)), closes [#2044](https://github.com/vitejs/vite/issues/2044) +* **scan:** ignore virtual entries during scan ([6dc2d56](https://github.com/vitejs/vite/commit/6dc2d561cf2d8e0ea5806764314582a6f434c1d6)), closes [#2047](https://github.com/vitejs/vite/issues/2047) +* always transform applicable requests ([#2041](https://github.com/vitejs/vite/issues/2041)) ([4fd61ab](https://github.com/vitejs/vite/commit/4fd61abc05c686088b9f0ece421138311a8428c8)) + + + +# [2.0.0-beta.70](https://github.com/vitejs/vite/compare/v2.0.0-beta.69...v2.0.0-beta.70) (2021-02-15) + + +### Bug Fixes + +* respect host option when listening ([f05ae32](https://github.com/vitejs/vite/commit/f05ae32156211d3bbf82ccfaea6d4f2fc137e609)), closes [#2032](https://github.com/vitejs/vite/issues/2032) +* **css:** resolve pre-processors from project root ([ddfcbce](https://github.com/vitejs/vite/commit/ddfcbce05753da3e525c1bb9bdf449a322e997f4)), closes [#2030](https://github.com/vitejs/vite/issues/2030) +* reject preload promise if link fails to load ([#2027](https://github.com/vitejs/vite/issues/2027)) ([f74d65d](https://github.com/vitejs/vite/commit/f74d65d41d898982839abb13787ed310555c7980)), closes [#2009](https://github.com/vitejs/vite/issues/2009) +* **ssr:** ignore base when normalizing urls for ssr ([26d409b](https://github.com/vitejs/vite/commit/26d409bbfb9bf661a19cc6619242b382f7181d05)), closes [#1995](https://github.com/vitejs/vite/issues/1995) + + +### Code Refactoring + +* make define option perform direct replacement instead ([059070e](https://github.com/vitejs/vite/commit/059070e10aaee27a03ec5fd52e77fa04effe4c8f)) + + +### Features + +* **css:** allow async additionalData function for css pre-processors ([20f609d](https://github.com/vitejs/vite/commit/20f609dcc4f588da89b4f81eb64fb59c16fd7e07)), closes [#2002](https://github.com/vitejs/vite/issues/2002) +* allow `getJSON` option on `css.modules` ([#2025](https://github.com/vitejs/vite/issues/2025)) ([e324e36](https://github.com/vitejs/vite/commit/e324e36e04ba76e2c5203126306f1cb5ac09df8d)) + + +### BREAKING CHANGES + +* `define` option no longer calls `JSON.stringify` on +string values. This means string define values will be now treated as +raw expressions. To define a string constant, explicit quotes are now +required. + + + +# [2.0.0-beta.69](https://github.com/vitejs/vite/compare/v2.0.0-beta.68...v2.0.0-beta.69) (2021-02-11) + + +### Bug Fixes + +* fix out of root static file serving on windows ([4d34a73](https://github.com/vitejs/vite/commit/4d34a7362e57ba8b04e8fee0e0f2f74ce05f13eb)), closes [#1982](https://github.com/vitejs/vite/issues/1982) +* Remove negative count in stdout with 0 rows ([#1983](https://github.com/vitejs/vite/issues/1983)) ([09b13ed](https://github.com/vitejs/vite/commit/09b13eddd98810fef82858bab7997ea895ab3289)), closes [#1981](https://github.com/vitejs/vite/issues/1981) +* **ssr:** handle virtual modules during ssr ([108be94](https://github.com/vitejs/vite/commit/108be949cd814ec8fc6214c6cdfa440c0dfd7e13)), closes [#1980](https://github.com/vitejs/vite/issues/1980) +* prevent crash on malformed URI ([#1977](https://github.com/vitejs/vite/issues/1977)) ([f1b0bc9](https://github.com/vitejs/vite/commit/f1b0bc9b9bf25d206e3db93c242d5a25af0c15d6)) +* user define on import.meta.env should apply during dev ([603d57e](https://github.com/vitejs/vite/commit/603d57ebc61970902ed9a275dd2e74a6c3eabe65)) + + +### Features + +* pass config env to plugin config hook ([19f3503](https://github.com/vitejs/vite/commit/19f35033045582b05c50ecad10bf2b75a0425383)) + + + +# [2.0.0-beta.68](https://github.com/vitejs/vite/compare/v2.0.0-beta.67...v2.0.0-beta.68) (2021-02-11) + + +### Bug Fixes + +* **css/assets:** properly replace multiple css asset urls on the same line ([1d805a6](https://github.com/vitejs/vite/commit/1d805a6beb212f1812b1b13460c910c848ca3772)), closes [#1975](https://github.com/vitejs/vite/issues/1975) +* **scan:** handle lang=jsx in sfcs ([2f9549c](https://github.com/vitejs/vite/commit/2f9549c910b954b0ed4257a7a3a2e0ae6004c701)), closes [#1972](https://github.com/vitejs/vite/issues/1972) +* fix path normalization for windows paths w/ non ascii chars ([03b323d](https://github.com/vitejs/vite/commit/03b323d39cafe2baabef74e6051a9640add82590)), closes [#1384](https://github.com/vitejs/vite/issues/1384) + + +### Features + +* support --open for `vite preview` command ([#1968](https://github.com/vitejs/vite/issues/1968)) ([446b815](https://github.com/vitejs/vite/commit/446b815d8911440f178f7b36aadc9a5a3cf46fe0)) +* **resolve:** expose full resolve options via config ([0318c64](https://github.com/vitejs/vite/commit/0318c64cc3efe970a5cd3ef6624fe3625af06012)), closes [#1951](https://github.com/vitejs/vite/issues/1951) + + +### Performance Improvements + +* ignore node_modules when globbing import.meta.glob ([8b3d0ea](https://github.com/vitejs/vite/commit/8b3d0ea41265870b9b0741bde3a31bde81078277)), closes [#1974](https://github.com/vitejs/vite/issues/1974) + + + +# [2.0.0-beta.67](https://github.com/vitejs/vite/compare/v2.0.0-beta.66...v2.0.0-beta.67) (2021-02-09) + + +### Bug Fixes + +* **html:** avoid duplicate preload link injection ([6e71596](https://github.com/vitejs/vite/commit/6e7159675c55f46bcc030f9c6fd35dee9a92cfca)), closes [#1957](https://github.com/vitejs/vite/issues/1957) +* **ssr:** fix ssr node require for virtual modules ([fa2d7d6](https://github.com/vitejs/vite/commit/fa2d7d66c16c2156354b6888a2f0bd4b47262ca2)) +* do not open browser when restarting server ([#1952](https://github.com/vitejs/vite/issues/1952)) ([9af1517](https://github.com/vitejs/vite/commit/9af1517e47f66bb793447d998cf1a4d2fa3ef758)) + + + +# [2.0.0-beta.66](https://github.com/vitejs/vite/compare/v2.0.0-beta.65...v2.0.0-beta.66) (2021-02-08) + + +### Bug Fixes + +* **import-analysis:** fix literal dynamic id false positive ([6a6508e](https://github.com/vitejs/vite/commit/6a6508edb9b31a4ea8bbc54b841f5227ba2b562a)), closes [#1902](https://github.com/vitejs/vite/issues/1902) +* **resolve:** avoid race condition in resolve skip check ([85f1e7b](https://github.com/vitejs/vite/commit/85f1e7bdcb9d454bd17b96ef98e2dc0cad58776b)), closes [#1937](https://github.com/vitejs/vite/issues/1937) +* **resolve:** pass down resolve skip via context ([9066f27](https://github.com/vitejs/vite/commit/9066f27c591b356107239e9cef36c1cad73864c0)), closes [#1937](https://github.com/vitejs/vite/issues/1937) +* **scan:** only scan supported entry file types ([a93e61d](https://github.com/vitejs/vite/commit/a93e61d02405728278ac905a9539450927dc7364)) +* use dedicated endpoint for hmr reconnect ping ([b433607](https://github.com/vitejs/vite/commit/b433607aca0986c6e1592c3f64adb2ef30689c5e)), closes [#1904](https://github.com/vitejs/vite/issues/1904) +* **ssr:** ssr external should take scannd imports into account ([92934d4](https://github.com/vitejs/vite/commit/92934d4c18329cc51879aca5016a408b467c1fa0)), closes [#1916](https://github.com/vitejs/vite/issues/1916) +* brotli skipped is printed when build.brotliSize is false ([#1912](https://github.com/vitejs/vite/issues/1912)) ([db3c324](https://github.com/vitejs/vite/commit/db3c324134db2bf371700cc4d838a49ac6148045)) + + + +# [2.0.0-beta.65](https://github.com/vitejs/vite/compare/v2.0.0-beta.64...v2.0.0-beta.65) (2021-02-05) + + +### Bug Fixes + +* **build:** ignore html asset urls that do not exist on disk ([02653f0](https://github.com/vitejs/vite/commit/02653f0b93cacd0f1b3464204d24c0d57f407aa0)), closes [#1885](https://github.com/vitejs/vite/issues/1885) +* better dependency non-js type file handling ([1fdc710](https://github.com/vitejs/vite/commit/1fdc710a391b968f85f6a150dc06e51e53742b02)) +* **dev:** check wasClean in onclose event ([#1872](https://github.com/vitejs/vite/issues/1872)) ([5d3107a](https://github.com/vitejs/vite/commit/5d3107a4a787929810fbfaef37bf3002aa0bcc17)) +* **resolve:** prioritize file over dir with same name for resolve ([c741872](https://github.com/vitejs/vite/commit/c741872e6ca975f507ec89581b742a1da19a0cb0)), closes [#1871](https://github.com/vitejs/vite/issues/1871) +* **ssr:** respect user defines for ssr ([3fad3ba](https://github.com/vitejs/vite/commit/3fad3ba861fb56edd22941db645f2d73b02bf7b1)) +* do not include vite in ssr externals ([578c591](https://github.com/vitejs/vite/commit/578c591ffe7b7c1ffa68e711a7df043afe013daa)), closes [#1865](https://github.com/vitejs/vite/issues/1865) + + +### Code Refactoring + +* **css:** use default CSS modules localsConvention settings ([fee7393](https://github.com/vitejs/vite/commit/fee739325fd4dbf7f6d842c205608e39271db513)) + + +### Features + +* **cli:** make --ssr flag value optional ([3c7b652](https://github.com/vitejs/vite/commit/3c7b652f24fdb5e67c5f56db3cea0769bcd9263b)), closes [#1877](https://github.com/vitejs/vite/issues/1877) +* **proxy:** support conditional options for proxy request ([#1888](https://github.com/vitejs/vite/issues/1888)) ([e81a118](https://github.com/vitejs/vite/commit/e81a118735045a40f0ab93c1bedef5b7d674f2f0)) +* support absolute glob patterns ([159cc79](https://github.com/vitejs/vite/commit/159cc799f19482da3626f906cde45accdf780823)), closes [#1875](https://github.com/vitejs/vite/issues/1875) +* support resolving style/sass entries in css [@import](https://github.com/import) ([f90a85c](https://github.com/vitejs/vite/commit/f90a85c2ba8c9ba215fe75c49035a7e38fa81a7d)), closes [#1874](https://github.com/vitejs/vite/issues/1874) + + +### Performance Improvements + +* improve resolve cache ([6a793d3](https://github.com/vitejs/vite/commit/6a793d319cf7adab061b056692c331a9d66fdac5)) + + +### BREAKING CHANGES + +* **css:** CSS modules now defaults to export class names as-is. +To get camelCase exports like before, explictly set +`css.modules.localsConvention` via config. + + + +# [2.0.0-beta.64](https://github.com/vitejs/vite/compare/v2.0.0-beta.63...v2.0.0-beta.64) (2021-02-03) + + +### Bug Fixes + +* **ssr:** do not resolve to optimized deps during ssr ([d021506](https://github.com/vitejs/vite/commit/d0215060e87c9464c97549cdbb008184796d0f8f)), closes [#1860](https://github.com/vitejs/vite/issues/1860) +* **ssr:** fix externalized cjs deps that exports compiled esmodule ([8ec2d6f](https://github.com/vitejs/vite/commit/8ec2d6f77eb04e015156769f4f004a4792077770)) + + + +# [2.0.0-beta.63](https://github.com/vitejs/vite/compare/v2.0.0-beta.62...v2.0.0-beta.63) (2021-02-03) + + +### Bug Fixes + +* **css:** hoist external [@import](https://github.com/import) in concatenated css ([000ee62](https://github.com/vitejs/vite/commit/000ee62ef41e4964d1002ab7862303cec0419c47)), closes [#1845](https://github.com/vitejs/vite/issues/1845) +* **css:** respect sass partial import convention ([cb7b6be](https://github.com/vitejs/vite/commit/cb7b6becd0a566c58aca6cc47ae785ac2c4b4482)) +* **vite:** close server and exit if stdin ends ([#1857](https://github.com/vitejs/vite/issues/1857)) ([b065ede](https://github.com/vitejs/vite/commit/b065ede3cca3bc72d3bb3e6f9cd945d1b36ccb42)) +* consistently use mode for NODE_ENV in deps ([cd13ef0](https://github.com/vitejs/vite/commit/cd13ef009abd23d2676dda470638c81895034a91)) +* do not shim process with actual object ([8ad7ecd](https://github.com/vitejs/vite/commit/8ad7ecd1029bdc0b47e55877db10ac630829c7e5)) +* make ssr external behavior consistent between dev/build ([e089eff](https://github.com/vitejs/vite/commit/e089eff8f8108fa5463e2e42e16244f7edfd5a1e)) +* only close if http server has listened ([94a8042](https://github.com/vitejs/vite/commit/94a804233682581c0f920ed5c0d42aa85ea3f163)), closes [#1855](https://github.com/vitejs/vite/issues/1855) +* **scan:** handle import glob in jsx/tsx files ([24695fe](https://github.com/vitejs/vite/commit/24695fe47727b7b4e3ac85bb389477f673c57c18)) +* **ssr:** improve ssr external heuristics ([928fc33](https://github.com/vitejs/vite/commit/928fc33b6fffb3bb22c2daa4b478ead7715a2c5f)), closes [#1854](https://github.com/vitejs/vite/issues/1854) +* respect config.build.brotliSize in reporter ([1d5437d](https://github.com/vitejs/vite/commit/1d5437d56bb0974c21561c1cdf5ad1588baefea3)) + + +### Features + +* **ssr:** graduate ssr method types ([0fe2634](https://github.com/vitejs/vite/commit/0fe2634756b6311f0489613460eeadc6c8280192)) + + + +# [2.0.0-beta.62](https://github.com/vitejs/vite/compare/v2.0.0-beta.61...v2.0.0-beta.62) (2021-02-02) + + +### Bug Fixes + +* properly cascade asset hash change ([f8e4eeb](https://github.com/vitejs/vite/commit/f8e4eebcc48ad5e98e52d12ce6595da014a43276)) +* **optimizer:** fix cjs interop check on entries with identical ending ([338d17a](https://github.com/vitejs/vite/commit/338d17a197c9835fbce79919b58b8c4e094f4bb9)), closes [#1847](https://github.com/vitejs/vite/issues/1847) +* **scan:** handle tsx lang in SFCs during dep scan ([#1837](https://github.com/vitejs/vite/issues/1837)) ([be9bc3f](https://github.com/vitejs/vite/commit/be9bc3ff6eb72386876af17b61ccabae1ee249db)) + + +### Features + +* **dev:** inject env for webworker ([#1846](https://github.com/vitejs/vite/issues/1846)) ([5735692](https://github.com/vitejs/vite/commit/5735692b571ad193c04f236325df97bca7ef92bc)), closes [#1838](https://github.com/vitejs/vite/issues/1838) +* better build output + options for brotli / chunk size warning ([da1b06f](https://github.com/vitejs/vite/commit/da1b06f3771371b72c8ba68f3428c48ebf2082ad)) + + + +# [2.0.0-beta.61](https://github.com/vitejs/vite/compare/v2.0.0-beta.60...v2.0.0-beta.61) (2021-02-01) + + +### Bug Fixes + +* **less:** fix less [@import](https://github.com/import) url rebasing ([41783fa](https://github.com/vitejs/vite/commit/41783fade0604adb98e468d4a4f8b50c9624899a)), closes [#1834](https://github.com/vitejs/vite/issues/1834) +* **manifest:** include assets referenced via CSS in manifest entries ([34894a2](https://github.com/vitejs/vite/commit/34894a2c41871a08a86fb9a1852563bc698d9c00)), closes [#1827](https://github.com/vitejs/vite/issues/1827) +* yarn pnp resolveDir ([9c6edef](https://github.com/vitejs/vite/commit/9c6edefd45634becbd51c1bf25b735770aeb752a)) +* **optimizer:** fix cjs export interop for webpacked output ([4b6ebc3](https://github.com/vitejs/vite/commit/4b6ebc3f3b117cbe45aff55746dd5f588dfe1587)), closes [#1830](https://github.com/vitejs/vite/issues/1830) +* **ssr:** do not inject hmr timestamp when transforming for ssr ([#1825](https://github.com/vitejs/vite/issues/1825)) ([8ace645](https://github.com/vitejs/vite/commit/8ace6456b682a9ae7d550225817f3270524d96a3)) + + + +# [2.0.0-beta.60](https://github.com/vitejs/vite/compare/v2.0.0-beta.59...v2.0.0-beta.60) (2021-01-31) + + +### Bug Fixes + +* **hmr:** do not update on file unlink when there are no affected modules ([#1818](https://github.com/vitejs/vite/issues/1818)) ([59fe913](https://github.com/vitejs/vite/commit/59fe913f122696ed94ac3f78655576fe7eef98d6)) +* **optimizer:** entry resolving for yarn pnp ([febff7b](https://github.com/vitejs/vite/commit/febff7b837a09eec64bfe8a7cf380dd8001bba67)), closes [#1813](https://github.com/vitejs/vite/issues/1813) +* **optimizer:** fix cjs interop for packages that cannot be ([3b85296](https://github.com/vitejs/vite/commit/3b852964344e4b7e3b45b3af30f27baa89660261)), closes [#1821](https://github.com/vitejs/vite/issues/1821) +* **scan:** skip non-absolute resolved paths during scan ([f635971](https://github.com/vitejs/vite/commit/f6359716ae9f3b206cca1e63b6c1240d3bbc74fa)) + + +### Features + +* support ?url special query ([0006e89](https://github.com/vitejs/vite/commit/0006e89af419472a3c4c3f0f5328242aade2939a)) + + + +# [2.0.0-beta.59](https://github.com/vitejs/vite/compare/v2.0.0-beta.58...v2.0.0-beta.59) (2021-01-30) + + +### Bug Fixes + +* **optimizer:** exclude should apply to deep imports ([3c22f84](https://github.com/vitejs/vite/commit/3c22f8404ecd8504448ffbe05763145887d05928)) +* **optimizer:** separate dep entry proxy modules from actual modules ([8e1d3d8](https://github.com/vitejs/vite/commit/8e1d3d82f6d3ba9e48adb60a1b016c35f0aab627)) + + + +# [2.0.0-beta.58](https://github.com/vitejs/vite/compare/v2.0.0-beta.57...v2.0.0-beta.58) (2021-01-29) + + +### Bug Fixes + +* **optimizer:** handle rollup plugin virtual ids ([a748896](https://github.com/vitejs/vite/commit/a748896b2058b0bbc2a45ef9cf84969f5681b49e)), closes [#1804](https://github.com/vitejs/vite/issues/1804) +* do not generate import specifier if not needed ([e438802](https://github.com/vitejs/vite/commit/e438802803d11acf99918690e4010b601fd7e40d)) + + +### Features + +* add ViteDevServer.transformIndexHtml method for ssr ([dbe1f4a](https://github.com/vitejs/vite/commit/dbe1f4aeadfb9f927f8cd0eec95a32aeee9c3601)), closes [#1745](https://github.com/vitejs/vite/issues/1745) +* support configuring publicDir via config ([470ceb8](https://github.com/vitejs/vite/commit/470ceb827629ab6cccf76cec3249caee08db247a)), closes [#1799](https://github.com/vitejs/vite/issues/1799) + + + +# [2.0.0-beta.57](https://github.com/vitejs/vite/compare/v2.0.0-beta.56...v2.0.0-beta.57) (2021-01-29) + + +### Bug Fixes + +* **optimizer:** fix entry cross imports ([a9ca3da](https://github.com/vitejs/vite/commit/a9ca3da4f1d2c584499bbbf2f16bdbf60d4f12e9)), closes [#1801](https://github.com/vitejs/vite/issues/1801) +* **optimizer:** respect ids that resolve to external urls during scan ([328b6b9](https://github.com/vitejs/vite/commit/328b6b9f7049ec9661cf42f4f43d0ea92fe9b9d0)), closes [#1798](https://github.com/vitejs/vite/issues/1798) +* still account for plugins in optimizer hash ([82dce90](https://github.com/vitejs/vite/commit/82dce90e9d5d3ad1ea516a2a66635960766afb65)) +* **optimizer:** check qualified deps length after accounting for include ([6a03813](https://github.com/vitejs/vite/commit/6a0381311b173b133772efe8d5f174e9bdf989cd)) +* **optimizer:** exclude ?worker and ?raw from runtime dep discovery ([d216da0](https://github.com/vitejs/vite/commit/d216da0e59bd5ab05a8eac38e99e9b6dd9461478)) +* **optimizer:** properly externalize unknown types ([c3b81a8](https://github.com/vitejs/vite/commit/c3b81a8f6a3c8b2199dd42c09f5a722121891334)), closes [#1793](https://github.com/vitejs/vite/issues/1793) + + + +# [2.0.0-beta.56](https://github.com/vitejs/vite/compare/v2.0.0-beta.55...v2.0.0-beta.56) (2021-01-29) + + +### Bug Fixes + +* **optimizer:** handle alias to optimized entries ([81eb7a0](https://github.com/vitejs/vite/commit/81eb7a09ddb0042ec94561052e961c1ee7463bb3)), closes [#1780](https://github.com/vitejs/vite/issues/1780) + + +### Performance Improvements + +* use esbuild service mode during pre-bundling ([b24b07c](https://github.com/vitejs/vite/commit/b24b07ce689df721d63b68e2647cc0609e58df32)) + + + +# [2.0.0-beta.55](https://github.com/vitejs/vite/compare/v2.0.0-beta.54...v2.0.0-beta.55) (2021-01-28) + + +### Bug Fixes + +* **optimizer:** use js loader for resolved mjs files in esbuild ([0f2c2ce](https://github.com/vitejs/vite/commit/0f2c2ce4875c3ed87264c4904b047f06ee1c5d2d)) + + + +# [2.0.0-beta.54](https://github.com/vitejs/vite/compare/v2.0.0-beta.53...v2.0.0-beta.54) (2021-01-28) + + +### Bug Fixes + +* **optimizer:** map entries to their file paths when passed as importer ([32ba8fb](https://github.com/vitejs/vite/commit/32ba8fb2b63b43dd4018dbbe5b6b431375e1c3d0)) + + + +# [2.0.0-beta.53](https://github.com/vitejs/vite/compare/v2.0.0-beta.52...v2.0.0-beta.53) (2021-01-28) + + +### Bug Fixes + +* **css:** pure css chunk removal + manifest entry with multiple css files ([cadf38c](https://github.com/vitejs/vite/commit/cadf38cdedf5d47c63e8476b16bb74434df35878)), closes [#1776](https://github.com/vitejs/vite/issues/1776) +* **optimizer:** add separate hash for invalidating optimized deps ([216ae8e](https://github.com/vitejs/vite/commit/216ae8e95cc43dca47da4607086d2948d538fc53)) +* **optimizer:** externalize json ([c3e52f2](https://github.com/vitejs/vite/commit/c3e52f2b204cdcfcab46e4b5e4992a6cefecba6a)) +* **optimizer:** invalidate all modules on deps rebundle ([02053a2](https://github.com/vitejs/vite/commit/02053a2bfc2db82f277625fdf0563b257ef9c221)) +* **optimizer:** use vite resolver for yarn 2 fallback ([475aae4](https://github.com/vitejs/vite/commit/475aae4ee29f9951f715d0ea98746202cfb586d4)), closes [#1778](https://github.com/vitejs/vite/issues/1778) +* fix pure css chunk removal ([d69d49d](https://github.com/vitejs/vite/commit/d69d49d4ae89b3f8ed37e1cf4345197634514546)) +* **optimizer:** use all inputs for optimized entry matching ([9ecf52b](https://github.com/vitejs/vite/commit/9ecf52b27a3bdd0ce487e142fb45578eea76a3b6)), closes [#1769](https://github.com/vitejs/vite/issues/1769) +* dependency scan with esbuild when using non-HTML entrypoints ([#1772](https://github.com/vitejs/vite/issues/1772)) ([ca862a2](https://github.com/vitejs/vite/commit/ca862a2ea12853876e38100e8894fa22d9dbbc6e)), closes [#1763](https://github.com/vitejs/vite/issues/1763) +* hold missing dep requests while re-bundling ([8e28803](https://github.com/vitejs/vite/commit/8e288039a871b56803a7a5b66cc3766b6c2267db)) +* more stable request hold ([be0e698](https://github.com/vitejs/vite/commit/be0e6981f764cb653d107966a755c8daa18d20c9)) + + +### Reverts + +* Revert "chore: remove unused logic" ([6b154f0](https://github.com/vitejs/vite/commit/6b154f0df3bd73cc3d3bdd91a999a7a4268e6c6b)) + + +### BREAKING CHANGES + +* **css:** the "css" property of build manifest entries is now an +array because it is possible for an entry to link to multiple generated +css files. + + + +# [2.0.0-beta.52](https://github.com/vitejs/vite/compare/v2.0.0-beta.51...v2.0.0-beta.52) (2021-01-28) + + +### Bug Fixes + +* **optimizer:** fix ?raw import and import with queries in pre-bundling ([2f1efa3](https://github.com/vitejs/vite/commit/2f1efa383f5f5e07618101898ce99ccbcbfc2654)), closes [#1759](https://github.com/vitejs/vite/issues/1759) +* always normalize fs prefix slashes ([99e4edd](https://github.com/vitejs/vite/commit/99e4edd468c5e27f66fd276b2ebf22d1c3424c31)) +* **optimizer:** fix optimizer updates on new dep discovery ([b2110af](https://github.com/vitejs/vite/commit/b2110af04564f184bac9308926116138b9ab7aeb)), closes [#1755](https://github.com/vitejs/vite/issues/1755) + + + +# [2.0.0-beta.51](https://github.com/vitejs/vite/compare/v2.0.0-beta.50...v2.0.0-beta.51) (2021-01-27) + + +### Bug Fixes + +* avoid removing double slash in fileToUrl ([f6db155](https://github.com/vitejs/vite/commit/f6db155aa7a06e687d2982069db3d1619495afec)) +* **build:** ensure lib mode file name is correctly inferred for scoped packages ([#1754](https://github.com/vitejs/vite/issues/1754)) ([c2e8806](https://github.com/vitejs/vite/commit/c2e88060624d73b544c31f92e5fee5d84503f6a4)) +* **hmr:** fix hmr for [@fs](https://github.com/fs) urls ([b5987c1](https://github.com/vitejs/vite/commit/b5987c1f603f628ce6c075bbc83e37cafb5ea923)), closes [#1749](https://github.com/vitejs/vite/issues/1749) +* **optimizer:** attempt resolve node builtin first before externalizing ([74b55b8](https://github.com/vitejs/vite/commit/74b55b854200c3847cf13e7e036c0dc299820c64)), closes [#1746](https://github.com/vitejs/vite/issues/1746) +* allow ssr css preloads in preload-helper ([#1734](https://github.com/vitejs/vite/issues/1734)) ([1dfda16](https://github.com/vitejs/vite/commit/1dfda1618801b904b721fbd81d52a874b057ac65)) +* handle vite client path with dollar signs ([#1732](https://github.com/vitejs/vite/issues/1732)) ([20bacf7](https://github.com/vitejs/vite/commit/20bacf7cacb7a0a180a9f38b18b306177a59b40d)), closes [#1423](https://github.com/vitejs/vite/issues/1423) +* scan on windows ([5f7698b](https://github.com/vitejs/vite/commit/5f7698b1f22545584e533bd0cd9abbb49c54d2b8)) +* **optimizer:** entry matching for .mjs entries ([ebe71c4](https://github.com/vitejs/vite/commit/ebe71c42a481c140bbb1999f3bfa37dc15699170)), closes [#1739](https://github.com/vitejs/vite/issues/1739) +* css [@import](https://github.com/import) alias for windows ([71fcfdf](https://github.com/vitejs/vite/commit/71fcfdf219c0dd2aab6612e6b5ba89af1f63cd85)) +* don't override resolver options ([#1740](https://github.com/vitejs/vite/issues/1740)) ([73196e5](https://github.com/vitejs/vite/commit/73196e517643af88a790ab5222d3e6b68dbbf987)) +* resolve css [@import](https://github.com/import) relative imports without leading dot ([78eb32c](https://github.com/vitejs/vite/commit/78eb32c17998a96aff0f787cf4629b2683c6cd09)), closes [#1737](https://github.com/vitejs/vite/issues/1737) +* **optimizer:** do not perform treeshaking for pre-bundling ([6b619c4](https://github.com/vitejs/vite/commit/6b619c4be210dbab0164f42ee4b358c3ac34a896)) + + +### Code Refactoring + +* adjust optimizeDeps options ([fd5e7c0](https://github.com/vitejs/vite/commit/fd5e7c01bae67f7dfc3e631aa87a8d08429b819a)) + + +### Features + +* auto re-run dep optimization on discovery of new imports ([470b4e4](https://github.com/vitejs/vite/commit/470b4e4a8cb040ec368b3702d82f8caa145b6698)) +* dep optimizer entry option ([64ba807](https://github.com/vitejs/vite/commit/64ba807f25df82e51eeacbc11d525df75cf84235)) +* import resolving + url rebasing for less ([f266bb7](https://github.com/vitejs/vite/commit/f266bb7417167e752bbbbd64fe3c82dceb13794b)) +* new manifest format ([51bc1ec](https://github.com/vitejs/vite/commit/51bc1ecc1c130eba7eabdbaf1e5693d1c9967628)) +* proper css resolving + sass import url rebase ([477f174](https://github.com/vitejs/vite/commit/477f1749d938d5ce95df3093de7154b749fe3667)) +* use esbuild to scan imports ([d0f8b12](https://github.com/vitejs/vite/commit/d0f8b1248890c1eea0b81b1d6f61a81d3dc6e44a)) +* **css:** support alias in css [@imports](https://github.com/imports) ([82d87d9](https://github.com/vitejs/vite/commit/82d87d91048b90282c4cae079ee142deb2a782d5)), closes [#650](https://github.com/vitejs/vite/issues/650) + + +### BREAKING CHANGES + +* `optimizeDeps` options have been adjusted. + - Dependencies are now automatically scanned from source code. There + is no longer the need to specify deep imports. + - `optimizeDeps.include` and `optimizeDeps.exclude` now expect type `string[]`. + - `optimizeDpes.link` and `optimizeDeps.auto` are removed. +* the build manifest format has changed. See +https://vitejs.dev/guide/backend-integration.html for more details. + + + +# [2.0.0-beta.50](https://github.com/vitejs/vite/compare/v2.0.0-beta.49...v2.0.0-beta.50) (2021-01-26) + + +### Bug Fixes + +* json plugin error report line regex ([#1719](https://github.com/vitejs/vite/issues/1719)) ([35e1f52](https://github.com/vitejs/vite/commit/35e1f520c99581248f8241b82a1d568518e72d3f)) +* **optimizer:** externalize cross-package imported css ([0599908](https://github.com/vitejs/vite/commit/0599908dcd233dd5108069ea501a651043c28d5c)), closes [#1722](https://github.com/vitejs/vite/issues/1722) +* **optimizer:** fix entry analysis fs read on case-sensitive systems ([1a9b321](https://github.com/vitejs/vite/commit/1a9b321c744b830fe8eb3275c4150eb763d9ba76)), closes [#1720](https://github.com/vitejs/vite/issues/1720) +* **optimizer:** fix entry matching edge case ([c5fe45f](https://github.com/vitejs/vite/commit/c5fe45fdd2c90436e2ee00754aedde2a32325ac6)), closes [#1661](https://github.com/vitejs/vite/issues/1661) +* **optimizer:** handle special case where esm entry gets converted to cjs by esbuild ([32413ce](https://github.com/vitejs/vite/commit/32413cec52ab12a835d3b3ec7a1e294946d11505)), closes [#1724](https://github.com/vitejs/vite/issues/1724) +* **optimizer:** pnp compat to match relative paths ([#1714](https://github.com/vitejs/vite/issues/1714)) ([8fb74f5](https://github.com/vitejs/vite/commit/8fb74f5d0983237a95aab683d800d3546b31729f)) +* **sourcemap:** empty source map chain on nullified sourcemap ([52c9416](https://github.com/vitejs/vite/commit/52c94161b5c0f5eb0ad7e676a7b30a2de4a23116)), closes [#1726](https://github.com/vitejs/vite/issues/1726) +* properly handle base + path in hmr config ([1e67d66](https://github.com/vitejs/vite/commit/1e67d669318fac320c61ea00e0e01e972183fa27)) + + +### Features + +* allow speicfying ssr entry directly via build.ssr option ([45d8bf4](https://github.com/vitejs/vite/commit/45d8bf4da234f73badcf47e574e1e3ee3dc55b6c)) + + + +# [2.0.0-beta.49](https://github.com/vitejs/vite/compare/v2.0.0-beta.48...v2.0.0-beta.49) (2021-01-25) + + +### Bug Fixes + +* **config:** fix native esm config loading on windows ([33d3cca](https://github.com/vitejs/vite/commit/33d3cca78607e14e4d0b13e7012d065a94d184b1)) +* **optimizer:** entry matching on windows ([e6120d5](https://github.com/vitejs/vite/commit/e6120d582051f3535951698df40dc9b6fc485ae0)) +* **optimizer:** fix output to entry matching logic ([6c96883](https://github.com/vitejs/vite/commit/6c96883d794d3396e890907df6b799d79a027420)), closes [#1704](https://github.com/vitejs/vite/issues/1704) +* **ssr:** generate same asset url links for ssr build ([68960f7](https://github.com/vitejs/vite/commit/68960f7867be13cfdce9ea49a8cc05448dff5e60)), closes [#1711](https://github.com/vitejs/vite/issues/1711) +* **watcher:** ensure only add normalized file paths ([a19c456](https://github.com/vitejs/vite/commit/a19c4565542c2c3575ab47642f80737a3bf26f3a)) +* **watcher:** watch fs specific root paths ([64d2c17](https://github.com/vitejs/vite/commit/64d2c1772a57b024373e33015740c11c172dba85)) +* do not move css modules to vendor chunk ([3d55e83](https://github.com/vitejs/vite/commit/3d55e8304e0faa71aec49326901048c46d196210)), closes [#1703](https://github.com/vitejs/vite/issues/1703) +* fix hmr.path option normalization ([cbeb9ba](https://github.com/vitejs/vite/commit/cbeb9ba7c7a192e61279fb00b543b81843663bc1)), closes [#1705](https://github.com/vitejs/vite/issues/1705) + + + +# [2.0.0-beta.48](https://github.com/vitejs/vite/compare/v2.0.0-beta.47...v2.0.0-beta.48) (2021-01-25) + + +### Bug Fixes + +* externalize known css types during dep-prebundling ([02a0324](https://github.com/vitejs/vite/commit/02a0324a56fcc3659ace4b62f96b2a8b10979f4c)), closes [#1695](https://github.com/vitejs/vite/issues/1695) +* fallback to static middleware on unfound source maps ([2096309](https://github.com/vitejs/vite/commit/2096309bee0f4ad838cde2a9dd9114b819e462c4)) +* preload marker incorrect replacement ([7f83deb](https://github.com/vitejs/vite/commit/7f83deb7fe5add6117f8f715fc3165511761d07b)) +* remove preload markers in all cases ([6cd2d35](https://github.com/vitejs/vite/commit/6cd2d35d791311de953b7a832a877b1c98e2b2ed)), closes [#1694](https://github.com/vitejs/vite/issues/1694) +* resolve library entry ([3240db1](https://github.com/vitejs/vite/commit/3240db19d33f0816e3c52a5042161a94753879d9)) + + +### Features + +* resolved ids rollup compat for win32 ([#1693](https://github.com/vitejs/vite/issues/1693)) ([e2137b7](https://github.com/vitejs/vite/commit/e2137b71a5a82580b2cf45e84ead136052014ac7)), closes [#1522](https://github.com/vitejs/vite/issues/1522) + + + +# [2.0.0-beta.47](https://github.com/vitejs/vite/compare/v2.0.0-beta.46...v2.0.0-beta.47) (2021-01-24) + + +### Bug Fixes + +* do not apply json plugin to commonjs proxy ([a92f430](https://github.com/vitejs/vite/commit/a92f4303253c9423093bedad6b06744d66dd1d39)), closes [#1679](https://github.com/vitejs/vite/issues/1679) +* esbuild optimizer yarn 2 pnp compat ([028c3bb](https://github.com/vitejs/vite/commit/028c3bb1a6c5f56eaa7f8f122200d6262a1a8683)), closes [#1688](https://github.com/vitejs/vite/issues/1688) +* fix incorrect preload placeholder regex ([5ca43ef](https://github.com/vitejs/vite/commit/5ca43ef6e91e41f09e06d92adef79953a3df9782)), closes [#1686](https://github.com/vitejs/vite/issues/1686) +* fix server.watch option ignore overwriting defaults ([#1680](https://github.com/vitejs/vite/issues/1680)) ([33cffa3](https://github.com/vitejs/vite/commit/33cffa3910600c5adfb10f2cab07029f1ff8f35f)) + + +### Performance Improvements + +* **build:** improve performance of default vendor chunk splitting ([#1690](https://github.com/vitejs/vite/issues/1690)) ([0bed9c4](https://github.com/vitejs/vite/commit/0bed9c44b2c89ad4fb7439907959f78d946b42cd)) + + + +# [2.0.0-beta.46](https://github.com/vitejs/vite/compare/v2.0.0-beta.45...v2.0.0-beta.46) (2021-01-24) + + +### Bug Fixes + +* **css:** fix extract concurrency issue when disabling cssCodeSplit ([4ac7e7e](https://github.com/vitejs/vite/commit/4ac7e7ec9915bd044454f90a6a3d5a9676b3615c)) + + + +# [2.0.0-beta.45](https://github.com/vitejs/vite/compare/v2.0.0-beta.44...v2.0.0-beta.45) (2021-01-24) + + +### Bug Fixes + +* **hmr:** fix nested hmr accept calls with base ([2950c3c](https://github.com/vitejs/vite/commit/2950c3c278e20174184e44c194393b098c0d4305)) +* **hmr:** preserve host when updating link CSS ([60f9782](https://github.com/vitejs/vite/commit/60f9782a8481a4ce4d4c90ca246f5de44065d314)), closes [#1665](https://github.com/vitejs/vite/issues/1665) +* **html:** ensure quote in rebased asset urls in html ([7306610](https://github.com/vitejs/vite/commit/73066105727e669fe15d926fbe07d1788a469844)), closes [#1668](https://github.com/vitejs/vite/issues/1668) +* **import-anaysis:** markPos out-of-range for overwrite ([#1671](https://github.com/vitejs/vite/issues/1671)) ([226e984](https://github.com/vitejs/vite/commit/226e9849253677770f11f8a26e6ec205067dc902)) +* **optimizer:** repsect alias in pre-bundling ([2824d06](https://github.com/vitejs/vite/commit/2824d067d5239b506f93dc9c073c21d7e059bbe3)), closes [#1674](https://github.com/vitejs/vite/issues/1674) +* **resolve:** handle paths starting with slash in entry fields ([13da32e](https://github.com/vitejs/vite/commit/13da32e9ce22b1916a1b98bba7ad83bd145563c1)), closes [#1676](https://github.com/vitejs/vite/issues/1676) +* import analysis dynamic import check ([d4909b9](https://github.com/vitejs/vite/commit/d4909b936994d4fec37dfbafd27cd24494de8d14)) +* revert trailing slash handling + improve dev base usage ([01e9ac0](https://github.com/vitejs/vite/commit/01e9ac0222dcc36c075c25e3fe8f7e8881867e9c)), closes [#1664](https://github.com/vitejs/vite/issues/1664) +* support empty, relative and external base values ([00bc446](https://github.com/vitejs/vite/commit/00bc4466567bd5613d67abd1bdf46d9c9cb23a80)), closes [#1669](https://github.com/vitejs/vite/issues/1669) + + +### Features + +* default vendor chunk splitting ([f6b58a0](https://github.com/vitejs/vite/commit/f6b58a0f535b1c26f9c1dfda74c28c685402c3c9)) +* disable prompts and clearScreen on CI ([63dd1a2](https://github.com/vitejs/vite/commit/63dd1a2829ea0764c12e11f2f3510bc1c096febf)), closes [#1673](https://github.com/vitejs/vite/issues/1673) +* source map for optimized deps ([972b13e](https://github.com/vitejs/vite/commit/972b13e09f9f0d43de9b7fb1d7bd706b4a10984b)) +* support stringifying json ([98c321b](https://github.com/vitejs/vite/commit/98c321b3694dc77dd66e8064f14467e909832171)), closes [#1672](https://github.com/vitejs/vite/issues/1672) +* vite preview command for previewing build output ([a198990](https://github.com/vitejs/vite/commit/a198990efe4f96c2155928ac23264437d393d54e)), closes [#1627](https://github.com/vitejs/vite/issues/1627) + + + +# [2.0.0-beta.44](https://github.com/vitejs/vite/compare/v2.0.0-beta.43...v2.0.0-beta.44) (2021-01-23) + + +### Bug Fixes + +* esbuild dep resolving on windows ([62e4d72](https://github.com/vitejs/vite/commit/62e4d724a8a008cb6bd6f2122753880ec3568192)) + + + +# [2.0.0-beta.43](https://github.com/vitejs/vite/compare/v2.0.0-beta.42...v2.0.0-beta.43) (2021-01-23) + + +### Bug Fixes + +* **optimizer:** force vite resolver for esbuild pre-bundle ([4c4d629](https://github.com/vitejs/vite/commit/4c4d629c391415351c797cf9b9c54d22be6244fe)) + + + +# [2.0.0-beta.42](https://github.com/vitejs/vite/compare/v2.0.0-beta.41...v2.0.0-beta.42) (2021-01-23) + + +### Bug Fixes + +* **optimizer:** ensure esbuild use vite-resolved entries ([bdb9b3c](https://github.com/vitejs/vite/commit/bdb9b3c5a5c8da83d8b8082e936cb3cc16eeb1e0)) + + + +# [2.0.0-beta.41](https://github.com/vitejs/vite/compare/v2.0.0-beta.40...v2.0.0-beta.41) (2021-01-23) + + +### Bug Fixes + +* lower .mjs resolve priority ([b15e90e](https://github.com/vitejs/vite/commit/b15e90e6893582d04f9506ef56cc9d03c9c6d775)), closes [#1660](https://github.com/vitejs/vite/issues/1660) + + + +# [2.0.0-beta.40](https://github.com/vitejs/vite/compare/v2.0.0-beta.39...v2.0.0-beta.40) (2021-01-23) + + +### Bug Fixes + +* **optimizer:** compiled esmdoule interop ([6826624](https://github.com/vitejs/vite/commit/68266245338d4f1c27d9552d5d54eff3420af8b6)), closes [#1659](https://github.com/vitejs/vite/issues/1659) + + + +# [2.0.0-beta.39](https://github.com/vitejs/vite/compare/v2.0.0-beta.38...v2.0.0-beta.39) (2021-01-23) + + +### Bug Fixes + +* **optimizer:** fix es interop heuristics for entry with only export * from ([ef1a7e3](https://github.com/vitejs/vite/commit/ef1a7e33cc19bac7893bca85b6df14adeb847516)) +* **ssr:** do not inject ?import query for ssr transforms ([7d26119](https://github.com/vitejs/vite/commit/7d261191e5ebf0c2fede0c6fc82137999d58cc5c)), closes [#1655](https://github.com/vitejs/vite/issues/1655) +* hmr port fallback in middlewareMode ([36a9456](https://github.com/vitejs/vite/commit/36a94560399e03cdbdbdbdb16913c05deb87ab9b)) +* **ssr:** avoid resolving externals to mjs ([3955fe3](https://github.com/vitejs/vite/commit/3955fe37fe4498e6c7df122376a942d63afe6acb)) +* file dir resolve should prioritize package.json ([ce2d49a](https://github.com/vitejs/vite/commit/ce2d49ab396aa7b4ed582650e569d7f2f6d3ef9f)) +* **ssr:** remove import query in ssrLoadModule ([80473c1](https://github.com/vitejs/vite/commit/80473c1423209824d143df77b38f1bdb8723f47b)) + + + +# [2.0.0-beta.38](https://github.com/vitejs/vite/compare/v2.0.0-beta.37...v2.0.0-beta.38) (2021-01-23) + + +### Bug Fixes + +* **dev:** remove comment for sourcemap reference at debug ([#1658](https://github.com/vitejs/vite/issues/1658)) ([16248c0](https://github.com/vitejs/vite/commit/16248c02844c5447eeb7c441cc4b051becef2346)) +* **optimizer:** improve exports analysis ([406cbea](https://github.com/vitejs/vite/commit/406cbeaa4f52472ce356980840f1a2a824eaa497)) +* **ssr:** fix ssr transform edge cases ([f22ddbd](https://github.com/vitejs/vite/commit/f22ddbdb52d4579a5756215c320a13cd674a38a0)), closes [#1646](https://github.com/vitejs/vite/issues/1646) +* exclude spa-fallback middleware in middlewareMode ([#1645](https://github.com/vitejs/vite/issues/1645)) ([843c879](https://github.com/vitejs/vite/commit/843c87915082b36f7d1ffeb81515b45d5d65aabb)) + + +### Code Refactoring + +* remove optimizeDeps.plugins ([38524f6](https://github.com/vitejs/vite/commit/38524f6c6e864f9805dd0083da1dfa8ce20fa816)) + + +### Features + +* esbuild based dep pre-bundling ([6e7f652](https://github.com/vitejs/vite/commit/6e7f652d89dde43806a2323560486c9b4b771a35)) +* support `base` option during dev, deprecate `build.base` ([#1556](https://github.com/vitejs/vite/issues/1556)) ([809d4bd](https://github.com/vitejs/vite/commit/809d4bd3bf62d3bc6b35f182178922d2ab2175f1)) + + +### BREAKING CHANGES + +* `optimizeDeps.plugins` has been removed. The dep +optimizer is now using `esbuild`, and all non-js files are automatically +externalized to be processed by Vite's transform pipeline when imported. + + + +# [2.0.0-beta.37](https://github.com/vitejs/vite/compare/v2.0.0-beta.35...v2.0.0-beta.37) (2021-01-22) + + +### Bug Fixes + +* **css:** fix url rewriting in [@imported](https://github.com/imported) css ([52ae44f](https://github.com/vitejs/vite/commit/52ae44fe97b53ce82633268030bb46594f385860)), closes [#1629](https://github.com/vitejs/vite/issues/1629) +* **manifest:** avoid chunks with same name overwriting one another ([cf81aa3](https://github.com/vitejs/vite/commit/cf81aa399b2df1ee8441a1b8922908f4e36358d6)), closes [#1632](https://github.com/vitejs/vite/issues/1632) +* **ssr:** do not inject inlined css in ssr build ([5d77665](https://github.com/vitejs/vite/commit/5d77665def42ffafc699a0006e4527536dfd1114)), closes [#1643](https://github.com/vitejs/vite/issues/1643) +* always reload when html is edited in middleware mode ([85c89be](https://github.com/vitejs/vite/commit/85c89bea9807090d928942a72b972183ebf8483a)) +* handle esm config syntax error in Node 12 ([20cf718](https://github.com/vitejs/vite/commit/20cf718ac77abfce5656ee9836f8c06ddbbc440d)), closes [#1635](https://github.com/vitejs/vite/issues/1635) +* normalize paths for cjs optimized deps on windows ([#1631](https://github.com/vitejs/vite/issues/1631)) ([b462e33](https://github.com/vitejs/vite/commit/b462e33ce3d31df49ada436324a9c32cd5c9053a)) +* still resolve jsnext fields ([4e0cd73](https://github.com/vitejs/vite/commit/4e0cd7384e850e4b7f23b68e5b591bb717650b79)) + + +### Features + +* allow inline postcss config ([6bd2140](https://github.com/vitejs/vite/commit/6bd21402a9e5955433656024f5548f12b12ea2fa)), closes [#1061](https://github.com/vitejs/vite/issues/1061) +* hmr for glob import ([edd2fd9](https://github.com/vitejs/vite/commit/edd2fd9de904a194f25e18136dfe298c7bcbbd8d)) + + + +# [2.0.0-beta.36](https://github.com/vitejs/vite/compare/v2.0.0-beta.35...v2.0.0-beta.36) (2021-01-21) + + +### Bug Fixes + +* always reload when html is edited in middleware mode ([85c89be](https://github.com/vitejs/vite/commit/85c89bea9807090d928942a72b972183ebf8483a)) +* still resolve jsnext fields ([6e06108](https://github.com/vitejs/vite/commit/6e061089c62898086c07fad7154b178446a18da5)) + + +### Features + +* allow inline postcss config ([6bd2140](https://github.com/vitejs/vite/commit/6bd21402a9e5955433656024f5548f12b12ea2fa)), closes [#1061](https://github.com/vitejs/vite/issues/1061) +* hmr for glob import ([edd2fd9](https://github.com/vitejs/vite/commit/edd2fd9de904a194f25e18136dfe298c7bcbbd8d)) + + + +# [2.0.0-beta.35](https://github.com/vitejs/vite/compare/v2.0.0-beta.34...v2.0.0-beta.35) (2021-01-20) + + +### Bug Fixes + +* allow direct inspection of static file via browser ([a3c334f](https://github.com/vitejs/vite/commit/a3c334f66dbe1e5c49c4e5d77381aa0098c4a8a9)), closes [#1612](https://github.com/vitejs/vite/issues/1612) +* also resolve for module condition ([3a3029e](https://github.com/vitejs/vite/commit/3a3029effa0b83775f02fbd9469ef104eb6adb33)), closes [#1583](https://github.com/vitejs/vite/issues/1583) +* do not apply jsxInject on ts files ([a72a59c](https://github.com/vitejs/vite/commit/a72a59c55355a2a247b84178e63ce8c7cc1d7564)) +* inline async css for legacy builds ([940d483](https://github.com/vitejs/vite/commit/940d48333f6572314576da9312f36018fd70bdc8)) +* manually test global regex codeframeRE index ([#1608](https://github.com/vitejs/vite/issues/1608)) ([20d6c0f](https://github.com/vitejs/vite/commit/20d6c0fae160e25ab6cb76484baf910388dccdc6)) +* properly format css pre-processor errors from [@imported](https://github.com/imported) files ([ec18bde](https://github.com/vitejs/vite/commit/ec18bde7ee4045a47362240a6f5ff4997657c7ba)), closes [#1600](https://github.com/vitejs/vite/issues/1600) [#1601](https://github.com/vitejs/vite/issues/1601) +* **asset:** use stricter asset url marker and regex ([e6c8478](https://github.com/vitejs/vite/commit/e6c8478dd765e63f56e2c4559daf03f976f60b4c)), closes [#1602](https://github.com/vitejs/vite/issues/1602) +* **plugin-dynamic-import:** include assetDir in dynamic import polyfill module path ([#1610](https://github.com/vitejs/vite/issues/1610)) ([47ff0f4](https://github.com/vitejs/vite/commit/47ff0f4307da6a90db2fc43fcf0aaffdb9e36643)) +* **resolve:** get pkg from importer for relative id ([#1599](https://github.com/vitejs/vite/issues/1599)) ([c821f09](https://github.com/vitejs/vite/commit/c821f094c25a7acde87b868dced265aa6e792a57)) + + +### Features + +* **manifest:** include dynamic entries and dynamic imports ([#1609](https://github.com/vitejs/vite/issues/1609)) ([9ed4908](https://github.com/vitejs/vite/commit/9ed49085ae860fb96d51ac50845f96ceb9fa649f)) +* detect and warn against imports to transitively optimized deps ([3841e70](https://github.com/vitejs/vite/commit/3841e702213efac178aa90ab01825a813d3b4819)), closes [#1543](https://github.com/vitejs/vite/issues/1543) + + + +# [2.0.0-beta.34](https://github.com/vitejs/vite/compare/v2.0.0-beta.33...v2.0.0-beta.34) (2021-01-20) + + +### Bug Fixes + +* default changeOrigin to true in proxy option shorthand ([b008bd5](https://github.com/vitejs/vite/commit/b008bd59674c6d46ca41108b1c9d5076374bd1b8)), closes [#1577](https://github.com/vitejs/vite/issues/1577) +* emit css only once when there are multiple outputs ([6bce108](https://github.com/vitejs/vite/commit/6bce1081991501f3779bff1a81e5dd1e63e5d38e)), closes [#1590](https://github.com/vitejs/vite/issues/1590) +* **optimizer:** handle commonjs require css ([#1568](https://github.com/vitejs/vite/issues/1568)) ([3d09b50](https://github.com/vitejs/vite/commit/3d09b50b8774cf85a8c1dee24b3e379cbd3e9eb5)), closes [#1566](https://github.com/vitejs/vite/issues/1566) +* handle legacy chunks in manifest ([123b6f6](https://github.com/vitejs/vite/commit/123b6f67f7e159d098109d5c65a74dc0d17bd495)), closes [#1551](https://github.com/vitejs/vite/issues/1551) +* use safe dynamic import rewrite ([5cb02ce](https://github.com/vitejs/vite/commit/5cb02ce0b24ff167b7da3e2de9b0237186d9e95a)), closes [#1563](https://github.com/vitejs/vite/issues/1563) +* **hmr:** fix hmr invalidation on circular deps ([ca8442c](https://github.com/vitejs/vite/commit/ca8442c19e51526e2fa75f0c4976941a2b9089e6)), closes [#1477](https://github.com/vitejs/vite/issues/1477) +* **resolve:** node resolve from virtual modules ([c6d5ed8](https://github.com/vitejs/vite/commit/c6d5ed833befafaaea14fbd2fb62a7ed8d58c409)) + + + +# [2.0.0-beta.33](https://github.com/vitejs/vite/compare/v2.0.0-beta.32...v2.0.0-beta.33) (2021-01-19) + + +### Bug Fixes + +* fix ssr module invalidation infinite loop ([30885d1](https://github.com/vitejs/vite/commit/30885d1673a282a12e0c7471fc80236b72ebeb16)), closes [#1591](https://github.com/vitejs/vite/issues/1591) + + + +# [2.0.0-beta.32](https://github.com/vitejs/vite/compare/v2.0.0-beta.31...v2.0.0-beta.32) (2021-01-19) + + +### Bug Fixes + +* avoid preloading owner chunk ([61969d7](https://github.com/vitejs/vite/commit/61969d787200ab0b03179ecf2855c5b4aff3baa6)) +* ssr transform check valid inMap ([bf4b3e9](https://github.com/vitejs/vite/commit/bf4b3e9b416bb0f2a8ee8bfce969d452429a8282)) +* support resolving .json ext to be consistent with Node ([a1d1dde](https://github.com/vitejs/vite/commit/a1d1dde70c4626ab603ed07234fe296ef8d5a65f)) + + +### Code Refactoring + +* rename ViteDevServer.app -> ViteDevServer.middlewares ([394390a](https://github.com/vitejs/vite/commit/394390a983deccd8cbca101066db93f60577b810)) + + +### Features + +* import.meta.env.SSR ([fe7396d](https://github.com/vitejs/vite/commit/fe7396d3896d04db17f73ea265eebe0397414e65)) +* ssr manifest for preload inference ([107e79e](https://github.com/vitejs/vite/commit/107e79e7b7d422f0d1dbe8b7b435636df7c6281c)) +* **ssr:** isolated mode ([e954ed2](https://github.com/vitejs/vite/commit/e954ed25099d9217d30a5a4d38e5dfee5acee0fd)) +* ssr sourcemap + stacktrace fix ([6cb04fa](https://github.com/vitejs/vite/commit/6cb04fa3b3a7a4ac4676a7b1c41d9d5068fae5de)) + + +### BREAKING CHANGES + +* `ViteDevServer.app` is now `ViteDevServer.middlewares`. +In addition, Vite no longer serves `index.html` in middleware mode. The +server using Vite as middleware is responsible for serving HTML with +`/@vite/client` injected. + + + +# [2.0.0-beta.31](https://github.com/vitejs/vite/compare/v2.0.0-beta.30...v2.0.0-beta.31) (2021-01-18) + + +### Bug Fixes + +* workaround for ts config + native esm w/ imports ([4a7d2eb](https://github.com/vitejs/vite/commit/4a7d2ebca1719d83c22d7dce5214e61f7906a772)), closes [#1560](https://github.com/vitejs/vite/issues/1560) +* **resolve:** also respect browser mapping of dependencies ([12b706d](https://github.com/vitejs/vite/commit/12b706d6ecd99c98f326deae53f9aa79cd8a81f4)), closes [#1547](https://github.com/vitejs/vite/issues/1547) + + + +# [2.0.0-beta.30](https://github.com/vitejs/vite/compare/v2.0.0-beta.29...v2.0.0-beta.30) (2021-01-15) + + +### Bug Fixes + +* **config:** delete cache correctly when restarting server ([#1541](https://github.com/vitejs/vite/issues/1541)) ([bd3b1bf](https://github.com/vitejs/vite/commit/bd3b1bfd83488b05a188a9d1c7093e3003721d91)) +* **config:** load native esm ts config string with base64 encoding ([55b05db](https://github.com/vitejs/vite/commit/55b05dba3d157da72eaf9c445b0bb5084b9858d0)), closes [#1548](https://github.com/vitejs/vite/issues/1548) + + + +# [2.0.0-beta.29](https://github.com/vitejs/vite/compare/v2.0.0-beta.28...v2.0.0-beta.29) (2021-01-14) + + +### Bug Fixes + +* **optimizer:** fix empty exclude filter ([4579c38](https://github.com/vitejs/vite/commit/4579c382d4a1b0385510bb708f74305c87c4a68a)) +* fix graceful shutdown on sigint ([fe7238c](https://github.com/vitejs/vite/commit/fe7238c530533d7ea7bff20ce97485669c7dfb46)) +* warn failed source map load instead of erroring ([7a1261b](https://github.com/vitejs/vite/commit/7a1261b51695cbe7d41da6835c360b9bb26d189e)) + + + +# [2.0.0-beta.28](https://github.com/vitejs/vite/compare/v2.0.0-beta.27...v2.0.0-beta.28) (2021-01-14) + + +### Bug Fixes + +* alias should work for optimized deps ([54dab71](https://github.com/vitejs/vite/commit/54dab71e41cdd9f516460d153b024d0c0cc05097)) +* serve out of root static file on windows ([#1537](https://github.com/vitejs/vite/issues/1537)) ([506bf2d](https://github.com/vitejs/vite/commit/506bf2d542a27ee19a1b1b2d05aad845f4387cf6)) +* **dev:** correct responce for html qurey ([#1526](https://github.com/vitejs/vite/issues/1526)) ([49d294d](https://github.com/vitejs/vite/commit/49d294d36d0f32d00a025a03017c9049d3f48ebd)), closes [#1524](https://github.com/vitejs/vite/issues/1524) +* **optimizer:** should respect rollup external during pre-bundling ([db97317](https://github.com/vitejs/vite/commit/db9731753abf36563172b02961ded54be23dd215)), closes [#1528](https://github.com/vitejs/vite/issues/1528) + + +### Features + +* add clearScreen option ([c5c3298](https://github.com/vitejs/vite/commit/c5c32982f207055229b6bce61ce205d8d20db023)) +* close server on sigint/sigterm ([4338d7d](https://github.com/vitejs/vite/commit/4338d7d6f32c8e0e67ff58f0cb8c1a9120294756)), closes [#1525](https://github.com/vitejs/vite/issues/1525) +* support specifying URL path via server.open option ([#1514](https://github.com/vitejs/vite/issues/1514)) ([25e9c44](https://github.com/vitejs/vite/commit/25e9c44992c8b868cec97dbdeddd3a4837d5bb07)) +* support using vite as a middleware ([960b420](https://github.com/vitejs/vite/commit/960b42068579dddc2c216720a7f16d8d189e8225)) + + + +# [2.0.0-beta.27](https://github.com/vitejs/vite/compare/v2.0.0-beta.26...v2.0.0-beta.27) (2021-01-13) + + +### Bug Fixes + +* transform import.meta.url in config files ([98e57de](https://github.com/vitejs/vite/commit/98e57deb9d16b23b7ae0c382cca49a9420443b47)), closes [#1511](https://github.com/vitejs/vite/issues/1511) + + +### Features + +* **vite:** support RegExp strings as server.proxy keys ([#1510](https://github.com/vitejs/vite/issues/1510)) ([f39a2aa](https://github.com/vitejs/vite/commit/f39a2aafd35a70effc298d53b0b7539fbac79e89)) +* warn unintended dependency during pre-bundling ([ae6cc27](https://github.com/vitejs/vite/commit/ae6cc27349e66945a0964635e6ad64933fe33960)) + + + +# [2.0.0-beta.26](https://github.com/vitejs/vite/compare/v2.0.0-beta.25...v2.0.0-beta.26) (2021-01-13) + + +### Bug Fixes + +* properly externalize resolved external urls ([6cda88d](https://github.com/vitejs/vite/commit/6cda88d882ffcd5b3fdaa005296bfe1f0991925c)) + + + +# [2.0.0-beta.25](https://github.com/vitejs/vite/compare/v2.0.0-beta.24...v2.0.0-beta.25) (2021-01-12) + + +### Bug Fixes + +* Revert "feat: allow browser new window view source ([#1496](https://github.com/vitejs/vite/issues/1496))" ([64fde38](https://github.com/vitejs/vite/commit/64fde3883e07f66fee6f6234f84ad35288a24b62)), closes [#1507](https://github.com/vitejs/vite/issues/1507) + + +### Features + +* support aliasing to external url ([abf7844](https://github.com/vitejs/vite/commit/abf784403e1d9e36653ee4fd167c4cf341fd343f)) + + + +# [2.0.0-beta.24](https://github.com/vitejs/vite/compare/v2.0.0-beta.23...v2.0.0-beta.24) (2021-01-12) + + +### Bug Fixes + +* **hmr:** watch file changes even when HMR is disabled ([#1504](https://github.com/vitejs/vite/issues/1504)) ([cc5fa6e](https://github.com/vitejs/vite/commit/cc5fa6efb3448e2f83b5d6d428e79803c8993657)) +* always replace preload marker with value ([2d6f524](https://github.com/vitejs/vite/commit/2d6f5243e16f7debd7ba0de4bf22706df35ccf73)) +* more consistent outDir formatting ([50bff79](https://github.com/vitejs/vite/commit/50bff797c536b08661791a833cfbb9179ff54422)), closes [#1497](https://github.com/vitejs/vite/issues/1497) +* show target build mode in logs ([#1498](https://github.com/vitejs/vite/issues/1498)) ([ae2e14b](https://github.com/vitejs/vite/commit/ae2e14baf1771c2ccdeece8bbc2b9bd11b279490)) +* support import.meta.url in ts esm config file ([cf5f3ab](https://github.com/vitejs/vite/commit/cf5f3ab2c33aca6ab6bff8d600854f93586adcf0)), closes [#1499](https://github.com/vitejs/vite/issues/1499) + + +### Features + +* allow browser new window view source ([#1496](https://github.com/vitejs/vite/issues/1496)) ([1629c54](https://github.com/vitejs/vite/commit/1629c546158253f155afecb55846771013f90ec0)) +* require explicit option to empty outDir when it is out of root ([730d2f0](https://github.com/vitejs/vite/commit/730d2f0d8081e11c88b1151086d99b23e0c58823)), closes [#1501](https://github.com/vitejs/vite/issues/1501) + + + +# [2.0.0-beta.23](https://github.com/vitejs/vite/compare/v2.0.0-beta.22...v2.0.0-beta.23) (2021-01-12) + + +### Bug Fixes + +* fix ts config loading on windows ([ec370d2](https://github.com/vitejs/vite/commit/ec370d22db875cca0b2319073d9025b05e7ffc54)), closes [#1493](https://github.com/vitejs/vite/issues/1493) + + + +# [2.0.0-beta.22](https://github.com/vitejs/vite/compare/v2.0.0-beta.21...v2.0.0-beta.22) (2021-01-11) + + +### Bug Fixes + +* handle http proxy error ([4ca20f2](https://github.com/vitejs/vite/commit/4ca20f2e16c1bba0dc330c7e5879ca322b2ab21c)), closes [#1485](https://github.com/vitejs/vite/issues/1485) +* optimizer hash should take inline mode into account ([0aed0e8](https://github.com/vitejs/vite/commit/0aed0e89f84aff26cfdf57879925a76fa696331d)), closes [#1490](https://github.com/vitejs/vite/issues/1490) +* support resolved Ids that start with null bytes ([7074414](https://github.com/vitejs/vite/commit/70744143cd09863412a59aad14de888067bd8531)), closes [#1471](https://github.com/vitejs/vite/issues/1471) +* **config:** support native esm config on windows + support TS config in native esm projects ([803f6da](https://github.com/vitejs/vite/commit/803f6da2ad04846c3ae2622e15b5a18f0691204e)), closes [#1487](https://github.com/vitejs/vite/issues/1487) + + +### Features + +* **resolve:** support subpath patterns + production/development conditinals in exports field ([62cbd53](https://github.com/vitejs/vite/commit/62cbd53f25411ddfc7cfd5446c2f487a260da191)) +* **server:** add strict-port option ([#1453](https://github.com/vitejs/vite/issues/1453)) ([0501084](https://github.com/vitejs/vite/commit/05010846cb266f540039f13e280b486c97803f03)) + + + +# [2.0.0-beta.21](https://github.com/vitejs/vite/compare/v2.0.0-beta.20...v2.0.0-beta.21) (2021-01-11) + + +### Bug Fixes + +* properly remove dynamic import args for full dynamic imports ([d9c3fdb](https://github.com/vitejs/vite/commit/d9c3fdb4073d49d427d825007154e873d8aa3d9a)) + + + +# [2.0.0-beta.20](https://github.com/vitejs/vite/compare/v2.0.0-beta.19...v2.0.0-beta.20) (2021-01-11) + + +### Bug Fixes + +* **optimizer:** exclude should not be resolve ([#1469](https://github.com/vitejs/vite/issues/1469)) ([f8c34ee](https://github.com/vitejs/vite/commit/f8c34eeb89e327f484293f3156119ba6d14f6aee)) +* **resolve:** heuristics for browser vs. module field ([1865e6e](https://github.com/vitejs/vite/commit/1865e6ee4c3e07c0f4a199c1ba7e1c1c4f68862f)), closes [#1467](https://github.com/vitejs/vite/issues/1467) + + +### Features + +* allow passing options to rollup commonjs plugin via build.commonjsOptions ([6ed8e28](https://github.com/vitejs/vite/commit/6ed8e286f149f9474e0fc624110de5f787551d62)), closes [#1460](https://github.com/vitejs/vite/issues/1460) +* async chunk loading optimizations ([e6f7fba](https://github.com/vitejs/vite/commit/e6f7fbad75c1b406b9a95060c5d2a42d3a8994a8)) + + + +# [2.0.0-beta.19](https://github.com/vitejs/vite/compare/v2.0.0-beta.18...v2.0.0-beta.19) (2021-01-10) + + +### Bug Fixes + +* transform json in deep import ([#1459](https://github.com/vitejs/vite/issues/1459)) ([cf8342b](https://github.com/vitejs/vite/commit/cf8342bef45bebb05d020d4f220b12d2bf526256)), closes [#1458](https://github.com/vitejs/vite/issues/1458) + + + +# [2.0.0-beta.18](https://github.com/vitejs/vite/compare/v2.0.0-beta.17...v2.0.0-beta.18) (2021-01-10) + + +### Bug Fixes + +* fix dynamic import with parent relative paths ([bbfe06c](https://github.com/vitejs/vite/commit/bbfe06ce1af8f89490032e609377c6516f7da773)), closes [#1461](https://github.com/vitejs/vite/issues/1461) +* **optimizer:** properly externalize css/asset imports in optimized deps ([5d180db](https://github.com/vitejs/vite/commit/5d180db4bd19e26de20bb816d594226b4d492804)), closes [#1443](https://github.com/vitejs/vite/issues/1443) + + +### Features + +* **optimizer:** support specifying plugins for the optimizer ([1ea0168](https://github.com/vitejs/vite/commit/1ea016823975f3d0e37bf7b65614eded213e0869)) + + + +# [2.0.0-beta.17](https://github.com/vitejs/vite/compare/v2.0.0-beta.16...v2.0.0-beta.17) (2021-01-10) + + +### Code Refactoring + +* support glob import under `import.meta.glob` ([23d0f2b](https://github.com/vitejs/vite/commit/23d0f2b85d8eb8677e30456342000cabed8e684e)) + + +### BREAKING CHANGES + +* Glob import syntax has changed. The feature is now +exposed under `import.meta.glob` (lazy, exposes dynamic import functions) +and `import.meta.globEager` (eager, exposes already imported modules). + + + +# [2.0.0-beta.16](https://github.com/vitejs/vite/compare/v2.0.0-beta.15...v2.0.0-beta.16) (2021-01-09) + + +### Bug Fixes + +* inject css link when cssCodeSplit is disabled ([51a02ff](https://github.com/vitejs/vite/commit/51a02ff902c3afa4dff76b43f75b9221768cd7f8)), closes [#1141](https://github.com/vitejs/vite/issues/1141) +* set NODE_ENV for build ([d7ceabe](https://github.com/vitejs/vite/commit/d7ceabe92efe1c523ee05a6941e3f5042733b2bf)), closes [#1445](https://github.com/vitejs/vite/issues/1445) [#1452](https://github.com/vitejs/vite/issues/1452) + + +### Features + +* allow tag injection after body open (body-prepend) ([#1435](https://github.com/vitejs/vite/issues/1435)) ([432487e](https://github.com/vitejs/vite/commit/432487e24cb8688c86502e3b4e284e25c81b7dd8)) + + + +# [2.0.0-beta.15](https://github.com/vitejs/vite/compare/v2.0.0-beta.14...v2.0.0-beta.15) (2021-01-09) + + +### Bug Fixes + +* **hmr:** ensure all modules are fetched as import ([98bc767](https://github.com/vitejs/vite/commit/98bc7675a0f515ec6a908c6f18b2947a4a117836)) + + + +# [2.0.0-beta.14](https://github.com/vitejs/vite/compare/v2.0.0-beta.13...v2.0.0-beta.14) (2021-01-09) + + +### Features + +* support ../ paths in glob import ([7f399e1](https://github.com/vitejs/vite/commit/7f399e1a628240fdcd866cddc45c5522b07fd7f6)) + + + +# [2.0.0-beta.13](https://github.com/vitejs/vite/compare/v2.0.0-beta.12...v2.0.0-beta.13) (2021-01-09) + + +### Bug Fixes + +* always rebase path against root ([d704b7c](https://github.com/vitejs/vite/commit/d704b7c55fcbf347b5277a1d92dee4cc9583bab5)), closes [#1413](https://github.com/vitejs/vite/issues/1413) +* handle potential imports that has no correspodning chunks ([d47e10c](https://github.com/vitejs/vite/commit/d47e10c77d642b0446cb6ea1d5fd5a33346e9391)) +* raw fetch requests should not be transformed ([0356c3c](https://github.com/vitejs/vite/commit/0356c3c5193a5aeb8586e5588c8c873df7a1a427)), closes [#1433](https://github.com/vitejs/vite/issues/1433) +* skip cjs rewrite for export * declarations ([cca015b](https://github.com/vitejs/vite/commit/cca015b1c46fff41e047a92430937f31df5e6dfb)), closes [#1439](https://github.com/vitejs/vite/issues/1439) +* **cli:** fix help for --root ([#1429](https://github.com/vitejs/vite/issues/1429)) ([7a55c5b](https://github.com/vitejs/vite/commit/7a55c5be36a6d04a5a1e434147f4208c4a64c492)) +* **dev:** decode url before `sirv` resolve ([#1432](https://github.com/vitejs/vite/issues/1432)) ([7cc3cf1](https://github.com/vitejs/vite/commit/7cc3cf1044594297320ed62e1b38b27883f3f6c0)), closes [#1426](https://github.com/vitejs/vite/issues/1426) + + +### Features + +* allow user define to overwrite default process.env. defines ([351ad4e](https://github.com/vitejs/vite/commit/351ad4ee56d46eb8837b6a90af19ef953e3fe28b)) +* build support for data uri import ([4fd0b86](https://github.com/vitejs/vite/commit/4fd0b8615ef5ecff704ed44cadece613368cf18b)) +* support import "glob:./*" ([8d8e2cc](https://github.com/vitejs/vite/commit/8d8e2cc9ea0e1cc8f620c0a9d143294c1efb37b0)) + + + +# [2.0.0-beta.12](https://github.com/vitejs/vite/compare/v2.0.0-beta.11...v2.0.0-beta.12) (2021-01-07) + + +### Bug Fixes + +* **plugin-legacy:** avoid esbuild transform on legacy chunks ([7734105](https://github.com/vitejs/vite/commit/7734105093c6dabf64da6bfc11486aa9ac62efea)) + + + +# [2.0.0-beta.11](https://github.com/vitejs/vite/compare/v2.0.0-beta.10...v2.0.0-beta.11) (2021-01-07) + + +### Bug Fixes + +* preserve html comments during dev ([b295400](https://github.com/vitejs/vite/commit/b2954009f48da0a0d3202eee802e51eb7a1fb6c5)), closes [#1420](https://github.com/vitejs/vite/issues/1420) +* **resolve:** respect exports env key order ([b58c860](https://github.com/vitejs/vite/commit/b58c860f1771deecb78e126dfe8b6f663bd5e7c9)), closes [#1418](https://github.com/vitejs/vite/issues/1418) +* avoid excessive quote in css public urls ([1437129](https://github.com/vitejs/vite/commit/1437129541b36c0453fcecb1f1d44b574cc3326f)), closes [#1399](https://github.com/vitejs/vite/issues/1399) +* do not rewrite dynamic import if format is not native es ([eb35bd5](https://github.com/vitejs/vite/commit/eb35bd546333f4edea94607d05581b887b2ce9b6)) +* esbuild transform should filter id with and wihtout query ([4cda5be](https://github.com/vitejs/vite/commit/4cda5beb9f62c766dc8a8ab5d7b17704355348fc)) +* fix cache invalidation for non-optimized deps with cross imports ([11c407a](https://github.com/vitejs/vite/commit/11c407a085e9facd810914a5d4256946c11a1ca9)), closes [#1401](https://github.com/vitejs/vite/issues/1401) +* html transform should not render boolean attr with false value ([a59ffef](https://github.com/vitejs/vite/commit/a59ffefe1087a45cc4c13ab9e15e1d43ccac114a)) +* remove vue from optimize ignore list ([9eab790](https://github.com/vitejs/vite/commit/9eab79088079e95fb32f458a4bf573af7618bec6)), closes [#1408](https://github.com/vitejs/vite/issues/1408) +* support serving extension-less files in /public ([a7bca9c](https://github.com/vitejs/vite/commit/a7bca9c324db280ad3fa8255a36dee838a29255b)), closes [#1364](https://github.com/vitejs/vite/issues/1364) +* **build:** inline quotes css url to base64 ([#1412](https://github.com/vitejs/vite/issues/1412)) ([9b5b352](https://github.com/vitejs/vite/commit/9b5b3526de3288fc5d0e0a40fd80378db24674a1)), closes [#1409](https://github.com/vitejs/vite/issues/1409) [#1413](https://github.com/vitejs/vite/issues/1413) + + +### Code Refactoring + +* pass `configFile` via inline config instead of extra arg in most ([24b3b5a](https://github.com/vitejs/vite/commit/24b3b5a4e4402543d45bd8e3e4ff9ff26c09d7cb)) + + +### Features + +* support specifying mode in user config ([396bbf8](https://github.com/vitejs/vite/commit/396bbf8c869b23360a39bc4d99b760e25645c84b)), closes [#1380](https://github.com/vitejs/vite/issues/1380) +* **plugin-legacy:** @vitejs/plugin-legacy ([8c34870](https://github.com/vitejs/vite/commit/8c34870040f8c2f4be7d00245a3683f9e64d894e)) +* **proxy:** add rewrite support for ws ([#1407](https://github.com/vitejs/vite/issues/1407)) ([fa3bc34](https://github.com/vitejs/vite/commit/fa3bc34e23e757d57ca42e66c41dc8e712ae5547)) +* also expose correspodning chunk in build html transform ([b2f4836](https://github.com/vitejs/vite/commit/b2f4836ea83d7ba86c2ef3a082773d5045f2e7d9)) +* expose loadConfigFromFile API ([#1403](https://github.com/vitejs/vite/issues/1403)) ([9582171](https://github.com/vitejs/vite/commit/958217177c3173b7e5dec7f29048a2e83168649b)) + + +### BREAKING CHANGES + +* the following JavaScript APIs now expect `configFile` +as a property of the config object passed in instead of an argument: + + - `createServer` + - `build` + - `resolveConfig` + + + +# [2.0.0-beta.10](https://github.com/vitejs/vite/compare/v2.0.0-beta.9...v2.0.0-beta.10) (2021-01-06) + + +### Bug Fixes + +* **alias:** normalize alias behavior when there is ending slash ([c4739a3](https://github.com/vitejs/vite/commit/c4739a3f6d341db220cc5732857cf194c7cecc0d)), closes [#1363](https://github.com/vitejs/vite/issues/1363) +* **build:** Pass `allowNodeBuiltins` to rollup instead of empty array (Fixes [#1392](https://github.com/vitejs/vite/issues/1392)) ([#1393](https://github.com/vitejs/vite/issues/1393)) ([f209ad9](https://github.com/vitejs/vite/commit/f209ad9c858235ea317db6beb3bf2ab5ec26c153)) +* avoid replacing process.env member expression ([c8f4bb9](https://github.com/vitejs/vite/commit/c8f4bb92337c8882f238ea395f169af96a59d2ae)), closes [#930](https://github.com/vitejs/vite/issues/930) + + + +# [2.0.0-beta.9](https://github.com/vitejs/vite/compare/v2.0.0-beta.8...v2.0.0-beta.9) (2021-01-06) + + +### Bug Fixes + +* properly handle browser: false resolving ([da09320](https://github.com/vitejs/vite/commit/da09320e3671dbf08a5f8c4a78bd273f75fdcd7d)), closes [#1386](https://github.com/vitejs/vite/issues/1386) +* properly handle ts worker source ([eea1224](https://github.com/vitejs/vite/commit/eea122434740a60d353df54cb4dc108e29d4ef87)), closes [#1385](https://github.com/vitejs/vite/issues/1385) + + +### Features + +* **env:** also expose VITE_ variables from actual env ([956cd2c](https://github.com/vitejs/vite/commit/956cd2c76e69ba046f51a36af8e44ae9fb3a67ab)) + + + +# [2.0.0-beta.8](https://github.com/vitejs/vite/compare/v2.0.0-beta.7...v2.0.0-beta.8) (2021-01-05) + + +### Bug Fixes + +* **resolve:** handle exports field w/ mapped directory ([724aa8a](https://github.com/vitejs/vite/commit/724aa8a5fcb0ccaea283b3bf065d29ebf2cdf5a2)) + + +### Features + +* **build:** default build target to 'modules' with dynamic import polyfill ([756e90f](https://github.com/vitejs/vite/commit/756e90ff9b7d0b838ac3a2d7a20c36c801f72d8c)) +* allow boolean attr values in html transform tag descriptors ([#1381](https://github.com/vitejs/vite/issues/1381)) ([0fad96e](https://github.com/vitejs/vite/commit/0fad96e5cbff48efd3a13bb27580de894e1ec728)) + + + +# [2.0.0-beta.7](https://github.com/vitejs/vite/compare/v2.0.0-beta.6...v2.0.0-beta.7) (2021-01-05) + + +### Code Refactoring + +* update client type usage ([245303c](https://github.com/vitejs/vite/commit/245303ca35ff2a40eca49e102b4f82cb1210f597)) + + +### BREAKING CHANGES + +* client types are now exposed under `vite/client.d.ts`. +It can now be included via the following `tsconfig.json`: + + ```ts + { + "compilerOptions": { + "types": ["vite/client"] + } + } + ``` + + + +# [2.0.0-beta.6](https://github.com/vitejs/vite/compare/v2.0.0-beta.5...v2.0.0-beta.6) (2021-01-05) + + +### Bug Fixes + +* **css:** ensure options for .styl ([b3237ff](https://github.com/vitejs/vite/commit/b3237fff697b4b8b0e10adc9e0041f64c33fbc2d)), closes [#1351](https://github.com/vitejs/vite/issues/1351) +* **error-handling:** avoid serilaizing unnecessary error properties when seinding to client ([61aec65](https://github.com/vitejs/vite/commit/61aec651b470d5b97f2340a1b692b82cfe0c8ba5)), closes [#1373](https://github.com/vitejs/vite/issues/1373) +* **optimizer:** optimizer should not be affected by config rollup options ([ba08310](https://github.com/vitejs/vite/commit/ba08310b9e82668670af8a95e889e7cb68388e84)), closes [#1372](https://github.com/vitejs/vite/issues/1372) +* support aliases in html references ([68eac64](https://github.com/vitejs/vite/commit/68eac643f907fb4d57bd25925a342692441b1d97)), closes [#1363](https://github.com/vitejs/vite/issues/1363) +* **optimizer:** resolve linked dep from relative root ([#1375](https://github.com/vitejs/vite/issues/1375)) ([034bbcd](https://github.com/vitejs/vite/commit/034bbcd1738426d89e6c942f27dd1ccc8ede3990)) + + +### Code Refactoring + +* remove the need for specifying `transformInclude` ([99522d0](https://github.com/vitejs/vite/commit/99522d0edf06da4b8519c209f5f928cdf2951105)) + + +### Features + +* exclude vue from optimization ([1046fe0](https://github.com/vitejs/vite/commit/1046fe008b3288633bf8b38efdc2401a5ad2bf47)) +* improve import analysis fail warning ([2b39fce](https://github.com/vitejs/vite/commit/2b39fce9450dc0d8bc99b06a6d757f4e48193001)), closes [#1368](https://github.com/vitejs/vite/issues/1368) + + +### BREAKING CHANGES + +* `transformInclude` option has been removed and is no +longer necessary. This allows full dynamic imports to custom file types +to automatically qualify for the transform pipeline. + + - All requests that accept `*/*` AND is not declared an asset type + will now qualify for the transform pipeline. + + - To exclude an asset type from being transformed when requested + directly, declare it as asset via `config.assetsInclude`. + + + +# [2.0.0-beta.5](https://github.com/vitejs/vite/compare/v2.0.0-beta.4...v2.0.0-beta.5) (2021-01-05) + + +### Bug Fixes + +* only append dep version query for known types ([42cd8b2](https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443)) +* **css:** fix css comment removal ([7b9dee0](https://github.com/vitejs/vite/commit/7b9dee020785022acaa8e6989dcb2cc7ec03c3f2)), closes [#1359](https://github.com/vitejs/vite/issues/1359) +* **css:** inline css in all non-entry split chunks ([e90ff76](https://github.com/vitejs/vite/commit/e90ff76d1c6d5ad1d079c953ba4fbfc84be73185)), closes [#1356](https://github.com/vitejs/vite/issues/1356) +* do not bundle resolve for yarn 2 compat ([3524e96](https://github.com/vitejs/vite/commit/3524e96da0de59e5dddf2210dc78e2a1de3f07e0)), closes [#1353](https://github.com/vitejs/vite/issues/1353) +* do not error on unresolved commonjs externals ([60a4708](https://github.com/vitejs/vite/commit/60a470880034fcd7e54c15b4cf92f738b973a3df)), closes [#1339](https://github.com/vitejs/vite/issues/1339) +* only allow built-ins as externals if building for ssr ([804c9a3](https://github.com/vitejs/vite/commit/804c9a30e673386c419a0582d0da11f805c285c4)) +* run mutiple output builds sequantially ([ab80522](https://github.com/vitejs/vite/commit/ab805228e55bd79275b6ac67b0408419a8ab5c70)) + + +### Features + +* **types:** separate client type shims from main types ([0cddbbc](https://github.com/vitejs/vite/commit/0cddbbc4bfc8e85329ba710117b9aec1d67d318d)) +* default clean-css level to 1 + expose options ([ef100d0](https://github.com/vitejs/vite/commit/ef100d09cbd1c6745108afc2877396fe69b08bdd)), closes [#936](https://github.com/vitejs/vite/issues/936) +* support plugin.apply ([d914b54](https://github.com/vitejs/vite/commit/d914b542450cd7b4bbeb057a0fee8f79efd2bb9d)) + + + +# [2.0.0-beta.4](https://github.com/vitejs/vite/compare/v2.0.0-beta.3...v2.0.0-beta.4) (2021-01-04) + + +### Bug Fixes + +* stop service in build esbuild plugin as well ([1a90b4e](https://github.com/vitejs/vite/commit/1a90b4e50250c4011a058e9e121b7b80caff888e)) +* **build:** rollup import resolving message ([#1336](https://github.com/vitejs/vite/issues/1336)) [skip ci] ([87d55f4](https://github.com/vitejs/vite/commit/87d55f43e90edb36c2f0d49d71ffadd20f82e97a)) +* **resolve:** always prioritize browser field ([409988f](https://github.com/vitejs/vite/commit/409988fbbb5d854ccbbae0dd81f757eb42e24c40)) +* [@fs](https://github.com/fs) paths resolving for win32 ([#1317](https://github.com/vitejs/vite/issues/1317)) ([0a94c88](https://github.com/vitejs/vite/commit/0a94c88238f265a14c116c2f1306d3be74b182e6)) +* do not error on css deep imports ([25adf1e](https://github.com/vitejs/vite/commit/25adf1eefaf6817f9443365f5ee3fcf0d63ffd6f)) +* ensure consistent module entry urls by removing import query ([2b82e84](https://github.com/vitejs/vite/commit/2b82e84a272db2a4269d742dd7b9a8a1ad8351dd)), closes [#1321](https://github.com/vitejs/vite/issues/1321) +* load source map from sourceMappingURL comment ([#1327](https://github.com/vitejs/vite/issues/1327)) ([1f89b0e](https://github.com/vitejs/vite/commit/1f89b0e704d4315246836d2cd7faf3cdcdf89dd9)) +* sourcemap path mangled by browser ([#1326](https://github.com/vitejs/vite/issues/1326)) ([1da12ba](https://github.com/vitejs/vite/commit/1da12baf00ab8e7c3366f9c0e088c09cce903934)), closes [#1323](https://github.com/vitejs/vite/issues/1323) +* **dev:** display localetime correctly ([#1310](https://github.com/vitejs/vite/issues/1310)) ([06663a7](https://github.com/vitejs/vite/commit/06663a7e7825bedd61593d299f00110f6ac40916)) + + +### Features + +* esbuild.(include|exclude|jsxInject) ([b5b1496](https://github.com/vitejs/vite/commit/b5b14962b53d8dcbae850b9eb6abf2ca5820b3db)) +* **wasm:** use `instantiateStreaming` when available ([#1330](https://github.com/vitejs/vite/issues/1330)) ([2286f62](https://github.com/vitejs/vite/commit/2286f629ab6d96fb0b90c9825582962bf8f0f2a5)), closes [#1143](https://github.com/vitejs/vite/issues/1143) +* export normalizePath helper ([#1313](https://github.com/vitejs/vite/issues/1313)) ([37d1a5d](https://github.com/vitejs/vite/commit/37d1a5de019cfd5db397f5c8e0365222950c1dff)) + + + +# [2.0.0-beta.3](https://github.com/vitejs/vite/compare/v2.0.0-beta.2...v2.0.0-beta.3) (2021-01-03) + + +### Bug Fixes + +* **build:** fix import-fresh shim ([b57d74c](https://github.com/vitejs/vite/commit/b57d74c2b72498aee251ed7ed45ff046a98d5499)), closes [#1306](https://github.com/vitejs/vite/issues/1306) +* decode incoming URL ([f52db58](https://github.com/vitejs/vite/commit/f52db5898dfb1eecb4b3427a73ffd7ecd2ac15d6)), closes [#1308](https://github.com/vitejs/vite/issues/1308) +* keep `this` defined in `configureServer` hook ([#1304](https://github.com/vitejs/vite/issues/1304)) ([b665b92](https://github.com/vitejs/vite/commit/b665b92323521475a568f8c5204a83c0e80a6b75)) +* **resolve:** prioritize module + avoid mutating path when ([6ce6d5c](https://github.com/vitejs/vite/commit/6ce6d5c2908c20b8308725a5f91f5a618aa09d8a)), closes [#1299](https://github.com/vitejs/vite/issues/1299) + + +### Features + +* dedupe option ([7858e62](https://github.com/vitejs/vite/commit/7858e629273269ca2aedf9891d560521a4bd0c8d)), closes [#1302](https://github.com/vitejs/vite/issues/1302) +* export `resolvePackageData` and `resolvePackageEntry` helpers ([#1307](https://github.com/vitejs/vite/issues/1307)) ([38b9613](https://github.com/vitejs/vite/commit/38b9613832d1af569ca5aba4226895f0bd7897a0)) +* expose `loadEnv` in public api ([#1300](https://github.com/vitejs/vite/issues/1300)) ([9d0a8e7](https://github.com/vitejs/vite/commit/9d0a8e74d1553c8c9108caeaf0c22cd938a502c7)) + + + +# [2.0.0-beta.2](https://github.com/vitejs/vite/compare/v2.0.0-beta.1...v2.0.0-beta.2) (2021-01-02) + + +### Bug Fixes + +* do not attempt to transform html requests ([a7a5c5b](https://github.com/vitejs/vite/commit/a7a5c5bbd9d26e46fb3a175c80bd898cdfce5572)) +* fix spa fallback on paths ending with slash ([60fe476](https://github.com/vitejs/vite/commit/60fe476638930702fb94f906afcf6d1dc4dfab7b)) +* **resolve:** prioritize browser field ([dfef3de](https://github.com/vitejs/vite/commit/dfef3de9a5875c238d9a795a461e47634db9809f)), closes [#1154](https://github.com/vitejs/vite/issues/1154) +* **resolve:** resolve inline package ([e27fe30](https://github.com/vitejs/vite/commit/e27fe30e7920d22f4ad786e5bfb14415d73cc2cc)), closes [#1291](https://github.com/vitejs/vite/issues/1291) +* dynamic load postcss plugin ([#1292](https://github.com/vitejs/vite/issues/1292)) ([00c7370](https://github.com/vitejs/vite/commit/00c737024a72ab3e2c5c17f74b2bf28c5b0d158f)), closes [#1287](https://github.com/vitejs/vite/issues/1287) +* fix transform result check for empty result ([2adfa8b](https://github.com/vitejs/vite/commit/2adfa8b1bdc01297a030f8cb3066df7f7a753d3c)), closes [#1278](https://github.com/vitejs/vite/issues/1278) + + +### Code Refactoring + +* **hmr:** pass context object to `handleHotUpdate` plugin hook ([b314771](https://github.com/vitejs/vite/commit/b3147710e96a8f88ab81b2e45dbf7e7174ad976c)) + + +### Reverts + +* Revert "types: worker types" (#1295) ([806ef96](https://github.com/vitejs/vite/commit/806ef9697069db581eaa2c1721db5d3e08707a7d)), closes [#1295](https://github.com/vitejs/vite/issues/1295) + + +### BREAKING CHANGES + +* **hmr:** `handleHotUpdate` plugin hook now receives a single +`HmrContext` argument instead of multiple args. + + + +# [2.0.0-beta.1](https://github.com/vitejs/vite/compare/v2.0.0-alpha.5...v2.0.0-beta.1) (2021-01-02) + + +### Bug Fixes + +* --open and --filter arguments ([#1259](https://github.com/vitejs/vite/issues/1259)) ([0c0bc4a](https://github.com/vitejs/vite/commit/0c0bc4a33c99da22be96214af872344f930732d4)) +* handle hmr errors ([ff2b3ce](https://github.com/vitejs/vite/commit/ff2b3cef01750c3cb33d39dc726317cbd832568b)) +* overlay z-index ([6b3278e](https://github.com/vitejs/vite/commit/6b3278eff8702c45bd8dbace35baca337fb89682)) +* **css:** respect minify option for chunk css ([6a287a1](https://github.com/vitejs/vite/commit/6a287a176dd4be6e290d3be0490e39b92916a0d0)) + + +### Features + +* also call buildEnd on container close ([94a8def](https://github.com/vitejs/vite/commit/94a8def3bcc673c00ff56f9d19b9933c6426c605)) +* provide default typing for supported file types ([a9c7eac](https://github.com/vitejs/vite/commit/a9c7eaca1cf8ab0f590bb605da49fd4daa766244)) +* support resolveId returning arbitrary value ([b782af4](https://github.com/vitejs/vite/commit/b782af44cc968cc4f18ef0722302991406fa82de)) + + + +# [2.0.0-alpha.5](https://github.com/vitejs/vite/compare/v2.0.0-alpha.4...v2.0.0-alpha.5) (2020-12-30) + + +### Bug Fixes + +* **css:** properly prevent css from being tree-shaken ([7f08835](https://github.com/vitejs/vite/commit/7f088352894f3fcc06e6936917de4bb70b5763dc)) + + + +# [2.0.0-alpha.4](https://github.com/vitejs/vite/compare/v2.0.0-alpha.3...v2.0.0-alpha.4) (2020-12-30) + + +### Bug Fixes + +* **css:** fix cssCodeSplit: false ([9a02203](https://github.com/vitejs/vite/commit/9a0220304bd6bc655078b7705b95f3cfd1059e36)) +* disable cssCodeSplit by default in lib mode ([e64509a](https://github.com/vitejs/vite/commit/e64509a680fdb01ff25393f9c65f34ac87eb799a)) +* fix terser worker thread when vite is linked ([a28419b](https://github.com/vitejs/vite/commit/a28419bafc649192cdb6eca3f6014e3b823d1c0a)) +* inline assets in lib mode ([c976d10](https://github.com/vitejs/vite/commit/c976d10ac1e40f0c59bcb02c1016ed6f39563ca0)) + + + +# [2.0.0-alpha.3](https://github.com/vitejs/vite/compare/v2.0.0-alpha.2...v2.0.0-alpha.3) (2020-12-30) + + + +# [2.0.0-alpha.2](https://github.com/vitejs/vite/compare/v2.0.0-alpha.1...v2.0.0-alpha.2) (2020-12-29) + + +### Bug Fixes + +* **plugin-vue:** avoid throwing on never requested file ([48a24c1](https://github.com/vitejs/vite/commit/48a24c1fa1f64e89ca853635580911859ef5881b)) + + + +# [2.0.0-alpha.1](https://github.com/vitejs/vite/compare/v1.0.0-rc.13...v2.0.0-alpha.1) (2020-12-29) + +- [x] new universal plugin format +- [x] framework agnostic core +- [x] smaller and faster install +- [x] improved JS API +- [x] improved alias and resolving +- [x] improved page reload performance (strong caching of npm deps) +- [x] error overlay +- [x] better vue perf (single request in most cases) +- [x] multi entry mode +- [x] lib mode diff --git a/node_modules/vite/LICENSE.md b/node_modules/vite/LICENSE.md new file mode 100644 index 0000000..3e7a3c8 --- /dev/null +++ b/node_modules/vite/LICENSE.md @@ -0,0 +1,5210 @@ +# Vite core license +Vite is released under the MIT license: + +MIT License + +Copyright (c) 2019-present, Yuxi (Evan) You and Vite 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. + +# Licenses of bundled dependencies +The published Vite artifact additionally contains code with the following licenses: +Apache-2.0, BSD-2-Clause, BSD-3-Clause, CC0-1.0, ISC, MIT, (BSD-3-Clause OR GPL-2.0), (MIT) + +# Bundled dependencies: +## @ampproject/remapping +License: Apache-2.0 +By: Justin Ridgewell +Repository: git+https://github.com/ampproject/remapping.git + +> Apache License +> Version 2.0, January 2004 +> http://www.apache.org/licenses/ +> +> TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +> +> 1. Definitions. +> +> "License" shall mean the terms and conditions for use, reproduction, +> and distribution as defined by Sections 1 through 9 of this document. +> +> "Licensor" shall mean the copyright owner or entity authorized by +> the copyright owner that is granting the License. +> +> "Legal Entity" shall mean the union of the acting entity and all +> other entities that control, are controlled by, or are under common +> control with that entity. For the purposes of this definition, +> "control" means (i) the power, direct or indirect, to cause the +> direction or management of such entity, whether by contract or +> otherwise, or (ii) ownership of fifty percent (50%) or more of the +> outstanding shares, or (iii) beneficial ownership of such entity. +> +> "You" (or "Your") shall mean an individual or Legal Entity +> exercising permissions granted by this License. +> +> "Source" form shall mean the preferred form for making modifications, +> including but not limited to software source code, documentation +> source, and configuration files. +> +> "Object" form shall mean any form resulting from mechanical +> transformation or translation of a Source form, including but +> not limited to compiled object code, generated documentation, +> and conversions to other media types. +> +> "Work" shall mean the work of authorship, whether in Source or +> Object form, made available under the License, as indicated by a +> copyright notice that is included in or attached to the work +> (an example is provided in the Appendix below). +> +> "Derivative Works" shall mean any work, whether in Source or Object +> form, that is based on (or derived from) the Work and for which the +> editorial revisions, annotations, elaborations, or other modifications +> represent, as a whole, an original work of authorship. For the purposes +> of this License, Derivative Works shall not include works that remain +> separable from, or merely link (or bind by name) to the interfaces of, +> the Work and Derivative Works thereof. +> +> "Contribution" shall mean any work of authorship, including +> the original version of the Work and any modifications or additions +> to that Work or Derivative Works thereof, that is intentionally +> submitted to Licensor for inclusion in the Work by the copyright owner +> or by an individual or Legal Entity authorized to submit on behalf of +> the copyright owner. For the purposes of this definition, "submitted" +> means any form of electronic, verbal, or written communication sent +> to the Licensor or its representatives, including but not limited to +> communication on electronic mailing lists, source code control systems, +> and issue tracking systems that are managed by, or on behalf of, the +> Licensor for the purpose of discussing and improving the Work, but +> excluding communication that is conspicuously marked or otherwise +> designated in writing by the copyright owner as "Not a Contribution." +> +> "Contributor" shall mean Licensor and any individual or Legal Entity +> on behalf of whom a Contribution has been received by Licensor and +> subsequently incorporated within the Work. +> +> 2. Grant of Copyright License. Subject to the terms and conditions of +> this License, each Contributor hereby grants to You a perpetual, +> worldwide, non-exclusive, no-charge, royalty-free, irrevocable +> copyright license to reproduce, prepare Derivative Works of, +> publicly display, publicly perform, sublicense, and distribute the +> Work and such Derivative Works in Source or Object form. +> +> 3. Grant of Patent License. Subject to the terms and conditions of +> this License, each Contributor hereby grants to You a perpetual, +> worldwide, non-exclusive, no-charge, royalty-free, irrevocable +> (except as stated in this section) patent license to make, have made, +> use, offer to sell, sell, import, and otherwise transfer the Work, +> where such license applies only to those patent claims licensable +> by such Contributor that are necessarily infringed by their +> Contribution(s) alone or by combination of their Contribution(s) +> with the Work to which such Contribution(s) was submitted. If You +> institute patent litigation against any entity (including a +> cross-claim or counterclaim in a lawsuit) alleging that the Work +> or a Contribution incorporated within the Work constitutes direct +> or contributory patent infringement, then any patent licenses +> granted to You under this License for that Work shall terminate +> as of the date such litigation is filed. +> +> 4. Redistribution. You may reproduce and distribute copies of the +> Work or Derivative Works thereof in any medium, with or without +> modifications, and in Source or Object form, provided that You +> meet the following conditions: +> +> (a) You must give any other recipients of the Work or +> Derivative Works a copy of this License; and +> +> (b) You must cause any modified files to carry prominent notices +> stating that You changed the files; and +> +> (c) You must retain, in the Source form of any Derivative Works +> that You distribute, all copyright, patent, trademark, and +> attribution notices from the Source form of the Work, +> excluding those notices that do not pertain to any part of +> the Derivative Works; and +> +> (d) If the Work includes a "NOTICE" text file as part of its +> distribution, then any Derivative Works that You distribute must +> include a readable copy of the attribution notices contained +> within such NOTICE file, excluding those notices that do not +> pertain to any part of the Derivative Works, in at least one +> of the following places: within a NOTICE text file distributed +> as part of the Derivative Works; within the Source form or +> documentation, if provided along with the Derivative Works; or, +> within a display generated by the Derivative Works, if and +> wherever such third-party notices normally appear. The contents +> of the NOTICE file are for informational purposes only and +> do not modify the License. You may add Your own attribution +> notices within Derivative Works that You distribute, alongside +> or as an addendum to the NOTICE text from the Work, provided +> that such additional attribution notices cannot be construed +> as modifying the License. +> +> You may add Your own copyright statement to Your modifications and +> may provide additional or different license terms and conditions +> for use, reproduction, or distribution of Your modifications, or +> for any such Derivative Works as a whole, provided Your use, +> reproduction, and distribution of the Work otherwise complies with +> the conditions stated in this License. +> +> 5. Submission of Contributions. Unless You explicitly state otherwise, +> any Contribution intentionally submitted for inclusion in the Work +> by You to the Licensor shall be under the terms and conditions of +> this License, without any additional terms or conditions. +> Notwithstanding the above, nothing herein shall supersede or modify +> the terms of any separate license agreement you may have executed +> with Licensor regarding such Contributions. +> +> 6. Trademarks. This License does not grant permission to use the trade +> names, trademarks, service marks, or product names of the Licensor, +> except as required for reasonable and customary use in describing the +> origin of the Work and reproducing the content of the NOTICE file. +> +> 7. Disclaimer of Warranty. Unless required by applicable law or +> agreed to in writing, Licensor provides the Work (and each +> Contributor provides its Contributions) on an "AS IS" BASIS, +> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +> implied, including, without limitation, any warranties or conditions +> of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +> PARTICULAR PURPOSE. You are solely responsible for determining the +> appropriateness of using or redistributing the Work and assume any +> risks associated with Your exercise of permissions under this License. +> +> 8. Limitation of Liability. In no event and under no legal theory, +> whether in tort (including negligence), contract, or otherwise, +> unless required by applicable law (such as deliberate and grossly +> negligent acts) or agreed to in writing, shall any Contributor be +> liable to You for damages, including any direct, indirect, special, +> incidental, or consequential damages of any character arising as a +> result of this License or out of the use or inability to use the +> Work (including but not limited to damages for loss of goodwill, +> work stoppage, computer failure or malfunction, or any and all +> other commercial damages or losses), even if such Contributor +> has been advised of the possibility of such damages. +> +> 9. Accepting Warranty or Additional Liability. While redistributing +> the Work or Derivative Works thereof, You may choose to offer, +> and charge a fee for, acceptance of support, warranty, indemnity, +> or other liability obligations and/or rights consistent with this +> License. However, in accepting such obligations, You may act only +> on Your own behalf and on Your sole responsibility, not on behalf +> of any other Contributor, and only if You agree to indemnify, +> defend, and hold each Contributor harmless for any liability +> incurred by, or claims asserted against, such Contributor by reason +> of your accepting any such warranty or additional liability. +> +> END OF TERMS AND CONDITIONS +> +> APPENDIX: How to apply the Apache License to your work. +> +> To apply the Apache License to your work, attach the following +> boilerplate notice, with the fields enclosed by brackets "[]" +> replaced with your own identifying information. (Don't include +> the brackets!) The text should be enclosed in the appropriate +> comment syntax for the file format. We also recommend that a +> file or class name and description of purpose be included on the +> same "printed page" as the copyright notice for easier +> identification within third-party archives. +> +> Copyright 2019 Google LLC +> +> Licensed under the Apache License, Version 2.0 (the "License"); +> you may not use this file except in compliance with the License. +> You may obtain a copy of the License at +> +> http://www.apache.org/licenses/LICENSE-2.0 +> +> Unless required by applicable law or agreed to in writing, software +> distributed under the License is distributed on an "AS IS" BASIS, +> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +> See the License for the specific language governing permissions and +> limitations under the License. + +--------------------------------------- + +## @babel/helper-validator-identifier +License: MIT +By: The Babel Team +Repository: https://github.com/babel/babel.git + +> MIT License +> +> Copyright (c) 2014-present Sebastian McKenzie and other contributors +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> "Software"), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## @babel/types +License: MIT +By: The Babel Team +Repository: https://github.com/babel/babel.git + +> MIT License +> +> Copyright (c) 2014-present Sebastian McKenzie and other contributors +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> "Software"), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## @cspotcode/source-map-consumer +License: BSD-3-Clause +By: Andrew Bradley, Nick Fitzgerald, Tobias Koppers, Duncan Beevers, Stephen Crane, Ryan Seddon, Miles Elam, Mihai Bazon, Michael Ficarra, Todd Wolfson, Alexander Solovyov, Felix Gnass, Conrad Irwin, usrbincc, David Glasser, Chase Douglas, Evan Wallace, Heather Arthur, Hugh Kennedy, Simon Lydell, Jmeas Smith, Michael Z Goddard, azu, John Gozde, Adam Kirkton, Chris Montgomery, J. Ryan Stinnett, Jack Herrington, Chris Truter, Daniel Espeset, Jamie Wong, Eddy Bruël, Hawken Rives, Gilad Peleg, djchie, Gary Ye, Nicolas Lalevée +Repository: http://github.com/cspotcode/source-map.git + +--------------------------------------- + +## @cspotcode/source-map-support +License: MIT +Repository: https://github.com/cspotcode/node-source-map-support + +> The MIT License (MIT) +> +> Copyright (c) 2014 Evan Wallace +> +> 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. + +--------------------------------------- + +## @nodelib/fs.scandir +License: MIT +Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.scandir + +> The MIT License (MIT) +> +> Copyright (c) Denis Malinochkin +> +> 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. + +--------------------------------------- + +## @nodelib/fs.stat +License: MIT +Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.stat + +> The MIT License (MIT) +> +> Copyright (c) Denis Malinochkin +> +> 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. + +--------------------------------------- + +## @nodelib/fs.walk +License: MIT +Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.walk + +> The MIT License (MIT) +> +> Copyright (c) Denis Malinochkin +> +> 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. + +--------------------------------------- + +## @polka/url +License: MIT +By: Luke Edwards +Repository: lukeed/polka + +> The MIT License (MIT) +> +> Copyright (c) Luke Edwards (https://lukeed.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. + +--------------------------------------- + +## @rollup/plugin-alias +License: MIT +By: Johannes Stein +Repository: rollup/plugins + +--------------------------------------- + +## @rollup/plugin-commonjs +License: MIT +By: Rich Harris +Repository: rollup/plugins + +> The MIT License (MIT) +> +> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## @rollup/plugin-dynamic-import-vars +License: MIT +By: LarsDenBakker +Repository: rollup/plugins + +--------------------------------------- + +## @rollup/pluginutils +License: MIT +By: Rich Harris +Repository: rollup/plugins + +--------------------------------------- + +## @tsconfig/node10 +License: MIT +Repository: https://github.com/tsconfig/bases.git + +> MIT License +> +> Copyright (c) Microsoft Corporation. +> +> 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 + +--------------------------------------- + +## @tsconfig/node12 +License: MIT +Repository: https://github.com/tsconfig/bases.git + +> MIT License +> +> Copyright (c) Microsoft Corporation. +> +> 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 + +--------------------------------------- + +## @tsconfig/node14 +License: MIT +Repository: https://github.com/tsconfig/bases.git + +> MIT License +> +> Copyright (c) Microsoft Corporation. +> +> 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 + +--------------------------------------- + +## @tsconfig/node16 +License: MIT +Repository: https://github.com/tsconfig/bases.git + +> MIT License +> +> Copyright (c) Microsoft Corporation. +> +> 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 + +--------------------------------------- + +## @vue/compiler-core +License: MIT +By: Evan You +Repository: git+https://github.com/vuejs/vue-next.git + +> The MIT License (MIT) +> +> Copyright (c) 2018-present, Yuxi (Evan) You +> +> 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. + +--------------------------------------- + +## @vue/compiler-dom +License: MIT +By: Evan You +Repository: git+https://github.com/vuejs/vue-next.git + +> The MIT License (MIT) +> +> Copyright (c) 2018-present, Yuxi (Evan) You +> +> 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. + +--------------------------------------- + +## @vue/shared +License: MIT +By: Evan You +Repository: git+https://github.com/vuejs/vue-next.git + +> The MIT License (MIT) +> +> Copyright (c) 2018-present, Yuxi (Evan) You +> +> 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. + +--------------------------------------- + +## accepts +License: MIT +By: Douglas Christopher Wilson, Jonathan Ong +Repository: jshttp/accepts + +> (The MIT License) +> +> Copyright (c) 2014 Jonathan Ong +> Copyright (c) 2015 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## acorn +License: MIT +By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine +Repository: https://github.com/acornjs/acorn.git + +> MIT License +> +> Copyright (C) 2012-2020 by various contributors (see AUTHORS) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## acorn-class-fields +License: MIT +By: Adrian Heine +Repository: https://github.com/acornjs/acorn-class-fields + +> Copyright (C) 2017-2018 by Adrian Heine +> +> 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. + +--------------------------------------- + +## acorn-numeric-separator +License: MIT +By: Adrian Heine +Repository: https://github.com/acornjs/acorn-numeric-separator + +> Copyright (C) 2017-2018 by Adrian Heine +> +> 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. + +--------------------------------------- + +## acorn-private-class-elements +License: MIT +By: Adrian Heine +Repository: https://github.com/acornjs/acorn-private-class-elements + +> Copyright (C) 2017-2018 by Adrian Heine +> +> 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. + +--------------------------------------- + +## acorn-static-class-features +License: MIT +By: Adrian Heine +Repository: https://github.com/acornjs/acorn-static-class-features + +> Copyright (C) 2017-2018 by Adrian Heine +> +> 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. + +--------------------------------------- + +## acorn-walk +License: MIT +By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine +Repository: https://github.com/acornjs/acorn.git + +> Copyright (C) 2012-2018 by various contributors (see AUTHORS) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## ansi-regex +License: MIT +By: Sindre Sorhus +Repository: chalk/ansi-regex + +> 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. + +--------------------------------------- + +## ansi-styles +License: MIT +By: Sindre Sorhus +Repository: chalk/ansi-styles + +> 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. + +--------------------------------------- + +## anymatch +License: ISC +By: Elan Shanker +Repository: https://github.com/micromatch/anymatch + +> The ISC License +> +> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) +> +> 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. + +--------------------------------------- + +## arg +License: MIT +By: Josh Junon +Repository: zeit/arg + +> MIT License +> +> Copyright (c) 2017-2019 Zeit, Inc. +> +> 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. + +--------------------------------------- + +## array-union +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/array-union + +> 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. + +--------------------------------------- + +## balanced-match +License: MIT +By: Julian Gruber +Repository: git://github.com/juliangruber/balanced-match.git + +> (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. + +--------------------------------------- + +## big.js +License: MIT +By: Michael Mclaughlin +Repository: https://github.com/MikeMcl/big.js.git + +--------------------------------------- + +## binary-extensions +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/binary-extensions + +> MIT License +> +> Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), 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: +> +> 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. + +--------------------------------------- + +## brace-expansion +License: MIT +By: Julian Gruber +Repository: git://github.com/juliangruber/brace-expansion.git + +> MIT License +> +> 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 +> 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. + +--------------------------------------- + +## braces +License: MIT +By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm +Repository: micromatch/braces + +> The MIT License (MIT) +> +> Copyright (c) 2014-2018, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## brotli-size +License: MIT +By: Erwin Mombay +Repository: erwinmombay/brotli-size + +> The MIT License (MIT) +> +> Copyright (c) Erwin Mombay +> +> 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. + +--------------------------------------- + +## builtin-modules +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/builtin-modules + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## bytes +License: MIT +By: TJ Holowaychuk, Jed Watson, Théo FIDRY +Repository: visionmedia/bytes.js + +> (The MIT License) +> +> Copyright (c) 2012-2014 TJ Holowaychuk +> Copyright (c) 2015 Jed Watson +> +> 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. + +--------------------------------------- + +## cac +License: MIT +By: egoist +Repository: egoist/cac + +> The MIT License (MIT) +> +> Copyright (c) EGOIST <0x142857@gmail.com> (https://github.com/egoist) +> +> 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. + +--------------------------------------- + +## chalk +License: MIT +Repository: chalk/chalk + +> 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. + +--------------------------------------- + +## chokidar +License: MIT +By: Paul Miller, Elan Shanker +Repository: git+https://github.com/paulmillr/chokidar.git + +> The MIT License (MIT) +> +> Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker +> +> 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. + +--------------------------------------- + +## color-convert +License: MIT +By: Heather Arthur +Repository: Qix-/color-convert + +> Copyright (c) 2011-2016 Heather Arthur +> +> 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. + +--------------------------------------- + +## color-name +License: MIT +By: DY +Repository: git@github.com:colorjs/color-name.git + +> 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. + +--------------------------------------- + +## commondir +License: MIT +By: James Halliday +Repository: http://github.com/substack/node-commondir.git + +> The MIT License +> +> Copyright (c) 2013 James Halliday (mail@substack.net) +> +> 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. + +--------------------------------------- + +## compressible +License: MIT +By: Douglas Christopher Wilson, Jonathan Ong, Jeremiah Senkpiel +Repository: jshttp/compressible + +> (The MIT License) +> +> Copyright (c) 2013 Jonathan Ong +> Copyright (c) 2014 Jeremiah Senkpiel +> Copyright (c) 2015 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## compression +License: MIT +By: Douglas Christopher Wilson, Jonathan Ong +Repository: expressjs/compression + +> (The MIT License) +> +> Copyright (c) 2014 Jonathan Ong +> Copyright (c) 2014-2015 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## concat-map +License: MIT +By: James Halliday +Repository: git://github.com/substack/node-concat-map.git + +> This software is released under the MIT license: +> +> 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. + +--------------------------------------- + +## connect +License: MIT +By: TJ Holowaychuk, Douglas Christopher Wilson, Jonathan Ong, Tim Caswell +Repository: senchalabs/connect + +> (The MIT License) +> +> Copyright (c) 2010 Sencha Inc. +> Copyright (c) 2011 LearnBoost +> Copyright (c) 2011-2014 TJ Holowaychuk +> Copyright (c) 2015 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## connect-history-api-fallback +License: MIT +By: Ben Ripkens, Craig Myles +Repository: http://github.com/bripkens/connect-history-api-fallback.git + +> The MIT License +> +> Copyright (c) 2012 Ben Ripkens http://bripkens.de +> +> 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. + +--------------------------------------- + +## convert-source-map +License: MIT +By: Thorsten Lorenz +Repository: git://github.com/thlorenz/convert-source-map.git + +> Copyright 2013 Thorsten Lorenz. +> 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. + +--------------------------------------- + +## cors +License: MIT +By: Troy Goode +Repository: expressjs/cors + +> (The MIT License) +> +> Copyright (c) 2013 Troy Goode +> +> 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. + +--------------------------------------- + +## create-require +License: MIT +By: Maël Nison, Paul Soporan, Pooya Parsa +Repository: nuxt-contrib/create-require + +> MIT License +> +> Copyright (c) 2020 +> +> Maël Nison +> Paul Soporan +> Pooya Parsa +> +> 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. + +--------------------------------------- + +## cross-spawn +License: MIT +By: André Cruz +Repository: git@github.com:moxystudio/node-cross-spawn.git + +> The MIT License (MIT) +> +> Copyright (c) 2018 Made With MOXY Lda +> +> 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. + +--------------------------------------- + +## cssesc +License: MIT +By: Mathias Bynens +Repository: https://github.com/mathiasbynens/cssesc.git + +> Copyright Mathias Bynens +> +> 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. + +--------------------------------------- + +## debug +License: MIT +By: TJ Holowaychuk, Nathan Rajlich, Andrew Rhyne, Josh Junon +Repository: git://github.com/visionmedia/debug.git + +> (The MIT License) +> +> Copyright (c) 2014 TJ Holowaychuk +> +> 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. + +--------------------------------------- + +## define-lazy-prop +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/define-lazy-prop + +> 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 +License: BSD-3-Clause +Repository: git://github.com/kpdecker/jsdiff.git + +> Software License Agreement (BSD License) +> +> Copyright (c) 2009-2015, Kevin Decker +> +> All rights reserved. +> +> Redistribution and use of this software in source and binary forms, with or without modification, +> are permitted provided that the following conditions are met: +> +> * Redistributions of source code must retain the above +> copyright notice, this list of conditions and the +> following disclaimer. +> +> * Redistributions in binary form must reproduce the above +> copyright notice, this list of conditions and the +> following disclaimer in the documentation and/or other +> materials provided with the distribution. +> +> * Neither the name of Kevin Decker nor the names of its +> contributors may be used to endorse or promote products +> derived from this software without specific prior +> written permission. +> +> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +> IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +> FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +> CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +> DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +> IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +> OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------- + +## dir-glob +License: MIT +By: Kevin Mårtensson +Repository: kevva/dir-glob + +> MIT License +> +> Copyright (c) Kevin Mårtensson (github.com/kevva) +> +> 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. + +--------------------------------------- + +## dotenv +License: BSD-2-Clause +Repository: git://github.com/motdotla/dotenv.git + +> Copyright (c) 2015, Scott Motte +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without +> modification, are permitted provided that the following conditions are met: +> +> * Redistributions of source code must retain the above copyright notice, this +> list of conditions and the following disclaimer. +> +> * Redistributions in binary form must reproduce the above copyright notice, +> this list of conditions and the following disclaimer in the documentation +> and/or other materials provided with the distribution. +> +> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------- + +## dotenv-expand +License: BSD-2-Clause +By: motdotla + +> Copyright (c) 2016, Scott Motte +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without +> modification, are permitted provided that the following conditions are met: +> +> * Redistributions of source code must retain the above copyright notice, this +> list of conditions and the following disclaimer. +> +> * Redistributions in binary form must reproduce the above copyright notice, +> this list of conditions and the following disclaimer in the documentation +> and/or other materials provided with the distribution. +> +> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------- + +## duplexer +License: (MIT) +By: Raynos, Jake Verbaten +Repository: git://github.com/Raynos/duplexer.git + +--------------------------------------- + +## ee-first +License: MIT +By: Jonathan Ong, Douglas Christopher Wilson +Repository: jonathanong/ee-first + +> The MIT License (MIT) +> +> Copyright (c) 2014 Jonathan Ong me@jongleberry.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. + +--------------------------------------- + +## emojis-list +License: MIT +By: Kiko Beats +Repository: git+https://github.com/kikobeats/emojis-list.git + +> The MIT License (MIT) +> +> Copyright © 2015 Kiko Beats +> +> 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. + +--------------------------------------- + +## encodeurl +License: MIT +By: Douglas Christopher Wilson +Repository: pillarjs/encodeurl + +> (The MIT License) +> +> Copyright (c) 2016 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## es-module-lexer +License: MIT +By: Guy Bedford +Repository: git+https://github.com/guybedford/es-module-lexer.git + +> MIT License +> ----------- +> +> Copyright (C) 2018-2021 Guy Bedford +> +> 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. + +--------------------------------------- + +## escape-html +License: MIT +Repository: component/escape-html + +> (The MIT License) +> +> Copyright (c) 2012-2013 TJ Holowaychuk +> Copyright (c) 2015 Andreas Lubbe +> Copyright (c) 2015 Tiancheng "Timothy" Gu +> +> 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. + +--------------------------------------- + +## escape-string-regexp +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/escape-string-regexp + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## estree-walker +License: MIT +By: Rich Harris +Repository: https://github.com/Rich-Harris/estree-walker + +> Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/contributors) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## etag +License: MIT +By: Douglas Christopher Wilson, David Björklund +Repository: jshttp/etag + +> (The MIT License) +> +> Copyright (c) 2014-2016 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## eventemitter3 +License: MIT +By: Arnout Kazemier +Repository: git://github.com/primus/eventemitter3.git + +> The MIT License (MIT) +> +> Copyright (c) 2014 Arnout Kazemier +> +> 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. + +--------------------------------------- + +## execa +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/execa + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## fast-glob +License: MIT +By: Denis Malinochkin +Repository: mrmlnc/fast-glob + +> The MIT License (MIT) +> +> Copyright (c) Denis Malinochkin +> +> 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. + +--------------------------------------- + +## fastq +License: ISC +By: Matteo Collina +Repository: git+https://github.com/mcollina/fastq.git + +> Copyright (c) 2015-2020, Matteo Collina +> +> 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. + +--------------------------------------- + +## fill-range +License: MIT +By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling +Repository: jonschlinkert/fill-range + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## finalhandler +License: MIT +By: Douglas Christopher Wilson +Repository: pillarjs/finalhandler + +> (The MIT License) +> +> Copyright (c) 2014-2017 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## follow-redirects +License: MIT +By: Ruben Verborgh, Olivier Lalonde, James Talmage +Repository: git@github.com:follow-redirects/follow-redirects.git + +> Copyright 2014–present Olivier Lalonde , James Talmage , Ruben Verborgh +> +> 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. + +--------------------------------------- + +## fs.realpath +License: ISC +By: Isaac Z. Schlueter +Repository: git+https://github.com/isaacs/fs.realpath.git + +> The ISC License +> +> Copyright (c) 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 +> 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. +> +> ---- +> +> This library bundles a version of the `fs.realpath` and `fs.realpathSync` +> methods from Node.js v0.10 under the terms of the Node.js MIT license. +> +> Node's license follows, also included at the header of `old.js` which contains +> the licensed code: +> +> 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. + +--------------------------------------- + +## generic-names +License: MIT +By: Alexey Litvinov +Repository: git+https://github.com/css-modules/generic-names.git + +> The MIT License (MIT) +> +> Copyright (c) 2015 Alexey Litvinov +> +> 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. + +--------------------------------------- + +## get-stream +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/get-stream + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## glob +License: ISC +By: Isaac Z. Schlueter +Repository: git://github.com/isaacs/node-glob.git + +> The ISC License +> +> Copyright (c) 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 +> 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. +> +> ## 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/ + +--------------------------------------- + +## glob-parent +License: ISC +By: Gulp Team, Elan Shanker, Blaine Bublitz +Repository: gulpjs/glob-parent + +> The ISC License +> +> Copyright (c) 2015, 2019 Elan Shanker +> +> 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. + +--------------------------------------- + +## globby +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/globby + +> 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. + +--------------------------------------- + +## has-flag +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/has-flag + +> 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. + +--------------------------------------- + +## http-proxy +License: MIT +By: Charlie Robbins +Repository: https://github.com/http-party/node-http-proxy.git + +> node-http-proxy +> +> Copyright (c) 2010-2016 Charlie Robbins, Jarrett Cruger & the 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. + +--------------------------------------- + +## human-signals +License: Apache-2.0 +By: ehmicky +Repository: ehmicky/human-signals + +> Apache License +> Version 2.0, January 2004 +> http://www.apache.org/licenses/ +> +> TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +> +> 1. Definitions. +> +> "License" shall mean the terms and conditions for use, reproduction, +> and distribution as defined by Sections 1 through 9 of this document. +> +> "Licensor" shall mean the copyright owner or entity authorized by +> the copyright owner that is granting the License. +> +> "Legal Entity" shall mean the union of the acting entity and all +> other entities that control, are controlled by, or are under common +> control with that entity. For the purposes of this definition, +> "control" means (i) the power, direct or indirect, to cause the +> direction or management of such entity, whether by contract or +> otherwise, or (ii) ownership of fifty percent (50%) or more of the +> outstanding shares, or (iii) beneficial ownership of such entity. +> +> "You" (or "Your") shall mean an individual or Legal Entity +> exercising permissions granted by this License. +> +> "Source" form shall mean the preferred form for making modifications, +> including but not limited to software source code, documentation +> source, and configuration files. +> +> "Object" form shall mean any form resulting from mechanical +> transformation or translation of a Source form, including but +> not limited to compiled object code, generated documentation, +> and conversions to other media types. +> +> "Work" shall mean the work of authorship, whether in Source or +> Object form, made available under the License, as indicated by a +> copyright notice that is included in or attached to the work +> (an example is provided in the Appendix below). +> +> "Derivative Works" shall mean any work, whether in Source or Object +> form, that is based on (or derived from) the Work and for which the +> editorial revisions, annotations, elaborations, or other modifications +> represent, as a whole, an original work of authorship. For the purposes +> of this License, Derivative Works shall not include works that remain +> separable from, or merely link (or bind by name) to the interfaces of, +> the Work and Derivative Works thereof. +> +> "Contribution" shall mean any work of authorship, including +> the original version of the Work and any modifications or additions +> to that Work or Derivative Works thereof, that is intentionally +> submitted to Licensor for inclusion in the Work by the copyright owner +> or by an individual or Legal Entity authorized to submit on behalf of +> the copyright owner. For the purposes of this definition, "submitted" +> means any form of electronic, verbal, or written communication sent +> to the Licensor or its representatives, including but not limited to +> communication on electronic mailing lists, source code control systems, +> and issue tracking systems that are managed by, or on behalf of, the +> Licensor for the purpose of discussing and improving the Work, but +> excluding communication that is conspicuously marked or otherwise +> designated in writing by the copyright owner as "Not a Contribution." +> +> "Contributor" shall mean Licensor and any individual or Legal Entity +> on behalf of whom a Contribution has been received by Licensor and +> subsequently incorporated within the Work. +> +> 2. Grant of Copyright License. Subject to the terms and conditions of +> this License, each Contributor hereby grants to You a perpetual, +> worldwide, non-exclusive, no-charge, royalty-free, irrevocable +> copyright license to reproduce, prepare Derivative Works of, +> publicly display, publicly perform, sublicense, and distribute the +> Work and such Derivative Works in Source or Object form. +> +> 3. Grant of Patent License. Subject to the terms and conditions of +> this License, each Contributor hereby grants to You a perpetual, +> worldwide, non-exclusive, no-charge, royalty-free, irrevocable +> (except as stated in this section) patent license to make, have made, +> use, offer to sell, sell, import, and otherwise transfer the Work, +> where such license applies only to those patent claims licensable +> by such Contributor that are necessarily infringed by their +> Contribution(s) alone or by combination of their Contribution(s) +> with the Work to which such Contribution(s) was submitted. If You +> institute patent litigation against any entity (including a +> cross-claim or counterclaim in a lawsuit) alleging that the Work +> or a Contribution incorporated within the Work constitutes direct +> or contributory patent infringement, then any patent licenses +> granted to You under this License for that Work shall terminate +> as of the date such litigation is filed. +> +> 4. Redistribution. You may reproduce and distribute copies of the +> Work or Derivative Works thereof in any medium, with or without +> modifications, and in Source or Object form, provided that You +> meet the following conditions: +> +> (a) You must give any other recipients of the Work or +> Derivative Works a copy of this License; and +> +> (b) You must cause any modified files to carry prominent notices +> stating that You changed the files; and +> +> (c) You must retain, in the Source form of any Derivative Works +> that You distribute, all copyright, patent, trademark, and +> attribution notices from the Source form of the Work, +> excluding those notices that do not pertain to any part of +> the Derivative Works; and +> +> (d) If the Work includes a "NOTICE" text file as part of its +> distribution, then any Derivative Works that You distribute must +> include a readable copy of the attribution notices contained +> within such NOTICE file, excluding those notices that do not +> pertain to any part of the Derivative Works, in at least one +> of the following places: within a NOTICE text file distributed +> as part of the Derivative Works; within the Source form or +> documentation, if provided along with the Derivative Works; or, +> within a display generated by the Derivative Works, if and +> wherever such third-party notices normally appear. The contents +> of the NOTICE file are for informational purposes only and +> do not modify the License. You may add Your own attribution +> notices within Derivative Works that You distribute, alongside +> or as an addendum to the NOTICE text from the Work, provided +> that such additional attribution notices cannot be construed +> as modifying the License. +> +> You may add Your own copyright statement to Your modifications and +> may provide additional or different license terms and conditions +> for use, reproduction, or distribution of Your modifications, or +> for any such Derivative Works as a whole, provided Your use, +> reproduction, and distribution of the Work otherwise complies with +> the conditions stated in this License. +> +> 5. Submission of Contributions. Unless You explicitly state otherwise, +> any Contribution intentionally submitted for inclusion in the Work +> by You to the Licensor shall be under the terms and conditions of +> this License, without any additional terms or conditions. +> Notwithstanding the above, nothing herein shall supersede or modify +> the terms of any separate license agreement you may have executed +> with Licensor regarding such Contributions. +> +> 6. Trademarks. This License does not grant permission to use the trade +> names, trademarks, service marks, or product names of the Licensor, +> except as required for reasonable and customary use in describing the +> origin of the Work and reproducing the content of the NOTICE file. +> +> 7. Disclaimer of Warranty. Unless required by applicable law or +> agreed to in writing, Licensor provides the Work (and each +> Contributor provides its Contributions) on an "AS IS" BASIS, +> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +> implied, including, without limitation, any warranties or conditions +> of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +> PARTICULAR PURPOSE. You are solely responsible for determining the +> appropriateness of using or redistributing the Work and assume any +> risks associated with Your exercise of permissions under this License. +> +> 8. Limitation of Liability. In no event and under no legal theory, +> whether in tort (including negligence), contract, or otherwise, +> unless required by applicable law (such as deliberate and grossly +> negligent acts) or agreed to in writing, shall any Contributor be +> liable to You for damages, including any direct, indirect, special, +> incidental, or consequential damages of any character arising as a +> result of this License or out of the use or inability to use the +> Work (including but not limited to damages for loss of goodwill, +> work stoppage, computer failure or malfunction, or any and all +> other commercial damages or losses), even if such Contributor +> has been advised of the possibility of such damages. +> +> 9. Accepting Warranty or Additional Liability. While redistributing +> the Work or Derivative Works thereof, You may choose to offer, +> and charge a fee for, acceptance of support, warranty, indemnity, +> or other liability obligations and/or rights consistent with this +> License. However, in accepting such obligations, You may act only +> on Your own behalf and on Your sole responsibility, not on behalf +> of any other Contributor, and only if You agree to indemnify, +> defend, and hold each Contributor harmless for any liability +> incurred by, or claims asserted against, such Contributor by reason +> of your accepting any such warranty or additional liability. +> +> END OF TERMS AND CONDITIONS +> +> APPENDIX: How to apply the Apache License to your work. +> +> To apply the Apache License to your work, attach the following +> boilerplate notice, with the fields enclosed by brackets "[]" +> replaced with your own identifying information. (Don't include +> the brackets!) The text should be enclosed in the appropriate +> comment syntax for the file format. We also recommend that a +> file or class name and description of purpose be included on the +> same "printed page" as the copyright notice for easier +> identification within third-party archives. +> +> Copyright 2019 ehmicky +> +> Licensed under the Apache License, Version 2.0 (the "License"); +> you may not use this file except in compliance with the License. +> You may obtain a copy of the License at +> +> http://www.apache.org/licenses/LICENSE-2.0 +> +> Unless required by applicable law or agreed to in writing, software +> distributed under the License is distributed on an "AS IS" BASIS, +> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +> See the License for the specific language governing permissions and +> limitations under the License. + +--------------------------------------- + +## icss-replace-symbols +License: ISC +By: Glen Maddern +Repository: git+https://github.com/css-modules/icss-replace-symbols.git + +--------------------------------------- + +## icss-utils +License: ISC +By: Glen Maddern +Repository: git+https://github.com/css-modules/icss-utils.git + +> ISC License (ISC) +> Copyright 2018 Glen Maddern +> +> 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. + +--------------------------------------- + +## ignore +License: MIT +By: kael +Repository: git@github.com:kaelzhang/node-ignore.git + +> Copyright (c) 2013 Kael Zhang , contributors +> http://kael.me/ +> +> 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. + +--------------------------------------- + +## import-cwd +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/import-cwd + +> 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. + +--------------------------------------- + +## import-from +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/import-from + +> 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. + +--------------------------------------- + +## inflight +License: ISC +By: Isaac Z. Schlueter +Repository: https://github.com/npm/inflight.git + +> The ISC License +> +> Copyright (c) Isaac Z. Schlueter +> +> 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. + +--------------------------------------- + +## inherits +License: ISC +Repository: git://github.com/isaacs/inherits + +> The ISC License +> +> Copyright (c) Isaac Z. Schlueter +> +> 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. + +--------------------------------------- + +## is-binary-path +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-binary-path + +> MIT License +> +> Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), 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: +> +> 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. + +--------------------------------------- + +## is-docker +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-docker + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## is-extglob +License: MIT +By: Jon Schlinkert +Repository: jonschlinkert/is-extglob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2016, Jon Schlinkert +> +> 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. + +--------------------------------------- + +## is-glob +License: MIT +By: Jon Schlinkert, Brian Woodward, Daniel Perez +Repository: micromatch/is-glob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2017, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## is-number +License: MIT +By: Jon Schlinkert, Olsten Larck, Rouven Weßling +Repository: jonschlinkert/is-number + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## is-reference +License: MIT +By: Rich Harris +Repository: git+https://github.com/Rich-Harris/is-reference.git + +--------------------------------------- + +## is-stream +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-stream + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## is-wsl +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-wsl + +> 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. + +--------------------------------------- + +## isexe +License: ISC +By: Isaac Z. Schlueter +Repository: git+https://github.com/isaacs/isexe.git + +> The ISC License +> +> Copyright (c) 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 +> 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. + +--------------------------------------- + +## json5 +License: MIT +By: Aseem Kishore, Max Nanasy, Andrew Eisenberg, Jordan Tucker +Repository: git+https://github.com/json5/json5.git + +> MIT License +> +> Copyright (c) 2012-2018 Aseem Kishore, and [others]. +> +> 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. +> +> [others]: https://github.com/json5/json5/contributors + +--------------------------------------- + +## launch-editor +License: MIT +By: Evan You +Repository: git+https://github.com/yyx990803/launch-editor.git + +--------------------------------------- + +## launch-editor-middleware +License: MIT +By: Evan You +Repository: git+https://github.com/yyx990803/launch-editor.git + +--------------------------------------- + +## lilconfig +License: MIT +By: antonk52 +Repository: https://github.com/antonk52/lilconfig + +--------------------------------------- + +## loader-utils +License: MIT +By: Tobias Koppers @sokra +Repository: https://github.com/webpack/loader-utils.git + +> Copyright JS Foundation and other contributors +> +> Permission is hereby granted, free of charge, to any person obtaining +> a copy of this software and associated documentation files (the +> 'Software'), to deal in the Software without restriction, including +> without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to +> permit persons to whom the Software is furnished to do so, subject to +> the following conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## lodash.camelcase +License: MIT +By: John-David Dalton, Blaine Bublitz, Mathias Bynens +Repository: lodash/lodash + +> Copyright jQuery Foundation and other contributors +> +> Based on Underscore.js, copyright Jeremy Ashkenas, +> DocumentCloud and Investigative Reporters & Editors +> +> This software consists of voluntary contributions made by many +> individuals. For exact contribution history, see the revision history +> available at https://github.com/lodash/lodash +> +> The following license applies to all parts of this software except as +> documented below: +> +> ==== +> +> 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. +> +> ==== +> +> Copyright and related rights for sample code are waived via CC0. Sample +> code is defined as all source code displayed within the prose of the +> documentation. +> +> CC0: http://creativecommons.org/publicdomain/zero/1.0/ +> +> ==== +> +> Files located in the node_modules and vendor directories are externally +> maintained libraries used by this software which have their own +> licenses; we recommend you read them, as their terms may differ from the +> terms above. + +--------------------------------------- + +## magic-string +License: MIT +By: Rich Harris +Repository: https://github.com/rich-harris/magic-string + +> Copyright 2018 Rich Harris +> +> 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. + +--------------------------------------- + +## make-error +License: ISC +By: Julien Fontanet +Repository: git://github.com/JsCommunity/make-error.git + +> Copyright 2014 Julien Fontanet +> +> 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. + +--------------------------------------- + +## merge-stream +License: MIT +By: Stephen Sugden +Repository: grncdr/merge-stream + +> The MIT License (MIT) +> +> Copyright (c) Stephen Sugden (stephensugden.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. + +--------------------------------------- + +## merge2 +License: MIT +Repository: git@github.com:teambition/merge2.git + +> The MIT License (MIT) +> +> Copyright (c) 2014-2020 Teambition +> +> 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. + +--------------------------------------- + +## micromatch +License: MIT +By: Jon Schlinkert, Amila Welihinda, Bogdan Chadkin, Brian Woodward, Devon Govett, Elan Shanker, Fabrício Matté, Martin Kolárik, Olsten Larck, Paul Miller, Tom Byrer, Tyler Akins, Peter Bright, Kuba Juszczyk +Repository: micromatch/micromatch + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## mime +License: MIT +By: Robert Kieffer +Repository: https://github.com/broofa/mime + +> The MIT License (MIT) +> +> Copyright (c) 2010 Benjamin Thomas, Robert Kieffer +> +> 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. + +--------------------------------------- + +## mime-db +License: MIT +By: Douglas Christopher Wilson, Jonathan Ong, Robert Kieffer +Repository: jshttp/mime-db + +> The MIT License (MIT) +> +> Copyright (c) 2014 Jonathan Ong me@jongleberry.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. + +--------------------------------------- + +## mime-types +License: MIT +By: Douglas Christopher Wilson, Jeremiah Senkpiel, Jonathan Ong +Repository: jshttp/mime-types + +> (The MIT License) +> +> Copyright (c) 2014 Jonathan Ong +> Copyright (c) 2015 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## mimic-fn +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/mimic-fn + +> 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. + +--------------------------------------- + +## minimatch +License: ISC +By: Isaac Z. Schlueter +Repository: git://github.com/isaacs/minimatch.git + +> The ISC License +> +> Copyright (c) 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 +> 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. + +--------------------------------------- + +## ms +License: MIT +Repository: zeit/ms + +> The MIT License (MIT) +> +> Copyright (c) 2016 Zeit, Inc. +> +> 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. + +--------------------------------------- + +## negotiator +License: MIT +By: Douglas Christopher Wilson, Federico Romero, Isaac Z. Schlueter +Repository: jshttp/negotiator + +> (The MIT License) +> +> Copyright (c) 2012-2014 Federico Romero +> Copyright (c) 2012-2014 Isaac Z. Schlueter +> Copyright (c) 2014-2015 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## node-forge +License: (BSD-3-Clause OR GPL-2.0) +By: Digital Bazaar, Inc., Dave Longley, David I. Lehn, Stefan Siegl, Christoph Dorn +Repository: https://github.com/digitalbazaar/forge + +> You may use the Forge project under the terms of either the BSD License or the +> GNU General Public License (GPL) Version 2. +> +> The BSD License is recommended for most projects. It is simple and easy to +> understand and it places almost no restrictions on what you can do with the +> Forge project. +> +> If the GPL suits your project better you are also free to use Forge under +> that license. +> +> You don't have to do anything special to choose one license or the other and +> you don't have to notify anyone which license you are using. You are free to +> use this project in commercial projects as long as the copyright header is +> left intact. +> +> If you are a commercial entity and use this set of libraries in your +> commercial software then reasonable payment to Digital Bazaar, if you can +> afford it, is not required but is expected and would be appreciated. If this +> library saves you time, then it's saving you money. The cost of developing +> the Forge software was on the order of several hundred hours and tens of +> thousands of dollars. We are attempting to strike a balance between helping +> the development community while not being taken advantage of by lucrative +> commercial entities for our efforts. +> +> ------------------------------------------------------------------------------- +> New BSD License (3-clause) +> Copyright (c) 2010, Digital Bazaar, Inc. +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without +> modification, are permitted provided that the following conditions are met: +> * Redistributions of source code must retain the above copyright +> notice, this list of conditions and the following disclaimer. +> * Redistributions in binary form must reproduce the above copyright +> notice, this list of conditions and the following disclaimer in the +> documentation and/or other materials provided with the distribution. +> * Neither the name of Digital Bazaar, Inc. nor the +> names of its contributors may be used to endorse or promote products +> derived from this software without specific prior written permission. +> +> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +> ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +> WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +> DISCLAIMED. IN NO EVENT SHALL DIGITAL BAZAAR BE LIABLE FOR ANY +> DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +> (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +> LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +> ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +> (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +> SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +> +> ------------------------------------------------------------------------------- +> GNU GENERAL PUBLIC LICENSE +> Version 2, June 1991 +> +> Copyright (C) 1989, 1991 Free Software Foundation, Inc. +> 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +> Everyone is permitted to copy and distribute verbatim copies +> of this license document, but changing it is not allowed. +> +> Preamble +> +> The licenses for most software are designed to take away your +> freedom to share and change it. By contrast, the GNU General Public +> License is intended to guarantee your freedom to share and change free +> software--to make sure the software is free for all its users. This +> General Public License applies to most of the Free Software +> Foundation's software and to any other program whose authors commit to +> using it. (Some other Free Software Foundation software is covered by +> the GNU Lesser General Public License instead.) You can apply it to +> your programs, too. +> +> When we speak of free software, we are referring to freedom, not +> price. Our General Public Licenses are designed to make sure that you +> have the freedom to distribute copies of free software (and charge for +> this service if you wish), that you receive source code or can get it +> if you want it, that you can change the software or use pieces of it +> in new free programs; and that you know you can do these things. +> +> To protect your rights, we need to make restrictions that forbid +> anyone to deny you these rights or to ask you to surrender the rights. +> These restrictions translate to certain responsibilities for you if you +> distribute copies of the software, or if you modify it. +> +> For example, if you distribute copies of such a program, whether +> gratis or for a fee, you must give the recipients all the rights that +> you have. You must make sure that they, too, receive or can get the +> source code. And you must show them these terms so they know their +> rights. +> +> We protect your rights with two steps: (1) copyright the software, and +> (2) offer you this license which gives you legal permission to copy, +> distribute and/or modify the software. +> +> Also, for each author's protection and ours, we want to make certain +> that everyone understands that there is no warranty for this free +> software. If the software is modified by someone else and passed on, we +> want its recipients to know that what they have is not the original, so +> that any problems introduced by others will not reflect on the original +> authors' reputations. +> +> Finally, any free program is threatened constantly by software +> patents. We wish to avoid the danger that redistributors of a free +> program will individually obtain patent licenses, in effect making the +> program proprietary. To prevent this, we have made it clear that any +> patent must be licensed for everyone's free use or not licensed at all. +> +> The precise terms and conditions for copying, distribution and +> modification follow. +> +> GNU GENERAL PUBLIC LICENSE +> TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION +> +> 0. This License applies to any program or other work which contains +> a notice placed by the copyright holder saying it may be distributed +> under the terms of this General Public License. The "Program", below, +> refers to any such program or work, and a "work based on the Program" +> means either the Program or any derivative work under copyright law: +> that is to say, a work containing the Program or a portion of it, +> either verbatim or with modifications and/or translated into another +> language. (Hereinafter, translation is included without limitation in +> the term "modification".) Each licensee is addressed as "you". +> +> Activities other than copying, distribution and modification are not +> covered by this License; they are outside its scope. The act of +> running the Program is not restricted, and the output from the Program +> is covered only if its contents constitute a work based on the +> Program (independent of having been made by running the Program). +> Whether that is true depends on what the Program does. +> +> 1. You may copy and distribute verbatim copies of the Program's +> source code as you receive it, in any medium, provided that you +> conspicuously and appropriately publish on each copy an appropriate +> copyright notice and disclaimer of warranty; keep intact all the +> notices that refer to this License and to the absence of any warranty; +> and give any other recipients of the Program a copy of this License +> along with the Program. +> +> You may charge a fee for the physical act of transferring a copy, and +> you may at your option offer warranty protection in exchange for a fee. +> +> 2. You may modify your copy or copies of the Program or any portion +> of it, thus forming a work based on the Program, and copy and +> distribute such modifications or work under the terms of Section 1 +> above, provided that you also meet all of these conditions: +> +> a) You must cause the modified files to carry prominent notices +> stating that you changed the files and the date of any change. +> +> b) You must cause any work that you distribute or publish, that in +> whole or in part contains or is derived from the Program or any +> part thereof, to be licensed as a whole at no charge to all third +> parties under the terms of this License. +> +> c) If the modified program normally reads commands interactively +> when run, you must cause it, when started running for such +> interactive use in the most ordinary way, to print or display an +> announcement including an appropriate copyright notice and a +> notice that there is no warranty (or else, saying that you provide +> a warranty) and that users may redistribute the program under +> these conditions, and telling the user how to view a copy of this +> License. (Exception: if the Program itself is interactive but +> does not normally print such an announcement, your work based on +> the Program is not required to print an announcement.) +> +> These requirements apply to the modified work as a whole. If +> identifiable sections of that work are not derived from the Program, +> and can be reasonably considered independent and separate works in +> themselves, then this License, and its terms, do not apply to those +> sections when you distribute them as separate works. But when you +> distribute the same sections as part of a whole which is a work based +> on the Program, the distribution of the whole must be on the terms of +> this License, whose permissions for other licensees extend to the +> entire whole, and thus to each and every part regardless of who wrote it. +> +> Thus, it is not the intent of this section to claim rights or contest +> your rights to work written entirely by you; rather, the intent is to +> exercise the right to control the distribution of derivative or +> collective works based on the Program. +> +> In addition, mere aggregation of another work not based on the Program +> with the Program (or with a work based on the Program) on a volume of +> a storage or distribution medium does not bring the other work under +> the scope of this License. +> +> 3. You may copy and distribute the Program (or a work based on it, +> under Section 2) in object code or executable form under the terms of +> Sections 1 and 2 above provided that you also do one of the following: +> +> a) Accompany it with the complete corresponding machine-readable +> source code, which must be distributed under the terms of Sections +> 1 and 2 above on a medium customarily used for software interchange; or, +> +> b) Accompany it with a written offer, valid for at least three +> years, to give any third party, for a charge no more than your +> cost of physically performing source distribution, a complete +> machine-readable copy of the corresponding source code, to be +> distributed under the terms of Sections 1 and 2 above on a medium +> customarily used for software interchange; or, +> +> c) Accompany it with the information you received as to the offer +> to distribute corresponding source code. (This alternative is +> allowed only for noncommercial distribution and only if you +> received the program in object code or executable form with such +> an offer, in accord with Subsection b above.) +> +> The source code for a work means the preferred form of the work for +> making modifications to it. For an executable work, complete source +> code means all the source code for all modules it contains, plus any +> associated interface definition files, plus the scripts used to +> control compilation and installation of the executable. However, as a +> special exception, the source code distributed need not include +> anything that is normally distributed (in either source or binary +> form) with the major components (compiler, kernel, and so on) of the +> operating system on which the executable runs, unless that component +> itself accompanies the executable. +> +> If distribution of executable or object code is made by offering +> access to copy from a designated place, then offering equivalent +> access to copy the source code from the same place counts as +> distribution of the source code, even though third parties are not +> compelled to copy the source along with the object code. +> +> 4. You may not copy, modify, sublicense, or distribute the Program +> except as expressly provided under this License. Any attempt +> otherwise to copy, modify, sublicense or distribute the Program is +> void, and will automatically terminate your rights under this License. +> However, parties who have received copies, or rights, from you under +> this License will not have their licenses terminated so long as such +> parties remain in full compliance. +> +> 5. You are not required to accept this License, since you have not +> signed it. However, nothing else grants you permission to modify or +> distribute the Program or its derivative works. These actions are +> prohibited by law if you do not accept this License. Therefore, by +> modifying or distributing the Program (or any work based on the +> Program), you indicate your acceptance of this License to do so, and +> all its terms and conditions for copying, distributing or modifying +> the Program or works based on it. +> +> 6. Each time you redistribute the Program (or any work based on the +> Program), the recipient automatically receives a license from the +> original licensor to copy, distribute or modify the Program subject to +> these terms and conditions. You may not impose any further +> restrictions on the recipients' exercise of the rights granted herein. +> You are not responsible for enforcing compliance by third parties to +> this License. +> +> 7. If, as a consequence of a court judgment or allegation of patent +> infringement or for any other reason (not limited to patent issues), +> conditions are imposed on you (whether by court order, agreement or +> otherwise) that contradict the conditions of this License, they do not +> excuse you from the conditions of this License. If you cannot +> distribute so as to satisfy simultaneously your obligations under this +> License and any other pertinent obligations, then as a consequence you +> may not distribute the Program at all. For example, if a patent +> license would not permit royalty-free redistribution of the Program by +> all those who receive copies directly or indirectly through you, then +> the only way you could satisfy both it and this License would be to +> refrain entirely from distribution of the Program. +> +> If any portion of this section is held invalid or unenforceable under +> any particular circumstance, the balance of the section is intended to +> apply and the section as a whole is intended to apply in other +> circumstances. +> +> It is not the purpose of this section to induce you to infringe any +> patents or other property right claims or to contest validity of any +> such claims; this section has the sole purpose of protecting the +> integrity of the free software distribution system, which is +> implemented by public license practices. Many people have made +> generous contributions to the wide range of software distributed +> through that system in reliance on consistent application of that +> system; it is up to the author/donor to decide if he or she is willing +> to distribute software through any other system and a licensee cannot +> impose that choice. +> +> This section is intended to make thoroughly clear what is believed to +> be a consequence of the rest of this License. +> +> 8. If the distribution and/or use of the Program is restricted in +> certain countries either by patents or by copyrighted interfaces, the +> original copyright holder who places the Program under this License +> may add an explicit geographical distribution limitation excluding +> those countries, so that distribution is permitted only in or among +> countries not thus excluded. In such case, this License incorporates +> the limitation as if written in the body of this License. +> +> 9. The Free Software Foundation may publish revised and/or new versions +> of the General Public License from time to time. Such new versions will +> be similar in spirit to the present version, but may differ in detail to +> address new problems or concerns. +> +> Each version is given a distinguishing version number. If the Program +> specifies a version number of this License which applies to it and "any +> later version", you have the option of following the terms and conditions +> either of that version or of any later version published by the Free +> Software Foundation. If the Program does not specify a version number of +> this License, you may choose any version ever published by the Free Software +> Foundation. +> +> 10. If you wish to incorporate parts of the Program into other free +> programs whose distribution conditions are different, write to the author +> to ask for permission. For software which is copyrighted by the Free +> Software Foundation, write to the Free Software Foundation; we sometimes +> make exceptions for this. Our decision will be guided by the two goals +> of preserving the free status of all derivatives of our free software and +> of promoting the sharing and reuse of software generally. +> +> NO WARRANTY +> +> 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +> FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +> OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +> PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +> OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +> TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +> PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +> REPAIR OR CORRECTION. +> +> 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +> WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +> REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +> INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +> OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +> TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +> YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +> PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +> POSSIBILITY OF SUCH DAMAGES. + +--------------------------------------- + +## normalize-path +License: MIT +By: Jon Schlinkert, Blaine Bublitz +Repository: jonschlinkert/normalize-path + +> The MIT License (MIT) +> +> Copyright (c) 2014-2018, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## npm-run-path +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/npm-run-path + +> 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. + +--------------------------------------- + +## object-assign +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/object-assign + +> The MIT License (MIT) +> +> 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. + +--------------------------------------- + +## okie +License: MIT +By: Evan You +Repository: git+https://github.com/yyx990803/okie.git + +> MIT License +> +> Copyright (c) 2020-present, Yuxi (Evan) You +> +> 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. + +--------------------------------------- + +## on-finished +License: MIT +By: Douglas Christopher Wilson, Jonathan Ong +Repository: jshttp/on-finished + +> (The MIT License) +> +> Copyright (c) 2013 Jonathan Ong +> Copyright (c) 2014 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## on-headers +License: MIT +By: Douglas Christopher Wilson +Repository: jshttp/on-headers + +> (The MIT License) +> +> Copyright (c) 2014 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## once +License: ISC +By: Isaac Z. Schlueter +Repository: git://github.com/isaacs/once + +> The ISC License +> +> Copyright (c) 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 +> 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. + +--------------------------------------- + +## onetime +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/onetime + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## open +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/open + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## parseurl +License: MIT +By: Douglas Christopher Wilson, Jonathan Ong +Repository: pillarjs/parseurl + +> (The MIT License) +> +> Copyright (c) 2014 Jonathan Ong +> Copyright (c) 2014-2017 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## path-is-absolute +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/path-is-absolute + +> The MIT License (MIT) +> +> 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. + +--------------------------------------- + +## path-key +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/path-key + +> The MIT License (MIT) +> +> 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. + +--------------------------------------- + +## path-type +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/path-type + +> 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. + +--------------------------------------- + +## periscopic +License: MIT +Repository: Rich-Harris/periscopic + +> Copyright (c) 2019 Rich Harris +> +> 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. + +--------------------------------------- + +## picomatch +License: MIT +By: Jon Schlinkert +Repository: micromatch/picomatch + +> The MIT License (MIT) +> +> Copyright (c) 2017-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## pify +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/pify + +> The MIT License (MIT) +> +> 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. + +--------------------------------------- + +## postcss-import +License: MIT +By: Maxime Thirouin +Repository: https://github.com/postcss/postcss-import.git + +> The MIT License (MIT) +> +> Copyright (c) 2014 Maxime Thirouin, Jason Campbell & Kevin Mårtensson +> +> 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. + +--------------------------------------- + +## postcss-load-config +License: MIT +By: Michael Ciniawky, Ryan Dunckel, Mateusz Derks, Dalton Santos, Patrick Gilday +Repository: postcss/postcss-load-config + +> The MIT License (MIT) +> +> Copyright Michael Ciniawsky +> +> 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. + +--------------------------------------- + +## postcss-modules +License: MIT +By: Alexander Madyankin +Repository: https://github.com/css-modules/postcss-modules.git + +> The MIT License (MIT) +> +> Copyright 2015-2016 Alexander Madyankin +> +> 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. + +--------------------------------------- + +## postcss-modules-extract-imports +License: ISC +By: Glen Maddern +Repository: https://github.com/css-modules/postcss-modules-extract-imports.git + +> Copyright 2015 Glen Maddern +> +> 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. + +--------------------------------------- + +## postcss-modules-local-by-default +License: MIT +By: Mark Dalgleish +Repository: https://github.com/css-modules/postcss-modules-local-by-default.git + +> The MIT License (MIT) +> +> Copyright 2015 Mark Dalgleish +> +> 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. + +--------------------------------------- + +## postcss-modules-scope +License: ISC +By: Glen Maddern +Repository: https://github.com/css-modules/postcss-modules-scope.git + +> ISC License (ISC) +> +> Copyright (c) 2015, Glen Maddern +> +> 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. + +--------------------------------------- + +## postcss-modules-values +License: ISC +By: Glen Maddern +Repository: git+https://github.com/css-modules/postcss-modules-values.git + +> ISC License (ISC) +> +> Copyright (c) 2015, Glen Maddern +> +> 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. + +--------------------------------------- + +## postcss-selector-parser +License: MIT +By: Ben Briggs, Chris Eppstein +Repository: postcss/postcss-selector-parser + +> Copyright (c) Ben Briggs (http://beneb.info) +> +> 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. + +--------------------------------------- + +## postcss-value-parser +License: MIT +By: Bogdan Chadkin +Repository: https://github.com/TrySound/postcss-value-parser.git + +> Copyright (c) Bogdan Chadkin +> +> 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. + +--------------------------------------- + +## queue-microtask +License: MIT +By: Feross Aboukhadijeh +Repository: git://github.com/feross/queue-microtask.git + +> The MIT License (MIT) +> +> Copyright (c) Feross Aboukhadijeh +> +> 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. + +--------------------------------------- + +## read-cache +License: MIT +By: Bogdan Chadkin +Repository: git+https://github.com/TrySound/read-cache.git + +> The MIT License (MIT) +> +> Copyright 2016 Bogdan Chadkin +> +> 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. + +--------------------------------------- + +## readdirp +License: MIT +By: Thorsten Lorenz, Paul Miller +Repository: git://github.com/paulmillr/readdirp.git + +> MIT License +> +> Copyright (c) 2012-2019 Thorsten Lorenz, 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: +> +> 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. + +--------------------------------------- + +## requires-port +License: MIT +By: Arnout Kazemier +Repository: https://github.com/unshiftio/requires-port + +> The MIT License (MIT) +> +> Copyright (c) 2015 Unshift.io, Arnout Kazemier, the 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. + +--------------------------------------- + +## resolve-from +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/resolve-from + +> 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. + +--------------------------------------- + +## resolve.exports +License: MIT +By: Luke Edwards +Repository: lukeed/resolve.exports + +> The MIT License (MIT) +> +> Copyright (c) Luke Edwards (lukeed.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. + +--------------------------------------- + +## reusify +License: MIT +By: Matteo Collina +Repository: git+https://github.com/mcollina/reusify.git + +> The MIT License (MIT) +> +> Copyright (c) 2015 Matteo Collina +> +> 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. + +--------------------------------------- + +## run-parallel +License: MIT +By: Feross Aboukhadijeh +Repository: git://github.com/feross/run-parallel.git + +> The MIT License (MIT) +> +> Copyright (c) Feross Aboukhadijeh +> +> 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. + +--------------------------------------- + +## safe-buffer +License: MIT +By: Feross Aboukhadijeh +Repository: git://github.com/feross/safe-buffer.git + +> The MIT License (MIT) +> +> Copyright (c) Feross Aboukhadijeh +> +> 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. + +--------------------------------------- + +## selfsigned +License: MIT +By: José F. Romaniello, Paolo Fragomeni, Charles Bushong +Repository: git://github.com/jfromaniello/selfsigned.git + +> MIT License +> +> Copyright (c) 2013 José F. Romaniello +> +> 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. + +--------------------------------------- + +## shebang-command +License: MIT +By: Kevin Mårtensson +Repository: kevva/shebang-command + +> The MIT License (MIT) +> +> Copyright (c) Kevin Martensson (github.com/kevva) +> +> 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. + +--------------------------------------- + +## shebang-regex +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/shebang-regex + +> The MIT License (MIT) +> +> 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. + +--------------------------------------- + +## shell-quote +License: MIT +By: James Halliday +Repository: http://github.com/substack/node-shell-quote.git + +> The MIT License +> +> Copyright (c) 2013 James Halliday (mail@substack.net) +> +> 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. + +--------------------------------------- + +## signal-exit +License: ISC +By: Ben Coe +Repository: https://github.com/tapjs/signal-exit.git + +> The ISC License +> +> Copyright (c) 2015, 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 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. + +--------------------------------------- + +## sirv +License: MIT +By: Luke Edwards +Repository: lukeed/sirv + +--------------------------------------- + +## slash +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/slash + +> 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. + +--------------------------------------- + +## source-map +License: BSD-3-Clause +By: Nick Fitzgerald, Tobias Koppers, Duncan Beevers, Stephen Crane, Ryan Seddon, Miles Elam, Mihai Bazon, Michael Ficarra, Todd Wolfson, Alexander Solovyov, Felix Gnass, Conrad Irwin, usrbincc, David Glasser, Chase Douglas, Evan Wallace, Heather Arthur, Hugh Kennedy, Simon Lydell, Jmeas Smith, Michael Z Goddard, azu, John Gozde, Adam Kirkton, Chris Montgomery, J. Ryan Stinnett, Jack Herrington, Chris Truter, Daniel Espeset, Jamie Wong, Eddy Bruël, Hawken Rives, Gilad Peleg, djchie, Gary Ye, Nicolas Lalevée +Repository: http://github.com/mozilla/source-map.git + +> Copyright (c) 2009-2011, Mozilla Foundation and contributors +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without +> modification, are permitted provided that the following conditions are met: +> +> * Redistributions of source code must retain the above copyright notice, this +> list of conditions and the following disclaimer. +> +> * Redistributions in binary form must reproduce the above copyright notice, +> this list of conditions and the following disclaimer in the documentation +> and/or other materials provided with the distribution. +> +> * Neither the names of the Mozilla Foundation nor the names of project +> contributors may be used to endorse or promote products derived from this +> software without specific prior written permission. +> +> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +> ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +> WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------- + +## sourcemap-codec +License: MIT +By: Rich Harris +Repository: https://github.com/Rich-Harris/sourcemap-codec + +> The MIT License +> +> Copyright (c) 2015 Rich Harris +> +> 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. + +--------------------------------------- + +## statuses +License: MIT +By: Douglas Christopher Wilson, Jonathan Ong +Repository: jshttp/statuses + +> The MIT License (MIT) +> +> Copyright (c) 2014 Jonathan Ong +> Copyright (c) 2016 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## string-hash +License: CC0-1.0 +By: The Dark Sky Company +Repository: git://github.com/darkskyapp/string-hash.git + +--------------------------------------- + +## strip-ansi +License: MIT +By: Sindre Sorhus +Repository: chalk/strip-ansi + +> 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. + +--------------------------------------- + +## strip-bom +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/strip-bom + +> 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. + +--------------------------------------- + +## strip-final-newline +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/strip-final-newline + +> 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. + +--------------------------------------- + +## strip-json-comments +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/strip-json-comments + +> MIT License +> +> 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: +> +> 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. + +--------------------------------------- + +## supports-color +License: MIT +By: Sindre Sorhus +Repository: chalk/supports-color + +> 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. + +--------------------------------------- + +## to-regex-range +License: MIT +By: Jon Schlinkert, Rouven Weßling +Repository: micromatch/to-regex-range + +> The MIT License (MIT) +> +> Copyright (c) 2015-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## totalist +License: MIT +By: Luke Edwards +Repository: lukeed/totalist + +> The MIT License (MIT) +> +> Copyright (c) Luke Edwards (lukeed.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. + +--------------------------------------- + +## ts-node +License: MIT +By: Blake Embrey, Andrew Bradley +Repository: git://github.com/TypeStrong/ts-node.git + +> The MIT License (MIT) +> +> Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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. + +--------------------------------------- + +## unpipe +License: MIT +By: Douglas Christopher Wilson +Repository: stream-utils/unpipe + +> (The MIT License) +> +> Copyright (c) 2015 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## util-deprecate +License: MIT +By: Nathan Rajlich +Repository: git://github.com/TooTallNate/util-deprecate.git + +> (The MIT License) +> +> Copyright (c) 2014 Nathan Rajlich +> +> 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. + +--------------------------------------- + +## utils-merge +License: MIT +By: Jared Hanson +Repository: git://github.com/jaredhanson/utils-merge.git + +> The MIT License (MIT) +> +> Copyright (c) 2013-2017 Jared Hanson +> +> 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. + +--------------------------------------- + +## vary +License: MIT +By: Douglas Christopher Wilson +Repository: jshttp/vary + +> (The MIT License) +> +> Copyright (c) 2014-2017 Douglas Christopher Wilson +> +> 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. + +--------------------------------------- + +## which +License: ISC +By: Isaac Z. Schlueter +Repository: git://github.com/isaacs/node-which.git + +> The ISC License +> +> Copyright (c) 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 +> 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. + +--------------------------------------- + +## wrappy +License: ISC +By: Isaac Z. Schlueter +Repository: https://github.com/npm/wrappy + +> The ISC License +> +> Copyright (c) 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 +> 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. + +--------------------------------------- + +## ws +License: MIT +By: Einar Otto Stangvik +Repository: websockets/ws + +> The MIT License (MIT) +> +> Copyright (c) 2011 Einar Otto Stangvik +> +> 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. + +--------------------------------------- + +## yaml +License: ISC +By: Eemeli Aro +Repository: github:eemeli/yaml + +> Copyright 2018 Eemeli Aro +> +> 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. + +--------------------------------------- + +## yn +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/yn + +> 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/vite/README.md b/node_modules/vite/README.md new file mode 100644 index 0000000..89490d7 --- /dev/null +++ b/node_modules/vite/README.md @@ -0,0 +1,20 @@ +# vite ⚡ + +> Next Generation Frontend Tooling + +- 💡 Instant Server Start +- ⚡️ Lightning Fast HMR +- 🛠️ Rich Features +- 📦 Optimized Build +- 🔩 Universal Plugin Interface +- 🔑 Fully Typed APIs + +Vite (French word for "fast", pronounced `/vit/`) is a new breed of frontend build tool that significantly improves the frontend development experience. It consists of two major parts: + +- A dev server that serves your source files over [native ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), with [rich built-in features](https://vitejs.dev/guide/features.html) and astonishingly fast [Hot Module Replacement (HMR)](https://vitejs.dev/guide/features.html#hot-module-replacement). + +- A [build command](https://vitejs.dev/guide/build.html) that bundles your code with [Rollup](https://rollupjs.org), pre-configured to output highly optimized static assets for production. + +In addition, Vite is highly extensible via its [Plugin API](https://vitejs.dev/guide/api-plugin.html) and [JavaScript API](https://vitejs.dev/guide/api-javascript.html) with full typing support. + +[Read the Docs to Learn More](https://vitejs.dev). diff --git a/node_modules/vite/api-extractor.json b/node_modules/vite/api-extractor.json new file mode 100644 index 0000000..0b5b417 --- /dev/null +++ b/node_modules/vite/api-extractor.json @@ -0,0 +1,54 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + + "projectFolder": "./src/node", + + "mainEntryPointFilePath": "./temp/node/index.d.ts", + + "dtsRollup": { + "enabled": true, + "untrimmedFilePath": "", + "publicTrimmedFilePath": "./dist/node/index.d.ts" + }, + + "apiReport": { + "enabled": false + }, + + "docModel": { + "enabled": false + }, + + "tsdocMetadata": { + "enabled": false + }, + + "messages": { + "compilerMessageReporting": { + "default": { + "logLevel": "warning" + } + }, + + "extractorMessageReporting": { + "default": { + "logLevel": "warning", + "addToApiReportFile": true + }, + + "ae-missing-release-tag": { + "logLevel": "none" + } + }, + + "tsdocMessageReporting": { + "default": { + "logLevel": "warning" + }, + + "tsdoc-undefined-tag": { + "logLevel": "none" + } + } + } +} diff --git a/node_modules/vite/bin/openChrome.applescript b/node_modules/vite/bin/openChrome.applescript new file mode 100644 index 0000000..25d496b --- /dev/null +++ b/node_modules/vite/bin/openChrome.applescript @@ -0,0 +1,86 @@ +(* +Copyright (c) 2015-present, Facebook, Inc. + +This source code is licensed under the MIT license found in the +LICENSE file at +https://github.com/facebookincubator/create-react-app/blob/master/LICENSE +*) + +property targetTab: null +property targetTabIndex: -1 +property targetWindow: null + +on run argv + set theURL to item 1 of argv + + with timeout of 2 seconds + tell application "Chrome" + + if (count every window) = 0 then + make new window + end if + + -- 1: Looking for tab running debugger + -- then, Reload debugging tab if found + -- then return + set found to my lookupTabWithUrl(theURL) + if found then + set targetWindow's active tab index to targetTabIndex + tell targetTab to reload + tell targetWindow to activate + set index of targetWindow to 1 + return + end if + + -- 2: Looking for Empty tab + -- In case debugging tab was not found + -- We try to find an empty tab instead + set found to my lookupTabWithUrl("chrome://newtab/") + if found then + set targetWindow's active tab index to targetTabIndex + set URL of targetTab to theURL + tell targetWindow to activate + return + end if + + -- 3: Create new tab + -- both debugging and empty tab were not found + -- make a new tab with url + tell window 1 + activate + make new tab with properties {URL:theURL} + end tell + end tell + end timeout +end run + +-- Function: +-- Lookup tab with given url +-- if found, store tab, index, and window in properties +-- (properties were declared on top of file) +on lookupTabWithUrl(lookupUrl) + tell application "Chrome" + -- Find a tab with the given url + set found to false + set theTabIndex to -1 + repeat with theWindow in every window + set theTabIndex to 0 + repeat with theTab in every tab of theWindow + set theTabIndex to theTabIndex + 1 + if (theTab's URL as string) contains lookupUrl then + -- assign tab, tab index, and window to properties + set targetTab to theTab + set targetTabIndex to theTabIndex + set targetWindow to theWindow + set found to true + exit repeat + end if + end repeat + + if found then + exit repeat + end if + end repeat + end tell + return found +end lookupTabWithUrl diff --git a/node_modules/vite/bin/vite.js b/node_modules/vite/bin/vite.js new file mode 100644 index 0000000..e3e7fb6 --- /dev/null +++ b/node_modules/vite/bin/vite.js @@ -0,0 +1,58 @@ +#!/usr/bin/env node + +if (!__dirname.includes('node_modules')) { + try { + // only available as dev dependency + require('source-map-support').install() + } catch (e) {} +} + +global.__vite_start_time = Date.now() + +// check debug mode first before requiring the CLI. +const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg)) +const filterIndex = process.argv.findIndex((arg) => + /^(?:-f|--filter)$/.test(arg) +) +const profileIndex = process.argv.indexOf('--profile') + +if (debugIndex > 0) { + let value = process.argv[debugIndex + 1] + if (!value || value.startsWith('-')) { + value = 'vite:*' + } else { + // support debugging multiple flags with comma-separated list + value = value + .split(',') + .map((v) => `vite:${v}`) + .join(',') + } + process.env.DEBUG = value + + if (filterIndex > 0) { + const filter = process.argv[filterIndex + 1] + if (filter && !filter.startsWith('-')) { + process.env.VITE_DEBUG_FILTER = filter + } + } +} + +function start() { + require('../dist/node/cli') +} + +if (profileIndex > 0) { + process.argv.splice(profileIndex, 1) + const next = process.argv[profileIndex] + if (next && !next.startsWith('-')) { + process.argv.splice(profileIndex, 1) + } + const inspector = require('inspector') + const session = (global.__vite_profile_session = new inspector.Session()) + session.connect() + session.post('Profiler.enable', () => { + session.post('Profiler.start', start) + }) +} else { + start() +} diff --git a/node_modules/vite/client.d.ts b/node_modules/vite/client.d.ts new file mode 100644 index 0000000..d52edd9 --- /dev/null +++ b/node_modules/vite/client.d.ts @@ -0,0 +1,204 @@ +/// +/// + +// CSS modules +type CSSModuleClasses = { readonly [key: string]: string } + +declare module '*.module.css' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.scss' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.sass' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.less' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.styl' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.stylus' { + const classes: CSSModuleClasses + export default classes +} +declare module '*.module.pcss' { + const classes: CSSModuleClasses + export default classes +} + +// CSS +declare module '*.css' { + const css: string + export default css +} +declare module '*.scss' { + const css: string + export default css +} +declare module '*.sass' { + const css: string + export default css +} +declare module '*.less' { + const css: string + export default css +} +declare module '*.styl' { + const css: string + export default css +} +declare module '*.stylus' { + const css: string + export default css +} +declare module '*.pcss' { + const css: string + export default css +} + +// Built-in asset types +// see `src/constants.ts` + +// images +declare module '*.jpg' { + const src: string + export default src +} +declare module '*.jpeg' { + const src: string + export default src +} +declare module '*.png' { + const src: string + export default src +} +declare module '*.gif' { + const src: string + export default src +} +declare module '*.svg' { + const src: string + export default src +} +declare module '*.ico' { + const src: string + export default src +} +declare module '*.webp' { + const src: string + export default src +} +declare module '*.avif' { + const src: string + export default src +} + +// media +declare module '*.mp4' { + const src: string + export default src +} +declare module '*.webm' { + const src: string + export default src +} +declare module '*.ogg' { + const src: string + export default src +} +declare module '*.mp3' { + const src: string + export default src +} +declare module '*.wav' { + const src: string + export default src +} +declare module '*.flac' { + const src: string + export default src +} +declare module '*.aac' { + const src: string + export default src +} + +// fonts +declare module '*.woff' { + const src: string + export default src +} +declare module '*.woff2' { + const src: string + export default src +} +declare module '*.eot' { + const src: string + export default src +} +declare module '*.ttf' { + const src: string + export default src +} +declare module '*.otf' { + const src: string + export default src +} + +// other +declare module '*.wasm' { + const src: string + export default src +} +declare module '*.webmanifest' { + const src: string + export default src +} +declare module '*.pdf' { + const src: string + export default src +} + +// web worker +declare module '*?worker' { + const workerConstructor: { + new (): Worker + } + export default workerConstructor +} + +declare module '*?worker&inline' { + const workerConstructor: { + new (): Worker + } + export default workerConstructor +} + +declare module '*?sharedworker' { + const sharedWorkerConstructor: { + new (): SharedWorker + } + export default sharedWorkerConstructor +} + +declare module '*?raw' { + const src: string + export default src +} + +declare module '*?url' { + const src: string + export default src +} + +declare module '*?inline' { + const src: string + export default src +} diff --git a/node_modules/vite/dist/client/client.mjs b/node_modules/vite/dist/client/client.mjs new file mode 100644 index 0000000..384f10a --- /dev/null +++ b/node_modules/vite/dist/client/client.mjs @@ -0,0 +1,549 @@ +import '@vite/env'; + +const template = /*html*/ ` + +
+
+

+  

+  

+  
+ Click outside or fix the code to dismiss.
+ You can also disable this overlay with + hmr: { overlay: false } in vite.config.js. +
+
+`; +const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g; +const codeframeRE = /^(?:>?\s+\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm; +class ErrorOverlay extends HTMLElement { + constructor(err) { + var _a; + super(); + this.root = this.attachShadow({ mode: 'open' }); + this.root.innerHTML = template; + codeframeRE.lastIndex = 0; + const hasFrame = err.frame && codeframeRE.test(err.frame); + const message = hasFrame + ? err.message.replace(codeframeRE, '') + : err.message; + if (err.plugin) { + this.text('.plugin', `[plugin:${err.plugin}] `); + } + this.text('.message-body', message.trim()); + const [file] = (((_a = err.loc) === null || _a === void 0 ? void 0 : _a.file) || err.id || 'unknown file').split(`?`); + if (err.loc) { + this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, true); + } + else if (err.id) { + this.text('.file', file); + } + if (hasFrame) { + this.text('.frame', err.frame.trim()); + } + this.text('.stack', err.stack, true); + this.root.querySelector('.window').addEventListener('click', (e) => { + e.stopPropagation(); + }); + this.addEventListener('click', () => { + this.close(); + }); + } + text(selector, text, linkFiles = false) { + const el = this.root.querySelector(selector); + if (!linkFiles) { + el.textContent = text; + } + else { + let curIndex = 0; + let match; + while ((match = fileRE.exec(text))) { + const { 0: file, index } = match; + if (index != null) { + const frag = text.slice(curIndex, index); + el.appendChild(document.createTextNode(frag)); + const link = document.createElement('a'); + link.textContent = file; + link.className = 'file-link'; + link.onclick = () => { + fetch('/__open-in-editor?file=' + encodeURIComponent(file)); + }; + el.appendChild(link); + curIndex += frag.length + file.length; + } + } + } + } + close() { + var _a; + (_a = this.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this); + } +} +const overlayId = 'vite-error-overlay'; +!customElements.get(overlayId) && customElements.define(overlayId, ErrorOverlay); + +console.log('[vite] connecting...'); +// use server configuration, then fallback to inference +const socketProtocol = __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws'); +const socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`; +const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr'); +const base = __BASE__ || '/'; +function warnFailedFetch(err, path) { + if (!err.message.match('fetch')) { + console.error(err); + } + console.error(`[hmr] Failed to reload ${path}. ` + + `This could be due to syntax errors or importing non-existent ` + + `modules. (see errors above)`); +} +// Listen for messages +socket.addEventListener('message', async ({ data }) => { + handleMessage(JSON.parse(data)); +}); +let isFirstUpdate = true; +async function handleMessage(payload) { + switch (payload.type) { + case 'connected': + console.log(`[vite] connected.`); + // proxy(nginx, docker) hmr ws maybe caused timeout, + // so send ping package let ws keep alive. + setInterval(() => socket.send('ping'), __HMR_TIMEOUT__); + break; + case 'update': + notifyListeners('vite:beforeUpdate', payload); + // if this is the first update and there's already an error overlay, it + // means the page opened with existing server compile error and the whole + // module script failed to load (since one of the nested imports is 500). + // in this case a normal update won't work and a full reload is needed. + if (isFirstUpdate && hasErrorOverlay()) { + window.location.reload(); + return; + } + else { + clearErrorOverlay(); + isFirstUpdate = false; + } + payload.updates.forEach((update) => { + if (update.type === 'js-update') { + queueUpdate(fetchUpdate(update)); + } + else { + // css-update + // this is only sent when a css file referenced with is updated + let { path, timestamp } = update; + path = path.replace(/\?.*/, ''); + // can't use querySelector with `[href*=]` here since the link may be + // using relative paths so we need to use link.href to grab the full + // URL for the include check. + const el = [].slice.call(document.querySelectorAll(`link`)).find((e) => e.href.includes(path)); + if (el) { + const newPath = `${base}${path.slice(1)}${path.includes('?') ? '&' : '?'}t=${timestamp}`; + el.href = new URL(newPath, el.href).href; + } + console.log(`[vite] css hot updated: ${path}`); + } + }); + break; + case 'custom': { + notifyListeners(payload.event, payload.data); + break; + } + case 'full-reload': + notifyListeners('vite:beforeFullReload', payload); + if (payload.path && payload.path.endsWith('.html')) { + // if html file is edited, only reload the page if the browser is + // currently on that page. + const pagePath = location.pathname; + const payloadPath = base + payload.path.slice(1); + if (pagePath === payloadPath || + (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)) { + location.reload(); + } + return; + } + else { + location.reload(); + } + break; + case 'prune': + notifyListeners('vite:beforePrune', payload); + // After an HMR update, some modules are no longer imported on the page + // but they may have left behind side effects that need to be cleaned up + // (.e.g style injections) + // TODO Trigger their dispose callbacks. + payload.paths.forEach((path) => { + const fn = pruneMap.get(path); + if (fn) { + fn(dataMap.get(path)); + } + }); + break; + case 'error': { + notifyListeners('vite:error', payload); + const err = payload.err; + if (enableOverlay) { + createErrorOverlay(err); + } + else { + console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`); + } + break; + } + default: { + const check = payload; + return check; + } + } +} +function notifyListeners(event, data) { + const cbs = customListenersMap.get(event); + if (cbs) { + cbs.forEach((cb) => cb(data)); + } +} +const enableOverlay = __HMR_ENABLE_OVERLAY__; +function createErrorOverlay(err) { + if (!enableOverlay) + return; + clearErrorOverlay(); + document.body.appendChild(new ErrorOverlay(err)); +} +function clearErrorOverlay() { + document + .querySelectorAll(overlayId) + .forEach((n) => n.close()); +} +function hasErrorOverlay() { + return document.querySelectorAll(overlayId).length; +} +let pending = false; +let queued = []; +/** + * buffer multiple hot updates triggered by the same src change + * so that they are invoked in the same order they were sent. + * (otherwise the order may be inconsistent because of the http request round trip) + */ +async function queueUpdate(p) { + queued.push(p); + if (!pending) { + pending = true; + await Promise.resolve(); + pending = false; + const loading = [...queued]; + queued = []; + (await Promise.all(loading)).forEach((fn) => fn && fn()); + } +} +async function waitForSuccessfulPing(ms = 1000) { + // eslint-disable-next-line no-constant-condition + while (true) { + try { + await fetch(`${base}__vite_ping`); + break; + } + catch (e) { + await new Promise((resolve) => setTimeout(resolve, ms)); + } + } +} +// ping server +socket.addEventListener('close', async ({ wasClean }) => { + if (wasClean) + return; + console.log(`[vite] server connection lost. polling for restart...`); + await waitForSuccessfulPing(); + location.reload(); +}); +const sheetsMap = new Map(); +function updateStyle(id, content) { + let style = sheetsMap.get(id); + { + if (style && !(style instanceof HTMLStyleElement)) { + removeStyle(id); + style = undefined; + } + if (!style) { + style = document.createElement('style'); + style.setAttribute('type', 'text/css'); + style.innerHTML = content; + document.head.appendChild(style); + } + else { + style.innerHTML = content; + } + } + sheetsMap.set(id, style); +} +function removeStyle(id) { + const style = sheetsMap.get(id); + if (style) { + if (style instanceof CSSStyleSheet) { + // @ts-ignore + document.adoptedStyleSheets.indexOf(style); + // @ts-ignore + document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style); + } + else { + document.head.removeChild(style); + } + sheetsMap.delete(id); + } +} +async function fetchUpdate({ path, acceptedPath, timestamp }) { + const mod = hotModulesMap.get(path); + if (!mod) { + // In a code-splitting project, + // it is common that the hot-updating module is not loaded yet. + // https://github.com/vitejs/vite/issues/721 + return; + } + const moduleMap = new Map(); + const isSelfUpdate = path === acceptedPath; + // make sure we only import each dep once + const modulesToUpdate = new Set(); + if (isSelfUpdate) { + // self update - only update self + modulesToUpdate.add(path); + } + else { + // dep update + for (const { deps } of mod.callbacks) { + deps.forEach((dep) => { + if (acceptedPath === dep) { + modulesToUpdate.add(dep); + } + }); + } + } + // determine the qualified callbacks before we re-import the modules + const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => { + return deps.some((dep) => modulesToUpdate.has(dep)); + }); + await Promise.all(Array.from(modulesToUpdate).map(async (dep) => { + const disposer = disposeMap.get(dep); + if (disposer) + await disposer(dataMap.get(dep)); + const [path, query] = dep.split(`?`); + try { + const newMod = await import( + /* @vite-ignore */ + base + + path.slice(1) + + `?import&t=${timestamp}${query ? `&${query}` : ''}`); + moduleMap.set(dep, newMod); + } + catch (e) { + warnFailedFetch(e, dep); + } + })); + return () => { + for (const { deps, fn } of qualifiedCallbacks) { + fn(deps.map((dep) => moduleMap.get(dep))); + } + const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`; + console.log(`[vite] hot updated: ${loggedPath}`); + }; +} +const hotModulesMap = new Map(); +const disposeMap = new Map(); +const pruneMap = new Map(); +const dataMap = new Map(); +const customListenersMap = new Map(); +const ctxToListenersMap = new Map(); +// Just infer the return type for now +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +const createHotContext = (ownerPath) => { + if (!dataMap.has(ownerPath)) { + dataMap.set(ownerPath, {}); + } + // when a file is hot updated, a new context is created + // clear its stale callbacks + const mod = hotModulesMap.get(ownerPath); + if (mod) { + mod.callbacks = []; + } + // clear stale custom event listeners + const staleListeners = ctxToListenersMap.get(ownerPath); + if (staleListeners) { + for (const [event, staleFns] of staleListeners) { + const listeners = customListenersMap.get(event); + if (listeners) { + customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l))); + } + } + } + const newListeners = new Map(); + ctxToListenersMap.set(ownerPath, newListeners); + function acceptDeps(deps, callback = () => { }) { + const mod = hotModulesMap.get(ownerPath) || { + id: ownerPath, + callbacks: [] + }; + mod.callbacks.push({ + deps, + fn: callback + }); + hotModulesMap.set(ownerPath, mod); + } + const hot = { + get data() { + return dataMap.get(ownerPath); + }, + accept(deps, callback) { + if (typeof deps === 'function' || !deps) { + // self-accept: hot.accept(() => {}) + acceptDeps([ownerPath], ([mod]) => deps && deps(mod)); + } + else if (typeof deps === 'string') { + // explicit deps + acceptDeps([deps], ([mod]) => callback && callback(mod)); + } + else if (Array.isArray(deps)) { + acceptDeps(deps, callback); + } + else { + throw new Error(`invalid hot.accept() usage.`); + } + }, + acceptDeps() { + throw new Error(`hot.acceptDeps() is deprecated. ` + + `Use hot.accept() with the same signature instead.`); + }, + dispose(cb) { + disposeMap.set(ownerPath, cb); + }, + prune(cb) { + pruneMap.set(ownerPath, cb); + }, + // TODO + // eslint-disable-next-line @typescript-eslint/no-empty-function + decline() { }, + invalidate() { + // TODO should tell the server to re-perform hmr propagation + // from this module as root + location.reload(); + }, + // custom events + on: (event, cb) => { + const addToMap = (map) => { + const existing = map.get(event) || []; + existing.push(cb); + map.set(event, existing); + }; + addToMap(customListenersMap); + addToMap(newListeners); + } + }; + return hot; +}; +/** + * urls here are dynamic import() urls that couldn't be statically analyzed + */ +function injectQuery(url, queryToInject) { + // skip urls that won't be handled by vite + if (!url.startsWith('.') && !url.startsWith('/')) { + return url; + } + // can't use pathname from URL since it may be relative like ../ + const pathname = url.replace(/#.*$/, '').replace(/\?.*$/, ''); + const { search, hash } = new URL(url, 'http://vitejs.dev'); + return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`; +} + +export { createHotContext, injectQuery, removeStyle, updateStyle }; +//# sourceMappingURL=client.mjs.map diff --git a/node_modules/vite/dist/client/client.mjs.map b/node_modules/vite/dist/client/client.mjs.map new file mode 100644 index 0000000..6486e79 --- /dev/null +++ b/node_modules/vite/dist/client/client.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"client.mjs","sources":["../../src/client/overlay.ts","../../src/client/client.ts"],"sourcesContent":["import { ErrorPayload } from 'types/hmrPayload'\n\nconst template = /*html*/ `\n\n
\n
\n
\n  
\n  
\n  
\n Click outside or fix the code to dismiss.
\n You can also disable this overlay with\n hmr: { overlay: false } in vite.config.js.\n
\n
\n`\n\nconst fileRE = /(?:[a-zA-Z]:\\\\|\\/).*?:\\d+:\\d+/g\nconst codeframeRE = /^(?:>?\\s+\\d+\\s+\\|.*|\\s+\\|\\s*\\^.*)\\r?\\n/gm\n\nexport class ErrorOverlay extends HTMLElement {\n root: ShadowRoot\n\n constructor(err: ErrorPayload['err']) {\n super()\n this.root = this.attachShadow({ mode: 'open' })\n this.root.innerHTML = template\n\n codeframeRE.lastIndex = 0\n const hasFrame = err.frame && codeframeRE.test(err.frame)\n const message = hasFrame\n ? err.message.replace(codeframeRE, '')\n : err.message\n if (err.plugin) {\n this.text('.plugin', `[plugin:${err.plugin}] `)\n }\n this.text('.message-body', message.trim())\n\n const [file] = (err.loc?.file || err.id || 'unknown file').split(`?`)\n if (err.loc) {\n this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, true)\n } else if (err.id) {\n this.text('.file', file)\n }\n\n if (hasFrame) {\n this.text('.frame', err.frame!.trim())\n }\n this.text('.stack', err.stack, true)\n\n this.root.querySelector('.window')!.addEventListener('click', (e) => {\n e.stopPropagation()\n })\n this.addEventListener('click', () => {\n this.close()\n })\n }\n\n text(selector: string, text: string, linkFiles = false): void {\n const el = this.root.querySelector(selector)!\n if (!linkFiles) {\n el.textContent = text\n } else {\n let curIndex = 0\n let match: RegExpExecArray | null\n while ((match = fileRE.exec(text))) {\n const { 0: file, index } = match\n if (index != null) {\n const frag = text.slice(curIndex, index)\n el.appendChild(document.createTextNode(frag))\n const link = document.createElement('a')\n link.textContent = file\n link.className = 'file-link'\n link.onclick = () => {\n fetch('/__open-in-editor?file=' + encodeURIComponent(file))\n }\n el.appendChild(link)\n curIndex += frag.length + file.length\n }\n }\n }\n }\n\n close(): void {\n this.parentNode?.removeChild(this)\n }\n}\n\nexport const overlayId = 'vite-error-overlay'\n!customElements.get(overlayId) && customElements.define(overlayId, ErrorOverlay)\n","import {\n ErrorPayload,\n FullReloadPayload,\n HMRPayload,\n PrunePayload,\n Update,\n UpdatePayload\n} from 'types/hmrPayload'\nimport { CustomEventName } from 'types/customEvent'\nimport { ErrorOverlay, overlayId } from './overlay'\n// eslint-disable-next-line node/no-missing-import\nimport '@vite/env'\n\n// injected by the hmr plugin when served\ndeclare const __BASE__: string\ndeclare const __HMR_PROTOCOL__: string\ndeclare const __HMR_HOSTNAME__: string\ndeclare const __HMR_PORT__: string\ndeclare const __HMR_TIMEOUT__: number\ndeclare const __HMR_ENABLE_OVERLAY__: boolean\n\nconsole.log('[vite] connecting...')\n\n// use server configuration, then fallback to inference\nconst socketProtocol =\n __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws')\nconst socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`\nconst socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')\nconst base = __BASE__ || '/'\n\nfunction warnFailedFetch(err: Error, path: string | string[]) {\n if (!err.message.match('fetch')) {\n console.error(err)\n }\n console.error(\n `[hmr] Failed to reload ${path}. ` +\n `This could be due to syntax errors or importing non-existent ` +\n `modules. (see errors above)`\n )\n}\n\n// Listen for messages\nsocket.addEventListener('message', async ({ data }) => {\n handleMessage(JSON.parse(data))\n})\n\nlet isFirstUpdate = true\n\nasync function handleMessage(payload: HMRPayload) {\n switch (payload.type) {\n case 'connected':\n console.log(`[vite] connected.`)\n // proxy(nginx, docker) hmr ws maybe caused timeout,\n // so send ping package let ws keep alive.\n setInterval(() => socket.send('ping'), __HMR_TIMEOUT__)\n break\n case 'update':\n notifyListeners('vite:beforeUpdate', payload)\n // if this is the first update and there's already an error overlay, it\n // means the page opened with existing server compile error and the whole\n // module script failed to load (since one of the nested imports is 500).\n // in this case a normal update won't work and a full reload is needed.\n if (isFirstUpdate && hasErrorOverlay()) {\n window.location.reload()\n return\n } else {\n clearErrorOverlay()\n isFirstUpdate = false\n }\n payload.updates.forEach((update) => {\n if (update.type === 'js-update') {\n queueUpdate(fetchUpdate(update))\n } else {\n // css-update\n // this is only sent when a css file referenced with is updated\n let { path, timestamp } = update\n path = path.replace(/\\?.*/, '')\n // can't use querySelector with `[href*=]` here since the link may be\n // using relative paths so we need to use link.href to grab the full\n // URL for the include check.\n const el = (\n [].slice.call(\n document.querySelectorAll(`link`)\n ) as HTMLLinkElement[]\n ).find((e) => e.href.includes(path))\n if (el) {\n const newPath = `${base}${path.slice(1)}${\n path.includes('?') ? '&' : '?'\n }t=${timestamp}`\n el.href = new URL(newPath, el.href).href\n }\n console.log(`[vite] css hot updated: ${path}`)\n }\n })\n break\n case 'custom': {\n notifyListeners(payload.event as CustomEventName, payload.data)\n break\n }\n case 'full-reload':\n notifyListeners('vite:beforeFullReload', payload)\n if (payload.path && payload.path.endsWith('.html')) {\n // if html file is edited, only reload the page if the browser is\n // currently on that page.\n const pagePath = location.pathname\n const payloadPath = base + payload.path.slice(1)\n if (\n pagePath === payloadPath ||\n (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)\n ) {\n location.reload()\n }\n return\n } else {\n location.reload()\n }\n break\n case 'prune':\n notifyListeners('vite:beforePrune', payload)\n // After an HMR update, some modules are no longer imported on the page\n // but they may have left behind side effects that need to be cleaned up\n // (.e.g style injections)\n // TODO Trigger their dispose callbacks.\n payload.paths.forEach((path) => {\n const fn = pruneMap.get(path)\n if (fn) {\n fn(dataMap.get(path))\n }\n })\n break\n case 'error': {\n notifyListeners('vite:error', payload)\n const err = payload.err\n if (enableOverlay) {\n createErrorOverlay(err)\n } else {\n console.error(\n `[vite] Internal Server Error\\n${err.message}\\n${err.stack}`\n )\n }\n break\n }\n default: {\n const check: never = payload\n return check\n }\n }\n}\n\nfunction notifyListeners(\n event: 'vite:beforeUpdate',\n payload: UpdatePayload\n): void\nfunction notifyListeners(event: 'vite:beforePrune', payload: PrunePayload): void\nfunction notifyListeners(\n event: 'vite:beforeFullReload',\n payload: FullReloadPayload\n): void\nfunction notifyListeners(event: 'vite:error', payload: ErrorPayload): void\nfunction notifyListeners(\n event: CustomEventName,\n data: any\n): void\nfunction notifyListeners(event: string, data: any): void {\n const cbs = customListenersMap.get(event)\n if (cbs) {\n cbs.forEach((cb) => cb(data))\n }\n}\n\nconst enableOverlay = __HMR_ENABLE_OVERLAY__\n\nfunction createErrorOverlay(err: ErrorPayload['err']) {\n if (!enableOverlay) return\n clearErrorOverlay()\n document.body.appendChild(new ErrorOverlay(err))\n}\n\nfunction clearErrorOverlay() {\n document\n .querySelectorAll(overlayId)\n .forEach((n) => (n as ErrorOverlay).close())\n}\n\nfunction hasErrorOverlay() {\n return document.querySelectorAll(overlayId).length\n}\n\nlet pending = false\nlet queued: Promise<(() => void) | undefined>[] = []\n\n/**\n * buffer multiple hot updates triggered by the same src change\n * so that they are invoked in the same order they were sent.\n * (otherwise the order may be inconsistent because of the http request round trip)\n */\nasync function queueUpdate(p: Promise<(() => void) | undefined>) {\n queued.push(p)\n if (!pending) {\n pending = true\n await Promise.resolve()\n pending = false\n const loading = [...queued]\n queued = []\n ;(await Promise.all(loading)).forEach((fn) => fn && fn())\n }\n}\n\nasync function waitForSuccessfulPing(ms = 1000) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n await fetch(`${base}__vite_ping`)\n break\n } catch (e) {\n await new Promise((resolve) => setTimeout(resolve, ms))\n }\n }\n}\n\n// ping server\nsocket.addEventListener('close', async ({ wasClean }) => {\n if (wasClean) return\n console.log(`[vite] server connection lost. polling for restart...`)\n await waitForSuccessfulPing()\n location.reload()\n})\n\n// https://wicg.github.io/construct-stylesheets\nconst supportsConstructedSheet = (() => {\n try {\n // new CSSStyleSheet()\n // return true\n } catch (e) {}\n return false\n})()\n\nconst sheetsMap = new Map()\n\nexport function updateStyle(id: string, content: string): void {\n let style = sheetsMap.get(id)\n if (supportsConstructedSheet && !content.includes('@import')) {\n if (style && !(style instanceof CSSStyleSheet)) {\n removeStyle(id)\n style = undefined\n }\n\n if (!style) {\n style = new CSSStyleSheet()\n style.replaceSync(content)\n // @ts-ignore\n document.adoptedStyleSheets = [...document.adoptedStyleSheets, style]\n } else {\n style.replaceSync(content)\n }\n } else {\n if (style && !(style instanceof HTMLStyleElement)) {\n removeStyle(id)\n style = undefined\n }\n\n if (!style) {\n style = document.createElement('style')\n style.setAttribute('type', 'text/css')\n style.innerHTML = content\n document.head.appendChild(style)\n } else {\n style.innerHTML = content\n }\n }\n sheetsMap.set(id, style)\n}\n\nexport function removeStyle(id: string): void {\n const style = sheetsMap.get(id)\n if (style) {\n if (style instanceof CSSStyleSheet) {\n // @ts-ignore\n const index = document.adoptedStyleSheets.indexOf(style)\n // @ts-ignore\n document.adoptedStyleSheets = document.adoptedStyleSheets.filter(\n (s: CSSStyleSheet) => s !== style\n )\n } else {\n document.head.removeChild(style)\n }\n sheetsMap.delete(id)\n }\n}\n\nasync function fetchUpdate({ path, acceptedPath, timestamp }: Update) {\n const mod = hotModulesMap.get(path)\n if (!mod) {\n // In a code-splitting project,\n // it is common that the hot-updating module is not loaded yet.\n // https://github.com/vitejs/vite/issues/721\n return\n }\n\n const moduleMap = new Map()\n const isSelfUpdate = path === acceptedPath\n\n // make sure we only import each dep once\n const modulesToUpdate = new Set()\n if (isSelfUpdate) {\n // self update - only update self\n modulesToUpdate.add(path)\n } else {\n // dep update\n for (const { deps } of mod.callbacks) {\n deps.forEach((dep) => {\n if (acceptedPath === dep) {\n modulesToUpdate.add(dep)\n }\n })\n }\n }\n\n // determine the qualified callbacks before we re-import the modules\n const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {\n return deps.some((dep) => modulesToUpdate.has(dep))\n })\n\n await Promise.all(\n Array.from(modulesToUpdate).map(async (dep) => {\n const disposer = disposeMap.get(dep)\n if (disposer) await disposer(dataMap.get(dep))\n const [path, query] = dep.split(`?`)\n try {\n const newMod = await import(\n /* @vite-ignore */\n base +\n path.slice(1) +\n `?import&t=${timestamp}${query ? `&${query}` : ''}`\n )\n moduleMap.set(dep, newMod)\n } catch (e) {\n warnFailedFetch(e, dep)\n }\n })\n )\n\n return () => {\n for (const { deps, fn } of qualifiedCallbacks) {\n fn(deps.map((dep) => moduleMap.get(dep)))\n }\n const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`\n console.log(`[vite] hot updated: ${loggedPath}`)\n }\n}\n\ninterface HotModule {\n id: string\n callbacks: HotCallback[]\n}\n\ninterface HotCallback {\n // the dependencies must be fetchable paths\n deps: string[]\n fn: (modules: object[]) => void\n}\n\nconst hotModulesMap = new Map()\nconst disposeMap = new Map void | Promise>()\nconst pruneMap = new Map void | Promise>()\nconst dataMap = new Map()\nconst customListenersMap = new Map void)[]>()\nconst ctxToListenersMap = new Map<\n string,\n Map void)[]>\n>()\n\n// Just infer the return type for now\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport const createHotContext = (ownerPath: string) => {\n if (!dataMap.has(ownerPath)) {\n dataMap.set(ownerPath, {})\n }\n\n // when a file is hot updated, a new context is created\n // clear its stale callbacks\n const mod = hotModulesMap.get(ownerPath)\n if (mod) {\n mod.callbacks = []\n }\n\n // clear stale custom event listeners\n const staleListeners = ctxToListenersMap.get(ownerPath)\n if (staleListeners) {\n for (const [event, staleFns] of staleListeners) {\n const listeners = customListenersMap.get(event)\n if (listeners) {\n customListenersMap.set(\n event,\n listeners.filter((l) => !staleFns.includes(l))\n )\n }\n }\n }\n\n const newListeners = new Map()\n ctxToListenersMap.set(ownerPath, newListeners)\n\n function acceptDeps(deps: string[], callback: HotCallback['fn'] = () => {}) {\n const mod: HotModule = hotModulesMap.get(ownerPath) || {\n id: ownerPath,\n callbacks: []\n }\n mod.callbacks.push({\n deps,\n fn: callback\n })\n hotModulesMap.set(ownerPath, mod)\n }\n\n const hot = {\n get data() {\n return dataMap.get(ownerPath)\n },\n\n accept(deps: any, callback?: any) {\n if (typeof deps === 'function' || !deps) {\n // self-accept: hot.accept(() => {})\n acceptDeps([ownerPath], ([mod]) => deps && deps(mod))\n } else if (typeof deps === 'string') {\n // explicit deps\n acceptDeps([deps], ([mod]) => callback && callback(mod))\n } else if (Array.isArray(deps)) {\n acceptDeps(deps, callback)\n } else {\n throw new Error(`invalid hot.accept() usage.`)\n }\n },\n\n acceptDeps() {\n throw new Error(\n `hot.acceptDeps() is deprecated. ` +\n `Use hot.accept() with the same signature instead.`\n )\n },\n\n dispose(cb: (data: any) => void) {\n disposeMap.set(ownerPath, cb)\n },\n\n prune(cb: (data: any) => void) {\n pruneMap.set(ownerPath, cb)\n },\n\n // TODO\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n decline() {},\n\n invalidate() {\n // TODO should tell the server to re-perform hmr propagation\n // from this module as root\n location.reload()\n },\n\n // custom events\n on: (event: string, cb: (data: any) => void) => {\n const addToMap = (map: Map) => {\n const existing = map.get(event) || []\n existing.push(cb)\n map.set(event, existing)\n }\n addToMap(customListenersMap)\n addToMap(newListeners)\n }\n }\n\n return hot\n}\n\n/**\n * urls here are dynamic import() urls that couldn't be statically analyzed\n */\nexport function injectQuery(url: string, queryToInject: string): string {\n // skip urls that won't be handled by vite\n if (!url.startsWith('.') && !url.startsWith('/')) {\n return url\n }\n\n // can't use pathname from URL since it may be relative like ../\n const pathname = url.replace(/#.*$/, '').replace(/\\?.*$/, '')\n const { search, hash } = new URL(url, 'http://vitejs.dev')\n\n return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${\n hash || ''\n }`\n}\n"],"names":[],"mappings":";;AAEA,MAAM,QAAQ,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4GzB,CAAA;AAED,MAAM,MAAM,GAAG,gCAAgC,CAAA;AAC/C,MAAM,WAAW,GAAG,0CAA0C,CAAA;MAEjD,YAAa,SAAQ,WAAW;IAG3C,YAAY,GAAwB;;QAClC,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;QAC/C,IAAI,CAAC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;QAE9B,WAAW,CAAC,SAAS,GAAG,CAAC,CAAA;QACzB,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK,IAAI,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QACzD,MAAM,OAAO,GAAG,QAAQ;cACpB,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;cACpC,GAAG,CAAC,OAAO,CAAA;QACf,IAAI,GAAG,CAAC,MAAM,EAAE;YACd,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,GAAG,CAAC,MAAM,IAAI,CAAC,CAAA;SAChD;QACD,IAAI,CAAC,IAAI,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,EAAE,QAAQ,CAAC,CAAA;aACzB,CAAA;YACD,QAAQ,CAAC,kBAAkB,CAAC,CAAA;YAC5B,QAAQ,CAAC,YAAY,CAAC,CAAA;SACvB;KACF,CAAA;IAED,OAAO,GAAG,CAAA;AACZ,EAAC;AAED;;;SAGgB,WAAW,CAAC,GAAW,EAAE,aAAqB;;IAE5D,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;QAChD,OAAO,GAAG,CAAA;KACX;;IAGD,MAAM,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;IAC7D,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,mBAAmB,CAAC,CAAA;IAE1D,OAAO,GAAG,QAAQ,IAAI,aAAa,GAAG,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,GACvE,IAAI,IAAI,EACV,EAAE,CAAA;AACJ;;;;"} \ No newline at end of file diff --git a/node_modules/vite/dist/client/env.mjs b/node_modules/vite/dist/client/env.mjs new file mode 100644 index 0000000..1b3a7d2 --- /dev/null +++ b/node_modules/vite/dist/client/env.mjs @@ -0,0 +1,30 @@ +const context = (() => { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else { + return Function('return this')(); + } +})(); +// assign defines +const defines = __DEFINES__; +Object.keys(defines).forEach((key) => { + const segments = key.split('.'); + let target = context; + for (let i = 0; i < segments.length; i++) { + const segment = segments[i]; + if (i === segments.length - 1) { + target[segment] = defines[key]; + } + else { + target = target[segment] || (target[segment] = {}); + } + } +}); +//# sourceMappingURL=env.mjs.map diff --git a/node_modules/vite/dist/client/env.mjs.map b/node_modules/vite/dist/client/env.mjs.map new file mode 100644 index 0000000..592b523 --- /dev/null +++ b/node_modules/vite/dist/client/env.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"env.mjs","sources":["../../src/client/env.ts"],"sourcesContent":["declare const __MODE__: string\ndeclare const __DEFINES__: Record\n\nconst context = (() => {\n if (typeof globalThis !== 'undefined') {\n return globalThis\n } else if (typeof self !== 'undefined') {\n return self\n } else if (typeof window !== 'undefined') {\n return window\n } else {\n return Function('return this')()\n }\n})()\n\n// assign defines\nconst defines = __DEFINES__\nObject.keys(defines).forEach((key) => {\n const segments = key.split('.')\n let target = context\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]\n if (i === segments.length - 1) {\n target[segment] = defines[key]\n } else {\n target = target[segment] || (target[segment] = {})\n }\n }\n})\n"],"names":[],"mappings":"AAGA,MAAM,OAAO,GAAG,CAAC;IACf,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE;QACrC,OAAO,UAAU,CAAA;KAClB;SAAM,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QACtC,OAAO,IAAI,CAAA;KACZ;SAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QACxC,OAAO,MAAM,CAAA;KACd;SAAM;QACL,OAAO,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAA;KACjC;AACH,CAAC,GAAG,CAAA;AAEJ;AACA,MAAM,OAAO,GAAG,WAAW,CAAA;AAC3B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG;IAC/B,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC/B,IAAI,MAAM,GAAG,OAAO,CAAA;IACpB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACxC,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;QAC3B,IAAI,CAAC,KAAK,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;YAC7B,MAAM,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAA;SAC/B;aAAM;YACL,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;SACnD;KACF;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/vite/dist/node/chunks/dep-0d2f9464.js b/node_modules/vite/dist/node/chunks/dep-0d2f9464.js new file mode 100644 index 0000000..cd34794 --- /dev/null +++ b/node_modules/vite/dist/node/chunks/dep-0d2f9464.js @@ -0,0 +1,733 @@ +'use strict'; + +var path$3 = require('path'); +var resolve$2 = require('resolve'); +var fs$1 = require('fs'); +var index$1 = require('./dep-e36486f6.js'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; } + +var path__default = /*#__PURE__*/_interopDefaultLegacy(path$3); +var resolve__default = /*#__PURE__*/_interopDefaultLegacy(resolve$2); +var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1); + +var joinMedia$1 = function (parentMedia, childMedia) { + if (!parentMedia.length && childMedia.length) return childMedia + if (parentMedia.length && !childMedia.length) return parentMedia + if (!parentMedia.length && !childMedia.length) return [] + + const media = []; + + parentMedia.forEach(parentItem => { + childMedia.forEach(childItem => { + if (parentItem !== childItem) media.push(`${parentItem} and ${childItem}`); + }); + }); + + return media +}; + +// external tooling +const resolve$1 = resolve__default; + +const moduleDirectories = ["web_modules", "node_modules"]; + +function resolveModule(id, opts) { + return new Promise((res, rej) => { + resolve$1(id, opts, (err, path) => (err ? rej(err) : res(path))); + }) +} + +var resolveId$1 = function (id, base, options) { + const paths = options.path; + + const resolveOpts = { + basedir: base, + moduleDirectory: moduleDirectories.concat(options.addModulesDirectories), + paths, + extensions: [".css"], + packageFilter: function processPackage(pkg) { + if (pkg.style) pkg.main = pkg.style; + else if (!pkg.main || !/\.css$/.test(pkg.main)) pkg.main = "index.css"; + return pkg + }, + preserveSymlinks: false, + }; + + return resolveModule(`./${id}`, resolveOpts) + .catch(() => resolveModule(id, resolveOpts)) + .catch(() => { + if (paths.indexOf(base) === -1) paths.unshift(base); + + throw new Error( + `Failed to find '${id}' + in [ + ${paths.join(",\n ")} + ]` + ) + }) +}; + +var readCache$1 = {exports: {}}; + +var pify$2 = {exports: {}}; + +var processFn = function (fn, P, opts) { + return function () { + var that = this; + var args = new Array(arguments.length); + + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + return new P(function (resolve, reject) { + args.push(function (err, result) { + if (err) { + reject(err); + } else if (opts.multiArgs) { + var results = new Array(arguments.length - 1); + + for (var i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); + } + }); + + fn.apply(that, args); + }); + }; +}; + +var pify$1 = pify$2.exports = function (obj, P, opts) { + if (typeof P !== 'function') { + opts = P; + P = Promise; + } + + opts = opts || {}; + opts.exclude = opts.exclude || [/.+Sync$/]; + + var filter = function (key) { + var match = function (pattern) { + return typeof pattern === 'string' ? key === pattern : pattern.test(key); + }; + + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + var ret = typeof obj === 'function' ? function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, P, opts).apply(this, arguments); + } : {}; + + return Object.keys(obj).reduce(function (ret, key) { + var x = obj[key]; + + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x; + + return ret; + }, ret); +}; + +pify$1.all = pify$1; + +var fs = fs__default; +var path$2 = path__default; +var pify = pify$2.exports; + +var stat = pify(fs.stat); +var readFile = pify(fs.readFile); +var resolve = path$2.resolve; + +var cache = Object.create(null); + +function convert(content, encoding) { + if (Buffer.isEncoding(encoding)) { + return content.toString(encoding); + } + return content; +} + +readCache$1.exports = function (path, encoding) { + path = resolve(path); + + return stat(path).then(function (stats) { + var item = cache[path]; + + if (item && item.mtime.getTime() === stats.mtime.getTime()) { + return convert(item.content, encoding); + } + + return readFile(path).then(function (data) { + cache[path] = { + mtime: stats.mtime, + content: data + }; + + return convert(data, encoding); + }); + }).catch(function (err) { + cache[path] = null; + return Promise.reject(err); + }); +}; + +readCache$1.exports.sync = function (path, encoding) { + path = resolve(path); + + try { + var stats = fs.statSync(path); + var item = cache[path]; + + if (item && item.mtime.getTime() === stats.mtime.getTime()) { + return convert(item.content, encoding); + } + + var data = fs.readFileSync(path); + + cache[path] = { + mtime: stats.mtime, + content: data + }; + + return convert(data, encoding); + } catch (err) { + cache[path] = null; + throw err; + } + +}; + +readCache$1.exports.get = function (path, encoding) { + path = resolve(path); + if (cache[path]) { + return convert(cache[path].content, encoding); + } + return null; +}; + +readCache$1.exports.clear = function () { + cache = Object.create(null); +}; + +const readCache = readCache$1.exports; + +var loadContent$1 = filename => readCache(filename, "utf-8"); + +// builtin tooling +const path$1 = path__default; + +// placeholder tooling +let sugarss; + +var processContent$1 = function processContent( + result, + content, + filename, + options, + postcss +) { + const { plugins } = options; + const ext = path$1.extname(filename); + + const parserList = []; + + // SugarSS support: + if (ext === ".sss") { + if (!sugarss) { + try { + sugarss = eval('require')('sugarss'); + } catch {} // Ignore + } + if (sugarss) + return runPostcss(postcss, content, filename, plugins, [sugarss]) + } + + // Syntax support: + if (result.opts.syntax && result.opts.syntax.parse) { + parserList.push(result.opts.syntax.parse); + } + + // Parser support: + if (result.opts.parser) parserList.push(result.opts.parser); + // Try the default as a last resort: + parserList.push(null); + + return runPostcss(postcss, content, filename, plugins, parserList) +}; + +function runPostcss(postcss, content, filename, plugins, parsers, index) { + if (!index) index = 0; + return postcss(plugins) + .process(content, { + from: filename, + parser: parsers[index], + }) + .catch(err => { + // If there's an error, try the next parser + index++; + // If there are no parsers left, throw it + if (index === parsers.length) throw err + return runPostcss(postcss, content, filename, plugins, parsers, index) + }) +} + +// external tooling +const valueParser = index$1.lib; + +// extended tooling +const { stringify } = valueParser; + +function split(params, start) { + const list = []; + const last = params.reduce((item, node, index) => { + if (index < start) return "" + if (node.type === "div" && node.value === ",") { + list.push(item); + return "" + } + return item + stringify(node) + }, ""); + list.push(last); + return list +} + +var parseStatements$1 = function (result, styles) { + const statements = []; + let nodes = []; + + styles.each(node => { + let stmt; + if (node.type === "atrule") { + if (node.name === "import") stmt = parseImport(result, node); + else if (node.name === "media") stmt = parseMedia(result, node); + else if (node.name === "charset") stmt = parseCharset(result, node); + } + + if (stmt) { + if (nodes.length) { + statements.push({ + type: "nodes", + nodes, + media: [], + }); + nodes = []; + } + statements.push(stmt); + } else nodes.push(node); + }); + + if (nodes.length) { + statements.push({ + type: "nodes", + nodes, + media: [], + }); + } + + return statements +}; + +function parseMedia(result, atRule) { + const params = valueParser(atRule.params).nodes; + return { + type: "media", + node: atRule, + media: split(params, 0), + } +} + +function parseCharset(result, atRule) { + if (atRule.prev()) { + return result.warn("@charset must precede all other statements", { + node: atRule, + }) + } + return { + type: "charset", + node: atRule, + media: [], + } +} + +function parseImport(result, atRule) { + let prev = atRule.prev(); + if (prev) { + do { + if ( + prev.type !== "comment" && + (prev.type !== "atrule" || + (prev.name !== "import" && prev.name !== "charset")) + ) { + return result.warn( + "@import must precede all other statements (besides @charset)", + { node: atRule } + ) + } + prev = prev.prev(); + } while (prev) + } + + if (atRule.nodes) { + return result.warn( + "It looks like you didn't end your @import statement correctly. " + + "Child nodes are attached to it.", + { node: atRule } + ) + } + + const params = valueParser(atRule.params).nodes; + const stmt = { + type: "import", + node: atRule, + media: [], + }; + + // prettier-ignore + if ( + !params.length || + ( + params[0].type !== "string" || + !params[0].value + ) && + ( + params[0].type !== "function" || + params[0].value !== "url" || + !params[0].nodes.length || + !params[0].nodes[0].value + ) + ) { + return result.warn(`Unable to find uri in '${ atRule.toString() }'`, { + node: atRule, + }) + } + + if (params[0].type === "string") stmt.uri = params[0].value; + else stmt.uri = params[0].nodes[0].value; + stmt.fullUri = stringify(params[0]); + + if (params.length > 2) { + if (params[1].type !== "space") { + return result.warn("Invalid import media statement", { node: atRule }) + } + stmt.media = split(params, 2); + } + + return stmt +} + +// builtin tooling +const path = path__default; + +// internal tooling +const joinMedia = joinMedia$1; +const resolveId = resolveId$1; +const loadContent = loadContent$1; +const processContent = processContent$1; +const parseStatements = parseStatements$1; + +function AtImport(options) { + options = { + root: process.cwd(), + path: [], + skipDuplicates: true, + resolve: resolveId, + load: loadContent, + plugins: [], + addModulesDirectories: [], + ...options, + }; + + options.root = path.resolve(options.root); + + // convert string to an array of a single element + if (typeof options.path === "string") options.path = [options.path]; + + if (!Array.isArray(options.path)) options.path = []; + + options.path = options.path.map(p => path.resolve(options.root, p)); + + return { + postcssPlugin: "postcss-import", + Once(styles, { result, atRule, postcss }) { + const state = { + importedFiles: {}, + hashFiles: {}, + }; + + if (styles.source && styles.source.input && styles.source.input.file) { + state.importedFiles[styles.source.input.file] = {}; + } + + if (options.plugins && !Array.isArray(options.plugins)) { + throw new Error("plugins option must be an array") + } + + return parseStyles(result, styles, options, state, []).then(bundle => { + applyRaws(bundle); + applyMedia(bundle); + applyStyles(bundle, styles); + }) + + function applyRaws(bundle) { + bundle.forEach((stmt, index) => { + if (index === 0) return + + if (stmt.parent) { + const { before } = stmt.parent.node.raws; + if (stmt.type === "nodes") stmt.nodes[0].raws.before = before; + else stmt.node.raws.before = before; + } else if (stmt.type === "nodes") { + stmt.nodes[0].raws.before = stmt.nodes[0].raws.before || "\n"; + } + }); + } + + function applyMedia(bundle) { + bundle.forEach(stmt => { + if (!stmt.media.length || stmt.type === "charset") return + if (stmt.type === "import") { + stmt.node.params = `${stmt.fullUri} ${stmt.media.join(", ")}`; + } else if (stmt.type === "media") + stmt.node.params = stmt.media.join(", "); + else { + const { nodes } = stmt; + const { parent } = nodes[0]; + const mediaNode = atRule({ + name: "media", + params: stmt.media.join(", "), + source: parent.source, + }); + + parent.insertBefore(nodes[0], mediaNode); + + // remove nodes + nodes.forEach(node => { + node.parent = undefined; + }); + + // better output + nodes[0].raws.before = nodes[0].raws.before || "\n"; + + // wrap new rules with media query + mediaNode.append(nodes); + + stmt.type = "media"; + stmt.node = mediaNode; + delete stmt.nodes; + } + }); + } + + function applyStyles(bundle, styles) { + styles.nodes = []; + + // Strip additional statements. + bundle.forEach(stmt => { + if (["charset", "import", "media"].includes(stmt.type)) { + stmt.node.parent = undefined; + styles.append(stmt.node); + } else if (stmt.type === "nodes") { + stmt.nodes.forEach(node => { + node.parent = undefined; + styles.append(node); + }); + } + }); + } + + function parseStyles(result, styles, options, state, media) { + const statements = parseStatements(result, styles); + + return Promise.resolve(statements) + .then(stmts => { + // process each statement in series + return stmts.reduce((promise, stmt) => { + return promise.then(() => { + stmt.media = joinMedia(media, stmt.media || []); + + // skip protocol base uri (protocol://url) or protocol-relative + if ( + stmt.type !== "import" || + /^(?:[a-z]+:)?\/\//i.test(stmt.uri) + ) { + return + } + + if (options.filter && !options.filter(stmt.uri)) { + // rejected by filter + return + } + + return resolveImportId(result, stmt, options, state) + }) + }, Promise.resolve()) + }) + .then(() => { + let charset; + const imports = []; + const bundle = []; + + function handleCharset(stmt) { + if (!charset) charset = stmt; + // charsets aren't case-sensitive, so convert to lower case to compare + else if ( + stmt.node.params.toLowerCase() !== + charset.node.params.toLowerCase() + ) { + throw new Error( + `Incompatable @charset statements: + ${stmt.node.params} specified in ${stmt.node.source.input.file} + ${charset.node.params} specified in ${charset.node.source.input.file}` + ) + } + } + + // squash statements and their children + statements.forEach(stmt => { + if (stmt.type === "charset") handleCharset(stmt); + else if (stmt.type === "import") { + if (stmt.children) { + stmt.children.forEach((child, index) => { + if (child.type === "import") imports.push(child); + else if (child.type === "charset") handleCharset(child); + else bundle.push(child); + // For better output + if (index === 0) child.parent = stmt; + }); + } else imports.push(stmt); + } else if (stmt.type === "media" || stmt.type === "nodes") { + bundle.push(stmt); + } + }); + + return charset + ? [charset, ...imports.concat(bundle)] + : imports.concat(bundle) + }) + } + + function resolveImportId(result, stmt, options, state) { + const atRule = stmt.node; + let sourceFile; + if (atRule.source && atRule.source.input && atRule.source.input.file) { + sourceFile = atRule.source.input.file; + } + const base = sourceFile + ? path.dirname(atRule.source.input.file) + : options.root; + + return Promise.resolve(options.resolve(stmt.uri, base, options)) + .then(paths => { + if (!Array.isArray(paths)) paths = [paths]; + // Ensure that each path is absolute: + return Promise.all( + paths.map(file => { + return !path.isAbsolute(file) + ? resolveId(file, base, options) + : file + }) + ) + }) + .then(resolved => { + // Add dependency messages: + resolved.forEach(file => { + result.messages.push({ + type: "dependency", + plugin: "postcss-import", + file, + parent: sourceFile, + }); + }); + + return Promise.all( + resolved.map(file => { + return loadImportContent(result, stmt, file, options, state) + }) + ) + }) + .then(result => { + // Merge loaded statements + stmt.children = result.reduce((result, statements) => { + return statements ? result.concat(statements) : result + }, []); + }) + } + + function loadImportContent(result, stmt, filename, options, state) { + const atRule = stmt.node; + const { media } = stmt; + if (options.skipDuplicates) { + // skip files already imported at the same scope + if ( + state.importedFiles[filename] && + state.importedFiles[filename][media] + ) { + return + } + + // save imported files to skip them next time + if (!state.importedFiles[filename]) state.importedFiles[filename] = {}; + state.importedFiles[filename][media] = true; + } + + return Promise.resolve(options.load(filename, options)).then( + content => { + if (content.trim() === "") { + result.warn(`${filename} is empty`, { node: atRule }); + return + } + + // skip previous imported files not containing @import rules + if (state.hashFiles[content] && state.hashFiles[content][media]) + return + + return processContent( + result, + content, + filename, + options, + postcss + ).then(importedResult => { + const styles = importedResult.root; + result.messages = result.messages.concat(importedResult.messages); + + if (options.skipDuplicates) { + const hasImport = styles.some(child => { + return child.type === "atrule" && child.name === "import" + }); + if (!hasImport) { + // save hash files to skip them next time + if (!state.hashFiles[content]) state.hashFiles[content] = {}; + state.hashFiles[content][media] = true; + } + } + + // recursion: import @import from imported file + return parseStyles(result, styles, options, state, media) + }) + } + ) + } + }, + } +} + +AtImport.postcss = true; + +var postcssImport = AtImport; + +var index = /*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), postcssImport, { + 'default': postcssImport +}); + +exports.index = index; +//# sourceMappingURL=dep-0d2f9464.js.map diff --git a/node_modules/vite/dist/node/chunks/dep-0d2f9464.js.map b/node_modules/vite/dist/node/chunks/dep-0d2f9464.js.map new file mode 100644 index 0000000..8b30006 --- /dev/null +++ b/node_modules/vite/dist/node/chunks/dep-0d2f9464.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dep-0d2f9464.js","sources":["../../../../../node_modules/postcss-import/lib/join-media.js","../../../../../node_modules/postcss-import/lib/resolve-id.js","../../../../../node_modules/pify/index.js","../../../../../node_modules/read-cache/index.js","../../../../../node_modules/postcss-import/lib/load-content.js","../../../../../node_modules/postcss-import/lib/process-content.js","../../../../../node_modules/postcss-import/lib/parse-statements.js","../../../../../node_modules/postcss-import/index.js"],"sourcesContent":["\"use strict\"\n\nmodule.exports = function (parentMedia, childMedia) {\n if (!parentMedia.length && childMedia.length) return childMedia\n if (parentMedia.length && !childMedia.length) return parentMedia\n if (!parentMedia.length && !childMedia.length) return []\n\n const media = []\n\n parentMedia.forEach(parentItem => {\n childMedia.forEach(childItem => {\n if (parentItem !== childItem) media.push(`${parentItem} and ${childItem}`)\n })\n })\n\n return media\n}\n","\"use strict\"\n\n// external tooling\nconst resolve = require(\"resolve\")\n\nconst moduleDirectories = [\"web_modules\", \"node_modules\"]\n\nfunction resolveModule(id, opts) {\n return new Promise((res, rej) => {\n resolve(id, opts, (err, path) => (err ? rej(err) : res(path)))\n })\n}\n\nmodule.exports = function (id, base, options) {\n const paths = options.path\n\n const resolveOpts = {\n basedir: base,\n moduleDirectory: moduleDirectories.concat(options.addModulesDirectories),\n paths,\n extensions: [\".css\"],\n packageFilter: function processPackage(pkg) {\n if (pkg.style) pkg.main = pkg.style\n else if (!pkg.main || !/\\.css$/.test(pkg.main)) pkg.main = \"index.css\"\n return pkg\n },\n preserveSymlinks: false,\n }\n\n return resolveModule(`./${id}`, resolveOpts)\n .catch(() => resolveModule(id, resolveOpts))\n .catch(() => {\n if (paths.indexOf(base) === -1) paths.unshift(base)\n\n throw new Error(\n `Failed to find '${id}'\n in [\n ${paths.join(\",\\n \")}\n ]`\n )\n })\n}\n","'use strict';\n\nvar processFn = function (fn, P, opts) {\n\treturn function () {\n\t\tvar that = this;\n\t\tvar args = new Array(arguments.length);\n\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\targs[i] = arguments[i];\n\t\t}\n\n\t\treturn new P(function (resolve, reject) {\n\t\t\targs.push(function (err, result) {\n\t\t\t\tif (err) {\n\t\t\t\t\treject(err);\n\t\t\t\t} else if (opts.multiArgs) {\n\t\t\t\t\tvar results = new Array(arguments.length - 1);\n\n\t\t\t\t\tfor (var i = 1; i < arguments.length; i++) {\n\t\t\t\t\t\tresults[i - 1] = arguments[i];\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(results);\n\t\t\t\t} else {\n\t\t\t\t\tresolve(result);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tfn.apply(that, args);\n\t\t});\n\t};\n};\n\nvar pify = module.exports = function (obj, P, opts) {\n\tif (typeof P !== 'function') {\n\t\topts = P;\n\t\tP = Promise;\n\t}\n\n\topts = opts || {};\n\topts.exclude = opts.exclude || [/.+Sync$/];\n\n\tvar filter = function (key) {\n\t\tvar match = function (pattern) {\n\t\t\treturn typeof pattern === 'string' ? key === pattern : pattern.test(key);\n\t\t};\n\n\t\treturn opts.include ? opts.include.some(match) : !opts.exclude.some(match);\n\t};\n\n\tvar ret = typeof obj === 'function' ? function () {\n\t\tif (opts.excludeMain) {\n\t\t\treturn obj.apply(this, arguments);\n\t\t}\n\n\t\treturn processFn(obj, P, opts).apply(this, arguments);\n\t} : {};\n\n\treturn Object.keys(obj).reduce(function (ret, key) {\n\t\tvar x = obj[key];\n\n\t\tret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;\n\n\t\treturn ret;\n\t}, ret);\n};\n\npify.all = pify;\n","var fs = require('fs');\r\nvar path = require('path');\r\nvar pify = require('pify');\r\n\r\nvar stat = pify(fs.stat);\r\nvar readFile = pify(fs.readFile);\r\nvar resolve = path.resolve;\r\n\r\nvar cache = Object.create(null);\r\n\r\nfunction convert(content, encoding) {\r\n\tif (Buffer.isEncoding(encoding)) {\r\n\t\treturn content.toString(encoding);\r\n\t}\r\n\treturn content;\r\n}\r\n\r\nmodule.exports = function (path, encoding) {\r\n\tpath = resolve(path);\r\n\r\n\treturn stat(path).then(function (stats) {\r\n\t\tvar item = cache[path];\r\n\r\n\t\tif (item && item.mtime.getTime() === stats.mtime.getTime()) {\r\n\t\t\treturn convert(item.content, encoding);\r\n\t\t}\r\n\r\n\t\treturn readFile(path).then(function (data) {\r\n\t\t\tcache[path] = {\r\n\t\t\t\tmtime: stats.mtime,\r\n\t\t\t\tcontent: data\r\n\t\t\t};\r\n\r\n\t\t\treturn convert(data, encoding);\r\n\t\t});\r\n\t}).catch(function (err) {\r\n\t\tcache[path] = null;\r\n\t\treturn Promise.reject(err);\r\n\t});\r\n};\r\n\r\nmodule.exports.sync = function (path, encoding) {\r\n\tpath = resolve(path);\r\n\r\n\ttry {\r\n\t\tvar stats = fs.statSync(path);\r\n\t\tvar item = cache[path];\r\n\r\n\t\tif (item && item.mtime.getTime() === stats.mtime.getTime()) {\r\n\t\t\treturn convert(item.content, encoding);\r\n\t\t}\r\n\r\n\t\tvar data = fs.readFileSync(path);\r\n\r\n\t\tcache[path] = {\r\n\t\t\tmtime: stats.mtime,\r\n\t\t\tcontent: data\r\n\t\t};\r\n\r\n\t\treturn convert(data, encoding);\r\n\t} catch (err) {\r\n\t\tcache[path] = null;\r\n\t\tthrow err;\r\n\t}\r\n\r\n};\r\n\r\nmodule.exports.get = function (path, encoding) {\r\n\tpath = resolve(path);\r\n\tif (cache[path]) {\r\n\t\treturn convert(cache[path].content, encoding);\r\n\t}\r\n\treturn null;\r\n};\r\n\r\nmodule.exports.clear = function () {\r\n\tcache = Object.create(null);\r\n};\r\n","\"use strict\"\n\nconst readCache = require(\"read-cache\")\n\nmodule.exports = filename => readCache(filename, \"utf-8\")\n","\"use strict\"\n\n// builtin tooling\nconst path = require(\"path\")\n\n// placeholder tooling\nlet sugarss\n\nmodule.exports = function processContent(\n result,\n content,\n filename,\n options,\n postcss\n) {\n const { plugins } = options\n const ext = path.extname(filename)\n\n const parserList = []\n\n // SugarSS support:\n if (ext === \".sss\") {\n if (!sugarss) {\n try {\n sugarss = require(\"sugarss\")\n } catch {} // Ignore\n }\n if (sugarss)\n return runPostcss(postcss, content, filename, plugins, [sugarss])\n }\n\n // Syntax support:\n if (result.opts.syntax && result.opts.syntax.parse) {\n parserList.push(result.opts.syntax.parse)\n }\n\n // Parser support:\n if (result.opts.parser) parserList.push(result.opts.parser)\n // Try the default as a last resort:\n parserList.push(null)\n\n return runPostcss(postcss, content, filename, plugins, parserList)\n}\n\nfunction runPostcss(postcss, content, filename, plugins, parsers, index) {\n if (!index) index = 0\n return postcss(plugins)\n .process(content, {\n from: filename,\n parser: parsers[index],\n })\n .catch(err => {\n // If there's an error, try the next parser\n index++\n // If there are no parsers left, throw it\n if (index === parsers.length) throw err\n return runPostcss(postcss, content, filename, plugins, parsers, index)\n })\n}\n","\"use strict\"\n\n// external tooling\nconst valueParser = require(\"postcss-value-parser\")\n\n// extended tooling\nconst { stringify } = valueParser\n\nfunction split(params, start) {\n const list = []\n const last = params.reduce((item, node, index) => {\n if (index < start) return \"\"\n if (node.type === \"div\" && node.value === \",\") {\n list.push(item)\n return \"\"\n }\n return item + stringify(node)\n }, \"\")\n list.push(last)\n return list\n}\n\nmodule.exports = function (result, styles) {\n const statements = []\n let nodes = []\n\n styles.each(node => {\n let stmt\n if (node.type === \"atrule\") {\n if (node.name === \"import\") stmt = parseImport(result, node)\n else if (node.name === \"media\") stmt = parseMedia(result, node)\n else if (node.name === \"charset\") stmt = parseCharset(result, node)\n }\n\n if (stmt) {\n if (nodes.length) {\n statements.push({\n type: \"nodes\",\n nodes,\n media: [],\n })\n nodes = []\n }\n statements.push(stmt)\n } else nodes.push(node)\n })\n\n if (nodes.length) {\n statements.push({\n type: \"nodes\",\n nodes,\n media: [],\n })\n }\n\n return statements\n}\n\nfunction parseMedia(result, atRule) {\n const params = valueParser(atRule.params).nodes\n return {\n type: \"media\",\n node: atRule,\n media: split(params, 0),\n }\n}\n\nfunction parseCharset(result, atRule) {\n if (atRule.prev()) {\n return result.warn(\"@charset must precede all other statements\", {\n node: atRule,\n })\n }\n return {\n type: \"charset\",\n node: atRule,\n media: [],\n }\n}\n\nfunction parseImport(result, atRule) {\n let prev = atRule.prev()\n if (prev) {\n do {\n if (\n prev.type !== \"comment\" &&\n (prev.type !== \"atrule\" ||\n (prev.name !== \"import\" && prev.name !== \"charset\"))\n ) {\n return result.warn(\n \"@import must precede all other statements (besides @charset)\",\n { node: atRule }\n )\n }\n prev = prev.prev()\n } while (prev)\n }\n\n if (atRule.nodes) {\n return result.warn(\n \"It looks like you didn't end your @import statement correctly. \" +\n \"Child nodes are attached to it.\",\n { node: atRule }\n )\n }\n\n const params = valueParser(atRule.params).nodes\n const stmt = {\n type: \"import\",\n node: atRule,\n media: [],\n }\n\n // prettier-ignore\n if (\n !params.length ||\n (\n params[0].type !== \"string\" ||\n !params[0].value\n ) &&\n (\n params[0].type !== \"function\" ||\n params[0].value !== \"url\" ||\n !params[0].nodes.length ||\n !params[0].nodes[0].value\n )\n ) {\n return result.warn(`Unable to find uri in '${ atRule.toString() }'`, {\n node: atRule,\n })\n }\n\n if (params[0].type === \"string\") stmt.uri = params[0].value\n else stmt.uri = params[0].nodes[0].value\n stmt.fullUri = stringify(params[0])\n\n if (params.length > 2) {\n if (params[1].type !== \"space\") {\n return result.warn(\"Invalid import media statement\", { node: atRule })\n }\n stmt.media = split(params, 2)\n }\n\n return stmt\n}\n","\"use strict\"\n// builtin tooling\nconst path = require(\"path\")\n\n// internal tooling\nconst joinMedia = require(\"./lib/join-media\")\nconst resolveId = require(\"./lib/resolve-id\")\nconst loadContent = require(\"./lib/load-content\")\nconst processContent = require(\"./lib/process-content\")\nconst parseStatements = require(\"./lib/parse-statements\")\n\nfunction AtImport(options) {\n options = {\n root: process.cwd(),\n path: [],\n skipDuplicates: true,\n resolve: resolveId,\n load: loadContent,\n plugins: [],\n addModulesDirectories: [],\n ...options,\n }\n\n options.root = path.resolve(options.root)\n\n // convert string to an array of a single element\n if (typeof options.path === \"string\") options.path = [options.path]\n\n if (!Array.isArray(options.path)) options.path = []\n\n options.path = options.path.map(p => path.resolve(options.root, p))\n\n return {\n postcssPlugin: \"postcss-import\",\n Once(styles, { result, atRule, postcss }) {\n const state = {\n importedFiles: {},\n hashFiles: {},\n }\n\n if (styles.source && styles.source.input && styles.source.input.file) {\n state.importedFiles[styles.source.input.file] = {}\n }\n\n if (options.plugins && !Array.isArray(options.plugins)) {\n throw new Error(\"plugins option must be an array\")\n }\n\n return parseStyles(result, styles, options, state, []).then(bundle => {\n applyRaws(bundle)\n applyMedia(bundle)\n applyStyles(bundle, styles)\n })\n\n function applyRaws(bundle) {\n bundle.forEach((stmt, index) => {\n if (index === 0) return\n\n if (stmt.parent) {\n const { before } = stmt.parent.node.raws\n if (stmt.type === \"nodes\") stmt.nodes[0].raws.before = before\n else stmt.node.raws.before = before\n } else if (stmt.type === \"nodes\") {\n stmt.nodes[0].raws.before = stmt.nodes[0].raws.before || \"\\n\"\n }\n })\n }\n\n function applyMedia(bundle) {\n bundle.forEach(stmt => {\n if (!stmt.media.length || stmt.type === \"charset\") return\n if (stmt.type === \"import\") {\n stmt.node.params = `${stmt.fullUri} ${stmt.media.join(\", \")}`\n } else if (stmt.type === \"media\")\n stmt.node.params = stmt.media.join(\", \")\n else {\n const { nodes } = stmt\n const { parent } = nodes[0]\n const mediaNode = atRule({\n name: \"media\",\n params: stmt.media.join(\", \"),\n source: parent.source,\n })\n\n parent.insertBefore(nodes[0], mediaNode)\n\n // remove nodes\n nodes.forEach(node => {\n node.parent = undefined\n })\n\n // better output\n nodes[0].raws.before = nodes[0].raws.before || \"\\n\"\n\n // wrap new rules with media query\n mediaNode.append(nodes)\n\n stmt.type = \"media\"\n stmt.node = mediaNode\n delete stmt.nodes\n }\n })\n }\n\n function applyStyles(bundle, styles) {\n styles.nodes = []\n\n // Strip additional statements.\n bundle.forEach(stmt => {\n if ([\"charset\", \"import\", \"media\"].includes(stmt.type)) {\n stmt.node.parent = undefined\n styles.append(stmt.node)\n } else if (stmt.type === \"nodes\") {\n stmt.nodes.forEach(node => {\n node.parent = undefined\n styles.append(node)\n })\n }\n })\n }\n\n function parseStyles(result, styles, options, state, media) {\n const statements = parseStatements(result, styles)\n\n return Promise.resolve(statements)\n .then(stmts => {\n // process each statement in series\n return stmts.reduce((promise, stmt) => {\n return promise.then(() => {\n stmt.media = joinMedia(media, stmt.media || [])\n\n // skip protocol base uri (protocol://url) or protocol-relative\n if (\n stmt.type !== \"import\" ||\n /^(?:[a-z]+:)?\\/\\//i.test(stmt.uri)\n ) {\n return\n }\n\n if (options.filter && !options.filter(stmt.uri)) {\n // rejected by filter\n return\n }\n\n return resolveImportId(result, stmt, options, state)\n })\n }, Promise.resolve())\n })\n .then(() => {\n let charset\n const imports = []\n const bundle = []\n\n function handleCharset(stmt) {\n if (!charset) charset = stmt\n // charsets aren't case-sensitive, so convert to lower case to compare\n else if (\n stmt.node.params.toLowerCase() !==\n charset.node.params.toLowerCase()\n ) {\n throw new Error(\n `Incompatable @charset statements:\n ${stmt.node.params} specified in ${stmt.node.source.input.file}\n ${charset.node.params} specified in ${charset.node.source.input.file}`\n )\n }\n }\n\n // squash statements and their children\n statements.forEach(stmt => {\n if (stmt.type === \"charset\") handleCharset(stmt)\n else if (stmt.type === \"import\") {\n if (stmt.children) {\n stmt.children.forEach((child, index) => {\n if (child.type === \"import\") imports.push(child)\n else if (child.type === \"charset\") handleCharset(child)\n else bundle.push(child)\n // For better output\n if (index === 0) child.parent = stmt\n })\n } else imports.push(stmt)\n } else if (stmt.type === \"media\" || stmt.type === \"nodes\") {\n bundle.push(stmt)\n }\n })\n\n return charset\n ? [charset, ...imports.concat(bundle)]\n : imports.concat(bundle)\n })\n }\n\n function resolveImportId(result, stmt, options, state) {\n const atRule = stmt.node\n let sourceFile\n if (atRule.source && atRule.source.input && atRule.source.input.file) {\n sourceFile = atRule.source.input.file\n }\n const base = sourceFile\n ? path.dirname(atRule.source.input.file)\n : options.root\n\n return Promise.resolve(options.resolve(stmt.uri, base, options))\n .then(paths => {\n if (!Array.isArray(paths)) paths = [paths]\n // Ensure that each path is absolute:\n return Promise.all(\n paths.map(file => {\n return !path.isAbsolute(file)\n ? resolveId(file, base, options)\n : file\n })\n )\n })\n .then(resolved => {\n // Add dependency messages:\n resolved.forEach(file => {\n result.messages.push({\n type: \"dependency\",\n plugin: \"postcss-import\",\n file,\n parent: sourceFile,\n })\n })\n\n return Promise.all(\n resolved.map(file => {\n return loadImportContent(result, stmt, file, options, state)\n })\n )\n })\n .then(result => {\n // Merge loaded statements\n stmt.children = result.reduce((result, statements) => {\n return statements ? result.concat(statements) : result\n }, [])\n })\n }\n\n function loadImportContent(result, stmt, filename, options, state) {\n const atRule = stmt.node\n const { media } = stmt\n if (options.skipDuplicates) {\n // skip files already imported at the same scope\n if (\n state.importedFiles[filename] &&\n state.importedFiles[filename][media]\n ) {\n return\n }\n\n // save imported files to skip them next time\n if (!state.importedFiles[filename]) state.importedFiles[filename] = {}\n state.importedFiles[filename][media] = true\n }\n\n return Promise.resolve(options.load(filename, options)).then(\n content => {\n if (content.trim() === \"\") {\n result.warn(`${filename} is empty`, { node: atRule })\n return\n }\n\n // skip previous imported files not containing @import rules\n if (state.hashFiles[content] && state.hashFiles[content][media])\n return\n\n return processContent(\n result,\n content,\n filename,\n options,\n postcss\n ).then(importedResult => {\n const styles = importedResult.root\n result.messages = result.messages.concat(importedResult.messages)\n\n if (options.skipDuplicates) {\n const hasImport = styles.some(child => {\n return child.type === \"atrule\" && child.name === \"import\"\n })\n if (!hasImport) {\n // save hash files to skip them next time\n if (!state.hashFiles[content]) state.hashFiles[content] = {}\n state.hashFiles[content][media] = true\n }\n }\n\n // recursion: import @import from imported file\n return parseStyles(result, styles, options, state, media)\n })\n }\n )\n }\n },\n }\n}\n\nAtImport.postcss = true\n\nmodule.exports = AtImport\n"],"names":["joinMedia","resolve","require$$0","resolveId","pify","pifyModule","path","require$$1","require$$2","readCacheModule","loadContent","processContent","parseStatements","require$$3","require$$4","require$$5"],"mappings":";;;;;;;;;;;;;IAEAA,WAAc,GAAG,UAAU,WAAW,EAAE,UAAU,EAAE;AACpD,EAAE,IAAI,CAAC,WAAW,CAAC,MAAM,IAAI,UAAU,CAAC,MAAM,EAAE,OAAO,UAAU;AACjE,EAAE,IAAI,WAAW,CAAC,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,WAAW;AAClE,EAAE,IAAI,CAAC,WAAW,CAAC,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE;AAC1D;AACA,EAAE,MAAM,KAAK,GAAG,GAAE;AAClB;AACA,EAAE,WAAW,CAAC,OAAO,CAAC,UAAU,IAAI;AACpC,IAAI,UAAU,CAAC,OAAO,CAAC,SAAS,IAAI;AACpC,MAAM,IAAI,UAAU,KAAK,SAAS,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,UAAU,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,EAAC;AAChF,KAAK,EAAC;AACN,GAAG,EAAC;AACJ;AACA,EAAE,OAAO,KAAK;AACd;;ACdA;AACA,MAAMC,SAAO,GAAGC,iBAAkB;AAClC;AACA,MAAM,iBAAiB,GAAG,CAAC,aAAa,EAAE,cAAc,EAAC;AACzD;AACA,SAAS,aAAa,CAAC,EAAE,EAAE,IAAI,EAAE;AACjC,EAAE,OAAO,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,KAAK;AACnC,IAAID,SAAO,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,IAAI,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC,EAAC;AA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AK,CAAC,IAAI,KAAK,QAAQ;AAC3E,iBAAiB,EAAC;AAClB,gBAAgB,IAAI,CAAC,SAAS,EAAE;AAChC;AACA,kBAAkB,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,GAAE;AAC9E,kBAAkB,KAAK,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,KAAI;AACxD,iBAAiB;AACjB,eAAe;AACf;AACA;AACA,cAAc,OAAO,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC;AACvE,aAAa,CAAC;AACd,WAAW;AACX,SAAS;AACT,OAAO;AACP,KAAK;AACL,GAAG;AACH,CAAC;AACD;AACA,QAAQ,CAAC,OAAO,GAAG,KAAI;AACvB;IACA,aAAc,GAAG;;;;;;"} \ No newline at end of file diff --git a/node_modules/vite/dist/node/chunks/dep-0e948eb3.js b/node_modules/vite/dist/node/chunks/dep-0e948eb3.js new file mode 100644 index 0000000..ec1b1a4 --- /dev/null +++ b/node_modules/vite/dist/node/chunks/dep-0e948eb3.js @@ -0,0 +1,29169 @@ +'use strict'; + +var build = require('./dep-1be34a63.js'); +var require$$1 = require('crypto'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; } + +var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); + +var selfsigned = {}; + +/** + * Node.js module for Forge. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ + +var forge$F = { + // default options + options: { + usePureJavaScript: false + } +}; + +/** + * Base-N/Base-X encoding/decoding functions. + * + * Original implementation from base-x: + * https://github.com/cryptocoinjs/base-x + * + * Which is MIT licensed: + * + * The MIT License (MIT) + * + * Copyright base-x contributors (c) 2016 + * + * 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 api = {}; +var baseN$1 = api; + +// baseN alphabet indexes +var _reverseAlphabets = {}; + +/** + * BaseN-encodes a Uint8Array using the given alphabet. + * + * @param input the Uint8Array to encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the baseN-encoded output string. + */ +api.encode = function(input, alphabet, maxline) { + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + if(maxline !== undefined && typeof maxline !== 'number') { + throw new TypeError('"maxline" must be a number.'); + } + + var output = ''; + + if(!(input instanceof Uint8Array)) { + // assume forge byte buffer + output = _encodeWithByteBuffer(input, alphabet); + } else { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for(i = 0; i < input.length; ++i) { + for(var j = 0, carry = input[i]; j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + // deal with leading zeros + for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + } + + if(maxline) { + var regex = new RegExp('.{1,' + maxline + '}', 'g'); + output = output.match(regex).join('\r\n'); + } + + return output; +}; + +/** + * Decodes a baseN-encoded (using the given alphabet) string to a + * Uint8Array. + * + * @param input the baseN-encoded input string. + * + * @return the Uint8Array. + */ +api.decode = function(input, alphabet) { + if(typeof input !== 'string') { + throw new TypeError('"input" must be a string.'); + } + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + + var table = _reverseAlphabets[alphabet]; + if(!table) { + // compute reverse alphabet + table = _reverseAlphabets[alphabet] = []; + for(var i = 0; i < alphabet.length; ++i) { + table[alphabet.charCodeAt(i)] = i; + } + } + + // remove whitespace characters + input = input.replace(/\s/g, ''); + + var base = alphabet.length; + var first = alphabet.charAt(0); + var bytes = [0]; + for(var i = 0; i < input.length; i++) { + var value = table[input.charCodeAt(i)]; + if(value === undefined) { + return; + } + + for(var j = 0, carry = value; j < bytes.length; ++j) { + carry += bytes[j] * base; + bytes[j] = carry & 0xff; + carry >>= 8; + } + + while(carry > 0) { + bytes.push(carry & 0xff); + carry >>= 8; + } + } + + // deal with leading zeros + for(var k = 0; input[k] === first && k < input.length - 1; ++k) { + bytes.push(0); + } + + if(typeof Buffer !== 'undefined') { + return Buffer.from(bytes.reverse()); + } + + return new Uint8Array(bytes.reverse()); +}; + +function _encodeWithByteBuffer(input, alphabet) { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for(i = 0; i < input.length(); ++i) { + for(var j = 0, carry = input.at(i); j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + var output = ''; + + // deal with leading zeros + for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + + return output; +} + +/** + * Utility functions for web applications. + * + * @author Dave Longley + * + * Copyright (c) 2010-2018 Digital Bazaar, Inc. + */ + +var forge$E = forge$F; +var baseN = baseN$1; + +/* Utilities API */ +var util$1 = forge$E.util = forge$E.util || {}; + +// define setImmediate and nextTick +(function() { + // use native nextTick (unless we're in webpack) + // webpack (or better node-libs-browser polyfill) sets process.browser. + // this way we can detect webpack properly + if(typeof process !== 'undefined' && process.nextTick && !process.browser) { + util$1.nextTick = process.nextTick; + if(typeof setImmediate === 'function') { + util$1.setImmediate = setImmediate; + } else { + // polyfill setImmediate with nextTick, older versions of node + // (those w/o setImmediate) won't totally starve IO + util$1.setImmediate = util$1.nextTick; + } + return; + } + + // polyfill nextTick with native setImmediate + if(typeof setImmediate === 'function') { + util$1.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; + util$1.nextTick = function(callback) { + return setImmediate(callback); + }; + return; + } + + /* Note: A polyfill upgrade pattern is used here to allow combining + polyfills. For example, MutationObserver is fast, but blocks UI updates, + so it needs to allow UI updates periodically, so it falls back on + postMessage or setTimeout. */ + + // polyfill with setTimeout + util$1.setImmediate = function(callback) { + setTimeout(callback, 0); + }; + + // upgrade polyfill to use postMessage + if(typeof window !== 'undefined' && + typeof window.postMessage === 'function') { + var msg = 'forge.setImmediate'; + var callbacks = []; + util$1.setImmediate = function(callback) { + callbacks.push(callback); + // only send message when one hasn't been sent in + // the current turn of the event loop + if(callbacks.length === 1) { + window.postMessage(msg, '*'); + } + }; + function handler(event) { + if(event.source === window && event.data === msg) { + event.stopPropagation(); + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + } + } + window.addEventListener('message', handler, true); + } + + // upgrade polyfill to use MutationObserver + if(typeof MutationObserver !== 'undefined') { + // polyfill with MutationObserver + var now = Date.now(); + var attr = true; + var div = document.createElement('div'); + var callbacks = []; + new MutationObserver(function() { + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + }).observe(div, {attributes: true}); + var oldSetImmediate = util$1.setImmediate; + util$1.setImmediate = function(callback) { + if(Date.now() - now > 15) { + now = Date.now(); + oldSetImmediate(callback); + } else { + callbacks.push(callback); + // only trigger observer when it hasn't been triggered in + // the current turn of the event loop + if(callbacks.length === 1) { + div.setAttribute('a', attr = !attr); + } + } + }; + } + + util$1.nextTick = util$1.setImmediate; +})(); + +// check if running under Node.js +util$1.isNodejs = + typeof process !== 'undefined' && process.versions && process.versions.node; + + +// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while +// it will point to `window` in the main thread. +// To remain compatible with older browsers, we fall back to 'window' if 'self' +// is not available. +util$1.globalScope = (function() { + if(util$1.isNodejs) { + return build.commonjsGlobal; + } + + return typeof self === 'undefined' ? window : self; +})(); + +// define isArray +util$1.isArray = Array.isArray || function(x) { + return Object.prototype.toString.call(x) === '[object Array]'; +}; + +// define isArrayBuffer +util$1.isArrayBuffer = function(x) { + return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; +}; + +// define isArrayBufferView +util$1.isArrayBufferView = function(x) { + return x && util$1.isArrayBuffer(x.buffer) && x.byteLength !== undefined; +}; + +/** + * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for + * algorithms where bit manipulation, JavaScript limitations, and/or algorithm + * design only allow for byte operations of a limited size. + * + * @param n number of bits. + * + * Throw Error if n invalid. + */ +function _checkBitsParam(n) { + if(!(n === 8 || n === 16 || n === 24 || n === 32)) { + throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); + } +} + +// TODO: set ByteBuffer to best available backing +util$1.ByteBuffer = ByteStringBuffer; + +/** Buffer w/BinaryString backing */ + +/** + * Constructor for a binary string backed byte buffer. + * + * @param [b] the bytes to wrap (either encoded as string, one byte per + * character, or as an ArrayBuffer or Typed Array). + */ +function ByteStringBuffer(b) { + // TODO: update to match DataBuffer API + + // the data in this buffer + this.data = ''; + // the pointer for reading from this buffer + this.read = 0; + + if(typeof b === 'string') { + this.data = b; + } else if(util$1.isArrayBuffer(b) || util$1.isArrayBufferView(b)) { + if(typeof Buffer !== 'undefined' && b instanceof Buffer) { + this.data = b.toString('binary'); + } else { + // convert native buffer to forge buffer + // FIXME: support native buffers internally instead + var arr = new Uint8Array(b); + try { + this.data = String.fromCharCode.apply(null, arr); + } catch(e) { + for(var i = 0; i < arr.length; ++i) { + this.putByte(arr[i]); + } + } + } + } else if(b instanceof ByteStringBuffer || + (typeof b === 'object' && typeof b.data === 'string' && + typeof b.read === 'number')) { + // copy existing buffer + this.data = b.data; + this.read = b.read; + } + + // used for v8 optimization + this._constructedStringLength = 0; +} +util$1.ByteStringBuffer = ByteStringBuffer; + +/* Note: This is an optimization for V8-based browsers. When V8 concatenates + a string, the strings are only joined logically using a "cons string" or + "constructed/concatenated string". These containers keep references to one + another and can result in very large memory usage. For example, if a 2MB + string is constructed by concatenating 4 bytes together at a time, the + memory usage will be ~44MB; so ~22x increase. The strings are only joined + together when an operation requiring their joining takes place, such as + substr(). This function is called when adding data to this buffer to ensure + these types of strings are periodically joined to reduce the memory + footprint. */ +var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; +util$1.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { + this._constructedStringLength += x; + if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { + // this substr() should cause the constructed string to join + this.data.substr(0, 1); + this._constructedStringLength = 0; + } +}; + +/** + * Gets the number of bytes in this buffer. + * + * @return the number of bytes in this buffer. + */ +util$1.ByteStringBuffer.prototype.length = function() { + return this.data.length - this.read; +}; + +/** + * Gets whether or not this buffer is empty. + * + * @return true if this buffer is empty, false if not. + */ +util$1.ByteStringBuffer.prototype.isEmpty = function() { + return this.length() <= 0; +}; + +/** + * Puts a byte in this buffer. + * + * @param b the byte to put. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putByte = function(b) { + return this.putBytes(String.fromCharCode(b)); +}; + +/** + * Puts a byte in this buffer N times. + * + * @param b the byte to put. + * @param n the number of bytes of value b to put. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.fillWithByte = function(b, n) { + b = String.fromCharCode(b); + var d = this.data; + while(n > 0) { + if(n & 1) { + d += b; + } + n >>>= 1; + if(n > 0) { + b += b; + } + } + this.data = d; + this._optimizeConstructedString(n); + return this; +}; + +/** + * Puts bytes in this buffer. + * + * @param bytes the bytes (as a binary encoded string) to put. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putBytes = function(bytes) { + this.data += bytes; + this._optimizeConstructedString(bytes.length); + return this; +}; + +/** + * Puts a UTF-16 encoded string into this buffer. + * + * @param str the string to put. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putString = function(str) { + return this.putBytes(util$1.encodeUtf8(str)); +}; + +/** + * Puts a 16-bit integer in this buffer in big-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putInt16 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 24-bit integer in this buffer in big-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putInt24 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 32-bit integer in this buffer in big-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putInt32 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 24 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 16-bit integer in this buffer in little-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putInt16Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF)); +}; + +/** + * Puts a 24-bit integer in this buffer in little-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putInt24Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF)); +}; + +/** + * Puts a 32-bit integer in this buffer in little-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putInt32Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 24 & 0xFF)); +}; + +/** + * Puts an n-bit integer in this buffer in big-endian order. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + var bytes = ''; + do { + n -= 8; + bytes += String.fromCharCode((i >> n) & 0xFF); + } while(n > 0); + return this.putBytes(bytes); +}; + +/** + * Puts a signed n-bit integer in this buffer in big-endian order. Two's + * complement representation is used. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putSignedInt = function(i, n) { + // putInt checks n + if(i < 0) { + i += 2 << (n - 1); + } + return this.putInt(i, n); +}; + +/** + * Puts the given buffer into this buffer. + * + * @param buffer the buffer to put into this one. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.putBuffer = function(buffer) { + return this.putBytes(buffer.getBytes()); +}; + +/** + * Gets a byte from this buffer and advances the read pointer by 1. + * + * @return the byte. + */ +util$1.ByteStringBuffer.prototype.getByte = function() { + return this.data.charCodeAt(this.read++); +}; + +/** + * Gets a uint16 from this buffer in big-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util$1.ByteStringBuffer.prototype.getInt16 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 8 ^ + this.data.charCodeAt(this.read + 1)); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in big-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util$1.ByteStringBuffer.prototype.getInt24 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 16 ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2)); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in big-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util$1.ByteStringBuffer.prototype.getInt32 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 24 ^ + this.data.charCodeAt(this.read + 1) << 16 ^ + this.data.charCodeAt(this.read + 2) << 8 ^ + this.data.charCodeAt(this.read + 3)); + this.read += 4; + return rval; +}; + +/** + * Gets a uint16 from this buffer in little-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util$1.ByteStringBuffer.prototype.getInt16Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in little-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util$1.ByteStringBuffer.prototype.getInt24Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2) << 16); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in little-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util$1.ByteStringBuffer.prototype.getInt32Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2) << 16 ^ + this.data.charCodeAt(this.read + 3) << 24); + this.read += 4; + return rval; +}; + +/** + * Gets an n-bit integer from this buffer in big-endian order and advances the + * read pointer by ceil(n/8). + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util$1.ByteStringBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. + rval = (rval << 8) + this.data.charCodeAt(this.read++); + n -= 8; + } while(n > 0); + return rval; +}; + +/** + * Gets a signed n-bit integer from this buffer in big-endian order, using + * two's complement, and advances the read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util$1.ByteStringBuffer.prototype.getSignedInt = function(n) { + // getInt checks n + var x = this.getInt(n); + var max = 2 << (n - 2); + if(x >= max) { + x -= max << 1; + } + return x; +}; + +/** + * Reads bytes out as a binary encoded string and clears them from the + * buffer. Note that the resulting string is binary encoded (in node.js this + * encoding is referred to as `binary`, it is *not* `utf8`). + * + * @param count the number of bytes to read, undefined or null for all. + * + * @return a binary encoded string of bytes. + */ +util$1.ByteStringBuffer.prototype.getBytes = function(count) { + var rval; + if(count) { + // read count bytes + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if(count === 0) { + rval = ''; + } else { + // read all bytes, optimize to only copy when needed + rval = (this.read === 0) ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; +}; + +/** + * Gets a binary encoded string of the bytes from this buffer without + * modifying the read pointer. + * + * @param count the number of bytes to get, omit to get all. + * + * @return a string full of binary encoded characters. + */ +util$1.ByteStringBuffer.prototype.bytes = function(count) { + return (typeof(count) === 'undefined' ? + this.data.slice(this.read) : + this.data.slice(this.read, this.read + count)); +}; + +/** + * Gets a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * + * @return the byte. + */ +util$1.ByteStringBuffer.prototype.at = function(i) { + return this.data.charCodeAt(this.read + i); +}; + +/** + * Puts a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * @param b the byte to put. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.setAt = function(i, b) { + this.data = this.data.substr(0, this.read + i) + + String.fromCharCode(b) + + this.data.substr(this.read + i + 1); + return this; +}; + +/** + * Gets the last byte without modifying the read pointer. + * + * @return the last byte. + */ +util$1.ByteStringBuffer.prototype.last = function() { + return this.data.charCodeAt(this.data.length - 1); +}; + +/** + * Creates a copy of this buffer. + * + * @return the copy. + */ +util$1.ByteStringBuffer.prototype.copy = function() { + var c = util$1.createBuffer(this.data); + c.read = this.read; + return c; +}; + +/** + * Compacts this buffer. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.compact = function() { + if(this.read > 0) { + this.data = this.data.slice(this.read); + this.read = 0; + } + return this; +}; + +/** + * Clears this buffer. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.clear = function() { + this.data = ''; + this.read = 0; + return this; +}; + +/** + * Shortens this buffer by triming bytes off of the end of this buffer. + * + * @param count the number of bytes to trim off. + * + * @return this buffer. + */ +util$1.ByteStringBuffer.prototype.truncate = function(count) { + var len = Math.max(0, this.length() - count); + this.data = this.data.substr(this.read, len); + this.read = 0; + return this; +}; + +/** + * Converts this buffer to a hexadecimal string. + * + * @return a hexadecimal string. + */ +util$1.ByteStringBuffer.prototype.toHex = function() { + var rval = ''; + for(var i = this.read; i < this.data.length; ++i) { + var b = this.data.charCodeAt(i); + if(b < 16) { + rval += '0'; + } + rval += b.toString(16); + } + return rval; +}; + +/** + * Converts this buffer to a UTF-16 string (standard JavaScript string). + * + * @return a UTF-16 string. + */ +util$1.ByteStringBuffer.prototype.toString = function() { + return util$1.decodeUtf8(this.bytes()); +}; + +/** End Buffer w/BinaryString backing */ + +/** Buffer w/UInt8Array backing */ + +/** + * FIXME: Experimental. Do not use yet. + * + * Constructor for an ArrayBuffer-backed byte buffer. + * + * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a + * TypedArray. + * + * If a string is given, its encoding should be provided as an option, + * otherwise it will default to 'binary'. A 'binary' string is encoded such + * that each character is one byte in length and size. + * + * If an ArrayBuffer, DataView, or TypedArray is given, it will be used + * *directly* without any copying. Note that, if a write to the buffer requires + * more space, the buffer will allocate a new backing ArrayBuffer to + * accommodate. The starting read and write offsets for the buffer may be + * given as options. + * + * @param [b] the initial bytes for this buffer. + * @param options the options to use: + * [readOffset] the starting read offset to use (default: 0). + * [writeOffset] the starting write offset to use (default: the + * length of the first parameter). + * [growSize] the minimum amount, in bytes, to grow the buffer by to + * accommodate writes (default: 1024). + * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the + * first parameter, if it is a string (default: 'binary'). + */ +function DataBuffer(b, options) { + // default options + options = options || {}; + + // pointers for read from/write to buffer + this.read = options.readOffset || 0; + this.growSize = options.growSize || 1024; + + var isArrayBuffer = util$1.isArrayBuffer(b); + var isArrayBufferView = util$1.isArrayBufferView(b); + if(isArrayBuffer || isArrayBufferView) { + // use ArrayBuffer directly + if(isArrayBuffer) { + this.data = new DataView(b); + } else { + // TODO: adjust read/write offset based on the type of view + // or specify that this must be done in the options ... that the + // offsets are byte-based + this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); + } + this.write = ('writeOffset' in options ? + options.writeOffset : this.data.byteLength); + return; + } + + // initialize to empty array buffer and add any given bytes using putBytes + this.data = new DataView(new ArrayBuffer(0)); + this.write = 0; + + if(b !== null && b !== undefined) { + this.putBytes(b); + } + + if('writeOffset' in options) { + this.write = options.writeOffset; + } +} +util$1.DataBuffer = DataBuffer; + +/** + * Gets the number of bytes in this buffer. + * + * @return the number of bytes in this buffer. + */ +util$1.DataBuffer.prototype.length = function() { + return this.write - this.read; +}; + +/** + * Gets whether or not this buffer is empty. + * + * @return true if this buffer is empty, false if not. + */ +util$1.DataBuffer.prototype.isEmpty = function() { + return this.length() <= 0; +}; + +/** + * Ensures this buffer has enough empty space to accommodate the given number + * of bytes. An optional parameter may be given that indicates a minimum + * amount to grow the buffer if necessary. If the parameter is not given, + * the buffer will be grown by some previously-specified default amount + * or heuristic. + * + * @param amount the number of bytes to accommodate. + * @param [growSize] the minimum amount, in bytes, to grow the buffer by if + * necessary. + */ +util$1.DataBuffer.prototype.accommodate = function(amount, growSize) { + if(this.length() >= amount) { + return this; + } + growSize = Math.max(growSize || this.growSize, amount); + + // grow buffer + var src = new Uint8Array( + this.data.buffer, this.data.byteOffset, this.data.byteLength); + var dst = new Uint8Array(this.length() + growSize); + dst.set(src); + this.data = new DataView(dst.buffer); + + return this; +}; + +/** + * Puts a byte in this buffer. + * + * @param b the byte to put. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putByte = function(b) { + this.accommodate(1); + this.data.setUint8(this.write++, b); + return this; +}; + +/** + * Puts a byte in this buffer N times. + * + * @param b the byte to put. + * @param n the number of bytes of value b to put. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.fillWithByte = function(b, n) { + this.accommodate(n); + for(var i = 0; i < n; ++i) { + this.data.setUint8(b); + } + return this; +}; + +/** + * Puts bytes in this buffer. The bytes may be given as a string, an + * ArrayBuffer, a DataView, or a TypedArray. + * + * @param bytes the bytes to put. + * @param [encoding] the encoding for the first parameter ('binary', 'utf8', + * 'utf16', 'hex'), if it is a string (default: 'binary'). + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putBytes = function(bytes, encoding) { + if(util$1.isArrayBufferView(bytes)) { + var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var len = src.byteLength - src.byteOffset; + this.accommodate(len); + var dst = new Uint8Array(this.data.buffer, this.write); + dst.set(src); + this.write += len; + return this; + } + + if(util$1.isArrayBuffer(bytes)) { + var src = new Uint8Array(bytes); + this.accommodate(src.byteLength); + var dst = new Uint8Array(this.data.buffer); + dst.set(src, this.write); + this.write += src.byteLength; + return this; + } + + // bytes is a util.DataBuffer or equivalent + if(bytes instanceof util$1.DataBuffer || + (typeof bytes === 'object' && + typeof bytes.read === 'number' && typeof bytes.write === 'number' && + util$1.isArrayBufferView(bytes.data))) { + var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); + this.accommodate(src.byteLength); + var dst = new Uint8Array(bytes.data.byteLength, this.write); + dst.set(src); + this.write += src.byteLength; + return this; + } + + if(bytes instanceof util$1.ByteStringBuffer) { + // copy binary string and process as the same as a string parameter below + bytes = bytes.data; + encoding = 'binary'; + } + + // string conversion + encoding = encoding || 'binary'; + if(typeof bytes === 'string') { + var view; + + // decode from string + if(encoding === 'hex') { + this.accommodate(Math.ceil(bytes.length / 2)); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util$1.binary.hex.decode(bytes, view, this.write); + return this; + } + if(encoding === 'base64') { + this.accommodate(Math.ceil(bytes.length / 4) * 3); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util$1.binary.base64.decode(bytes, view, this.write); + return this; + } + + // encode text as UTF-8 bytes + if(encoding === 'utf8') { + // encode as UTF-8 then decode string as raw binary + bytes = util$1.encodeUtf8(bytes); + encoding = 'binary'; + } + + // decode string as raw binary + if(encoding === 'binary' || encoding === 'raw') { + // one byte per character + this.accommodate(bytes.length); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util$1.binary.raw.decode(view); + return this; + } + + // encode text as UTF-16 bytes + if(encoding === 'utf16') { + // two bytes per character + this.accommodate(bytes.length * 2); + view = new Uint16Array(this.data.buffer, this.write); + this.write += util$1.text.utf16.encode(view); + return this; + } + + throw new Error('Invalid encoding: ' + encoding); + } + + throw Error('Invalid parameter: ' + bytes); +}; + +/** + * Puts the given buffer into this buffer. + * + * @param buffer the buffer to put into this one. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putBuffer = function(buffer) { + this.putBytes(buffer); + buffer.clear(); + return this; +}; + +/** + * Puts a string into this buffer. + * + * @param str the string to put. + * @param [encoding] the encoding for the string (default: 'utf16'). + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putString = function(str) { + return this.putBytes(str, 'utf16'); +}; + +/** + * Puts a 16-bit integer in this buffer in big-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putInt16 = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i); + this.write += 2; + return this; +}; + +/** + * Puts a 24-bit integer in this buffer in big-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putInt24 = function(i) { + this.accommodate(3); + this.data.setInt16(this.write, i >> 8 & 0xFFFF); + this.data.setInt8(this.write, i >> 16 & 0xFF); + this.write += 3; + return this; +}; + +/** + * Puts a 32-bit integer in this buffer in big-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putInt32 = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i); + this.write += 4; + return this; +}; + +/** + * Puts a 16-bit integer in this buffer in little-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putInt16Le = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i, true); + this.write += 2; + return this; +}; + +/** + * Puts a 24-bit integer in this buffer in little-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putInt24Le = function(i) { + this.accommodate(3); + this.data.setInt8(this.write, i >> 16 & 0xFF); + this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); + this.write += 3; + return this; +}; + +/** + * Puts a 32-bit integer in this buffer in little-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putInt32Le = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i, true); + this.write += 4; + return this; +}; + +/** + * Puts an n-bit integer in this buffer in big-endian order. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + do { + n -= 8; + this.data.setInt8(this.write++, (i >> n) & 0xFF); + } while(n > 0); + return this; +}; + +/** + * Puts a signed n-bit integer in this buffer in big-endian order. Two's + * complement representation is used. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.putSignedInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + if(i < 0) { + i += 2 << (n - 1); + } + return this.putInt(i, n); +}; + +/** + * Gets a byte from this buffer and advances the read pointer by 1. + * + * @return the byte. + */ +util$1.DataBuffer.prototype.getByte = function() { + return this.data.getInt8(this.read++); +}; + +/** + * Gets a uint16 from this buffer in big-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util$1.DataBuffer.prototype.getInt16 = function() { + var rval = this.data.getInt16(this.read); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in big-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util$1.DataBuffer.prototype.getInt24 = function() { + var rval = ( + this.data.getInt16(this.read) << 8 ^ + this.data.getInt8(this.read + 2)); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in big-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util$1.DataBuffer.prototype.getInt32 = function() { + var rval = this.data.getInt32(this.read); + this.read += 4; + return rval; +}; + +/** + * Gets a uint16 from this buffer in little-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util$1.DataBuffer.prototype.getInt16Le = function() { + var rval = this.data.getInt16(this.read, true); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in little-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util$1.DataBuffer.prototype.getInt24Le = function() { + var rval = ( + this.data.getInt8(this.read) ^ + this.data.getInt16(this.read + 1, true) << 8); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in little-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util$1.DataBuffer.prototype.getInt32Le = function() { + var rval = this.data.getInt32(this.read, true); + this.read += 4; + return rval; +}; + +/** + * Gets an n-bit integer from this buffer in big-endian order and advances the + * read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util$1.DataBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. + rval = (rval << 8) + this.data.getInt8(this.read++); + n -= 8; + } while(n > 0); + return rval; +}; + +/** + * Gets a signed n-bit integer from this buffer in big-endian order, using + * two's complement, and advances the read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util$1.DataBuffer.prototype.getSignedInt = function(n) { + // getInt checks n + var x = this.getInt(n); + var max = 2 << (n - 2); + if(x >= max) { + x -= max << 1; + } + return x; +}; + +/** + * Reads bytes out as a binary encoded string and clears them from the + * buffer. + * + * @param count the number of bytes to read, undefined or null for all. + * + * @return a binary encoded string of bytes. + */ +util$1.DataBuffer.prototype.getBytes = function(count) { + // TODO: deprecate this method, it is poorly named and + // this.toString('binary') replaces it + // add a toTypedArray()/toArrayBuffer() function + var rval; + if(count) { + // read count bytes + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if(count === 0) { + rval = ''; + } else { + // read all bytes, optimize to only copy when needed + rval = (this.read === 0) ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; +}; + +/** + * Gets a binary encoded string of the bytes from this buffer without + * modifying the read pointer. + * + * @param count the number of bytes to get, omit to get all. + * + * @return a string full of binary encoded characters. + */ +util$1.DataBuffer.prototype.bytes = function(count) { + // TODO: deprecate this method, it is poorly named, add "getString()" + return (typeof(count) === 'undefined' ? + this.data.slice(this.read) : + this.data.slice(this.read, this.read + count)); +}; + +/** + * Gets a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * + * @return the byte. + */ +util$1.DataBuffer.prototype.at = function(i) { + return this.data.getUint8(this.read + i); +}; + +/** + * Puts a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * @param b the byte to put. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.setAt = function(i, b) { + this.data.setUint8(i, b); + return this; +}; + +/** + * Gets the last byte without modifying the read pointer. + * + * @return the last byte. + */ +util$1.DataBuffer.prototype.last = function() { + return this.data.getUint8(this.write - 1); +}; + +/** + * Creates a copy of this buffer. + * + * @return the copy. + */ +util$1.DataBuffer.prototype.copy = function() { + return new util$1.DataBuffer(this); +}; + +/** + * Compacts this buffer. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.compact = function() { + if(this.read > 0) { + var src = new Uint8Array(this.data.buffer, this.read); + var dst = new Uint8Array(src.byteLength); + dst.set(src); + this.data = new DataView(dst); + this.write -= this.read; + this.read = 0; + } + return this; +}; + +/** + * Clears this buffer. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.clear = function() { + this.data = new DataView(new ArrayBuffer(0)); + this.read = this.write = 0; + return this; +}; + +/** + * Shortens this buffer by triming bytes off of the end of this buffer. + * + * @param count the number of bytes to trim off. + * + * @return this buffer. + */ +util$1.DataBuffer.prototype.truncate = function(count) { + this.write = Math.max(0, this.length() - count); + this.read = Math.min(this.read, this.write); + return this; +}; + +/** + * Converts this buffer to a hexadecimal string. + * + * @return a hexadecimal string. + */ +util$1.DataBuffer.prototype.toHex = function() { + var rval = ''; + for(var i = this.read; i < this.data.byteLength; ++i) { + var b = this.data.getUint8(i); + if(b < 16) { + rval += '0'; + } + rval += b.toString(16); + } + return rval; +}; + +/** + * Converts this buffer to a string, using the given encoding. If no + * encoding is given, 'utf8' (UTF-8) is used. + * + * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex', + * 'base64' (default: 'utf8'). + * + * @return a string representation of the bytes in this buffer. + */ +util$1.DataBuffer.prototype.toString = function(encoding) { + var view = new Uint8Array(this.data, this.read, this.length()); + encoding = encoding || 'utf8'; + + // encode to string + if(encoding === 'binary' || encoding === 'raw') { + return util$1.binary.raw.encode(view); + } + if(encoding === 'hex') { + return util$1.binary.hex.encode(view); + } + if(encoding === 'base64') { + return util$1.binary.base64.encode(view); + } + + // decode to text + if(encoding === 'utf8') { + return util$1.text.utf8.decode(view); + } + if(encoding === 'utf16') { + return util$1.text.utf16.decode(view); + } + + throw new Error('Invalid encoding: ' + encoding); +}; + +/** End Buffer w/UInt8Array backing */ + +/** + * Creates a buffer that stores bytes. A value may be given to populate the + * buffer with data. This value can either be string of encoded bytes or a + * regular string of characters. When passing a string of binary encoded + * bytes, the encoding `raw` should be given. This is also the default. When + * passing a string of characters, the encoding `utf8` should be given. + * + * @param [input] a string with encoded bytes to store in the buffer. + * @param [encoding] (default: 'raw', other: 'utf8'). + */ +util$1.createBuffer = function(input, encoding) { + // TODO: deprecate, use new ByteBuffer() instead + encoding = encoding || 'raw'; + if(input !== undefined && encoding === 'utf8') { + input = util$1.encodeUtf8(input); + } + return new util$1.ByteBuffer(input); +}; + +/** + * Fills a string with a particular value. If you want the string to be a byte + * string, pass in String.fromCharCode(theByte). + * + * @param c the character to fill the string with, use String.fromCharCode + * to fill the string with a byte value. + * @param n the number of characters of value c to fill with. + * + * @return the filled string. + */ +util$1.fillString = function(c, n) { + var s = ''; + while(n > 0) { + if(n & 1) { + s += c; + } + n >>>= 1; + if(n > 0) { + c += c; + } + } + return s; +}; + +/** + * Performs a per byte XOR between two byte strings and returns the result as a + * string of bytes. + * + * @param s1 first string of bytes. + * @param s2 second string of bytes. + * @param n the number of bytes to XOR. + * + * @return the XOR'd result. + */ +util$1.xorBytes = function(s1, s2, n) { + var s3 = ''; + var b = ''; + var t = ''; + var i = 0; + var c = 0; + for(; n > 0; --n, ++i) { + b = s1.charCodeAt(i) ^ s2.charCodeAt(i); + if(c >= 10) { + s3 += t; + t = ''; + c = 0; + } + t += String.fromCharCode(b); + ++c; + } + s3 += t; + return s3; +}; + +/** + * Converts a hex string into a 'binary' encoded string of bytes. + * + * @param hex the hexadecimal string to convert. + * + * @return the binary-encoded string of bytes. + */ +util$1.hexToBytes = function(hex) { + // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead." + var rval = ''; + var i = 0; + if(hex.length & 1 == 1) { + // odd number of characters, convert first character alone + i = 1; + rval += String.fromCharCode(parseInt(hex[0], 16)); + } + // convert 2 characters (1 byte) at a time + for(; i < hex.length; i += 2) { + rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + } + return rval; +}; + +/** + * Converts a 'binary' encoded string of bytes to hex. + * + * @param bytes the byte string to convert. + * + * @return the string of hexadecimal characters. + */ +util$1.bytesToHex = function(bytes) { + // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead." + return util$1.createBuffer(bytes).toHex(); +}; + +/** + * Converts an 32-bit integer to 4-big-endian byte string. + * + * @param i the integer. + * + * @return the byte string. + */ +util$1.int32ToBytes = function(i) { + return ( + String.fromCharCode(i >> 24 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +// base64 characters, reverse mapping +var _base64 = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +var _base64Idx = [ +/*43 -43 = 0*/ +/*'+', 1, 2, 3,'/' */ + 62, -1, -1, -1, 63, + +/*'0','1','2','3','4','5','6','7','8','9' */ + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, + +/*15, 16, 17,'=', 19, 20, 21 */ + -1, -1, -1, 64, -1, -1, -1, + +/*65 - 43 = 22*/ +/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + +/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + +/*91 - 43 = 48 */ +/*48, 49, 50, 51, 52, 53 */ + -1, -1, -1, -1, -1, -1, + +/*97 - 43 = 54*/ +/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + +/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 +]; + +// base58 characters (Bitcoin alphabet) +var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +/** + * Base64 encodes a 'binary' encoded string of bytes. + * + * @param input the binary encoded string of bytes to base64-encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the base64-encoded output. + */ +util$1.encode64 = function(input, maxline) { + // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead." + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while(i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + // encode 4 character group + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + } + + if(maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); + } + } + output += line; + return output; +}; + +/** + * Base64 decodes a string into a 'binary' encoded string of bytes. + * + * @param input the base64-encoded input. + * + * @return the binary encoded string. + */ +util$1.decode64 = function(input) { + // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead." + + // remove all non-base64 characters + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + + var output = ''; + var enc1, enc2, enc3, enc4; + var i = 0; + + while(i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + + output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); + if(enc3 !== 64) { + // decoded at least 2 bytes + output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); + if(enc4 !== 64) { + // decoded 3 bytes + output += String.fromCharCode(((enc3 & 3) << 6) | enc4); + } + } + } + + return output; +}; + +/** + * Encodes the given string of characters (a standard JavaScript + * string) as a binary encoded string where the bytes represent + * a UTF-8 encoded string of characters. Non-ASCII characters will be + * encoded as multiple bytes according to UTF-8. + * + * @param str a standard string of characters to encode. + * + * @return the binary encoded string. + */ +util$1.encodeUtf8 = function(str) { + return unescape(encodeURIComponent(str)); +}; + +/** + * Decodes a binary encoded string that contains bytes that + * represent a UTF-8 encoded string of characters -- into a + * string of characters (a standard JavaScript string). + * + * @param str the binary encoded string to decode. + * + * @return the resulting standard string of characters. + */ +util$1.decodeUtf8 = function(str) { + return decodeURIComponent(escape(str)); +}; + +// binary encoding/decoding tools +// FIXME: Experimental. Do not use yet. +util$1.binary = { + raw: {}, + hex: {}, + base64: {}, + base58: {}, + baseN : { + encode: baseN.encode, + decode: baseN.decode + } +}; + +/** + * Encodes a Uint8Array as a binary-encoded string. This encoding uses + * a value between 0 and 255 for each character. + * + * @param bytes the Uint8Array to encode. + * + * @return the binary-encoded string. + */ +util$1.binary.raw.encode = function(bytes) { + return String.fromCharCode.apply(null, bytes); +}; + +/** + * Decodes a binary-encoded string to a Uint8Array. This encoding uses + * a value between 0 and 255 for each character. + * + * @param str the binary-encoded string to decode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util$1.binary.raw.decode = function(str, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for(var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? (j - offset) : out; +}; + +/** + * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or + * ByteBuffer as a string of hexadecimal characters. + * + * @param bytes the bytes to convert. + * + * @return the string of hexadecimal characters. + */ +util$1.binary.hex.encode = util$1.bytesToHex; + +/** + * Decodes a hex-encoded string to a Uint8Array. + * + * @param hex the hexadecimal string to convert. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util$1.binary.hex.decode = function(hex, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(Math.ceil(hex.length / 2)); + } + offset = offset || 0; + var i = 0, j = offset; + if(hex.length & 1) { + // odd number of characters, convert first character alone + i = 1; + out[j++] = parseInt(hex[0], 16); + } + // convert 2 characters (1 byte) at a time + for(; i < hex.length; i += 2) { + out[j++] = parseInt(hex.substr(i, 2), 16); + } + return output ? (j - offset) : out; +}; + +/** + * Base64-encodes a Uint8Array. + * + * @param input the Uint8Array to encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the base64-encoded output string. + */ +util$1.binary.base64.encode = function(input, maxline) { + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while(i < input.byteLength) { + chr1 = input[i++]; + chr2 = input[i++]; + chr3 = input[i++]; + + // encode 4 character group + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + } + + if(maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); + } + } + output += line; + return output; +}; + +/** + * Decodes a base64-encoded string to a Uint8Array. + * + * @param input the base64-encoded input string. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util$1.binary.base64.decode = function(input, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(Math.ceil(input.length / 4) * 3); + } + + // remove all non-base64 characters + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + + offset = offset || 0; + var enc1, enc2, enc3, enc4; + var i = 0, j = offset; + + while(i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + + out[j++] = (enc1 << 2) | (enc2 >> 4); + if(enc3 !== 64) { + // decoded at least 2 bytes + out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); + if(enc4 !== 64) { + // decoded 3 bytes + out[j++] = ((enc3 & 3) << 6) | enc4; + } + } + } + + // make sure result is the exact decoded length + return output ? (j - offset) : out.subarray(0, j); +}; + +// add support for base58 encoding/decoding with Bitcoin alphabet +util$1.binary.base58.encode = function(input, maxline) { + return util$1.binary.baseN.encode(input, _base58, maxline); +}; +util$1.binary.base58.decode = function(input, maxline) { + return util$1.binary.baseN.decode(input, _base58, maxline); +}; + +// text encoding/decoding tools +// FIXME: Experimental. Do not use yet. +util$1.text = { + utf8: {}, + utf16: {} +}; + +/** + * Encodes the given string as UTF-8 in a Uint8Array. + * + * @param str the string to encode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util$1.text.utf8.encode = function(str, output, offset) { + str = util$1.encodeUtf8(str); + var out = output; + if(!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for(var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? (j - offset) : out; +}; + +/** + * Decodes the UTF-8 contents from a Uint8Array. + * + * @param bytes the Uint8Array to decode. + * + * @return the resulting string. + */ +util$1.text.utf8.decode = function(bytes) { + return util$1.decodeUtf8(String.fromCharCode.apply(null, bytes)); +}; + +/** + * Encodes the given string as UTF-16 in a Uint8Array. + * + * @param str the string to encode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util$1.text.utf16.encode = function(str, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(str.length * 2); + } + var view = new Uint16Array(out.buffer); + offset = offset || 0; + var j = offset; + var k = offset; + for(var i = 0; i < str.length; ++i) { + view[k++] = str.charCodeAt(i); + j += 2; + } + return output ? (j - offset) : out; +}; + +/** + * Decodes the UTF-16 contents from a Uint8Array. + * + * @param bytes the Uint8Array to decode. + * + * @return the resulting string. + */ +util$1.text.utf16.decode = function(bytes) { + return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); +}; + +/** + * Deflates the given data using a flash interface. + * + * @param api the flash interface. + * @param bytes the data. + * @param raw true to return only raw deflate data, false to include zlib + * header and trailer. + * + * @return the deflated data as a string. + */ +util$1.deflate = function(api, bytes, raw) { + bytes = util$1.decode64(api.deflate(util$1.encode64(bytes)).rval); + + // strip zlib header and trailer if necessary + if(raw) { + // zlib header is 2 bytes (CMF,FLG) where FLG indicates that + // there is a 4-byte DICT (alder-32) block before the data if + // its 5th bit is set + var start = 2; + var flg = bytes.charCodeAt(1); + if(flg & 0x20) { + start = 6; + } + // zlib trailer is 4 bytes of adler-32 + bytes = bytes.substring(start, bytes.length - 4); + } + + return bytes; +}; + +/** + * Inflates the given data using a flash interface. + * + * @param api the flash interface. + * @param bytes the data. + * @param raw true if the incoming data has no zlib header or trailer and is + * raw DEFLATE data. + * + * @return the inflated data as a string, null on error. + */ +util$1.inflate = function(api, bytes, raw) { + // TODO: add zlib header and trailer if necessary/possible + var rval = api.inflate(util$1.encode64(bytes)).rval; + return (rval === null) ? null : util$1.decode64(rval); +}; + +/** + * Sets a storage object. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param obj the storage object, null to remove. + */ +var _setStorageObject = function(api, id, obj) { + if(!api) { + throw new Error('WebStorage not available.'); + } + + var rval; + if(obj === null) { + rval = api.removeItem(id); + } else { + // json-encode and base64-encode object + obj = util$1.encode64(JSON.stringify(obj)); + rval = api.setItem(id, obj); + } + + // handle potential flash error + if(typeof(rval) !== 'undefined' && rval.rval !== true) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } +}; + +/** + * Gets a storage object. + * + * @param api the storage interface. + * @param id the storage ID to use. + * + * @return the storage object entry or null if none exists. + */ +var _getStorageObject = function(api, id) { + if(!api) { + throw new Error('WebStorage not available.'); + } + + // get the existing entry + var rval = api.getItem(id); + + /* Note: We check api.init because we can't do (api == localStorage) + on IE because of "Class doesn't support Automation" exception. Only + the flash api has an init method so this works too, but we need a + better solution in the future. */ + + // flash returns item wrapped in an object, handle special case + if(api.init) { + if(rval.rval === null) { + if(rval.error) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } + // no error, but also no item + rval = null; + } else { + rval = rval.rval; + } + } + + // handle decoding + if(rval !== null) { + // base64-decode and json-decode data + rval = JSON.parse(util$1.decode64(rval)); + } + + return rval; +}; + +/** + * Stores an item in local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + * @param data the data for the item (any javascript object/primitive). + */ +var _setItem = function(api, id, key, data) { + // get storage object + var obj = _getStorageObject(api, id); + if(obj === null) { + // create a new storage object + obj = {}; + } + // update key + obj[key] = data; + + // set storage object + _setStorageObject(api, id, obj); +}; + +/** + * Gets an item from local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + * + * @return the item. + */ +var _getItem = function(api, id, key) { + // get storage object + var rval = _getStorageObject(api, id); + if(rval !== null) { + // return data at key + rval = (key in rval) ? rval[key] : null; + } + + return rval; +}; + +/** + * Removes an item from local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + */ +var _removeItem = function(api, id, key) { + // get storage object + var obj = _getStorageObject(api, id); + if(obj !== null && key in obj) { + // remove key + delete obj[key]; + + // see if entry has no keys remaining + var empty = true; + for(var prop in obj) { + empty = false; + break; + } + if(empty) { + // remove entry entirely if no keys are left + obj = null; + } + + // set storage object + _setStorageObject(api, id, obj); + } +}; + +/** + * Clears the local disk storage identified by the given ID. + * + * @param api the storage interface. + * @param id the storage ID to use. + */ +var _clearItems = function(api, id) { + _setStorageObject(api, id, null); +}; + +/** + * Calls a storage function. + * + * @param func the function to call. + * @param args the arguments for the function. + * @param location the location argument. + * + * @return the return value from the function. + */ +var _callStorageFunction = function(func, args, location) { + var rval = null; + + // default storage types + if(typeof(location) === 'undefined') { + location = ['web', 'flash']; + } + + // apply storage types in order of preference + var type; + var done = false; + var exception = null; + for(var idx in location) { + type = location[idx]; + try { + if(type === 'flash' || type === 'both') { + if(args[0] === null) { + throw new Error('Flash local storage not available.'); + } + rval = func.apply(this, args); + done = (type === 'flash'); + } + if(type === 'web' || type === 'both') { + args[0] = localStorage; + rval = func.apply(this, args); + done = true; + } + } catch(ex) { + exception = ex; + } + if(done) { + break; + } + } + + if(!done) { + throw exception; + } + + return rval; +}; + +/** + * Stores an item on local disk. + * + * The available types of local storage include 'flash', 'web', and 'both'. + * + * The type 'flash' refers to flash local storage (SharedObject). In order + * to use flash local storage, the 'api' parameter must be valid. The type + * 'web' refers to WebStorage, if supported by the browser. The type 'both' + * refers to storing using both 'flash' and 'web', not just one or the + * other. + * + * The location array should list the storage types to use in order of + * preference: + * + * ['flash']: flash only storage + * ['web']: web only storage + * ['both']: try to store in both + * ['flash','web']: store in flash first, but if not available, 'web' + * ['web','flash']: store in web first, but if not available, 'flash' + * + * The location array defaults to: ['web', 'flash'] + * + * @param api the flash interface, null to use only WebStorage. + * @param id the storage ID to use. + * @param key the key for the item. + * @param data the data for the item (any javascript object/primitive). + * @param location an array with the preferred types of storage to use. + */ +util$1.setItem = function(api, id, key, data, location) { + _callStorageFunction(_setItem, arguments, location); +}; + +/** + * Gets an item on local disk. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface, null to use only WebStorage. + * @param id the storage ID to use. + * @param key the key for the item. + * @param location an array with the preferred types of storage to use. + * + * @return the item. + */ +util$1.getItem = function(api, id, key, location) { + return _callStorageFunction(_getItem, arguments, location); +}; + +/** + * Removes an item on local disk. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface. + * @param id the storage ID to use. + * @param key the key for the item. + * @param location an array with the preferred types of storage to use. + */ +util$1.removeItem = function(api, id, key, location) { + _callStorageFunction(_removeItem, arguments, location); +}; + +/** + * Clears the local disk storage identified by the given ID. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface if flash is available. + * @param id the storage ID to use. + * @param location an array with the preferred types of storage to use. + */ +util$1.clearItems = function(api, id, location) { + _callStorageFunction(_clearItems, arguments, location); +}; + +/** + * Parses the scheme, host, and port from an http(s) url. + * + * @param str the url string. + * + * @return the parsed url object or null if the url is invalid. + */ +util$1.parseUrl = function(str) { + // FIXME: this regex looks a bit broken + var regex = /^(https?):\/\/([^:&^\/]*):?(\d*)(.*)$/g; + regex.lastIndex = 0; + var m = regex.exec(str); + var url = (m === null) ? null : { + full: str, + scheme: m[1], + host: m[2], + port: m[3], + path: m[4] + }; + if(url) { + url.fullHost = url.host; + if(url.port) { + if(url.port !== 80 && url.scheme === 'http') { + url.fullHost += ':' + url.port; + } else if(url.port !== 443 && url.scheme === 'https') { + url.fullHost += ':' + url.port; + } + } else if(url.scheme === 'http') { + url.port = 80; + } else if(url.scheme === 'https') { + url.port = 443; + } + url.full = url.scheme + '://' + url.fullHost; + } + return url; +}; + +/* Storage for query variables */ +var _queryVariables = null; + +/** + * Returns the window location query variables. Query is parsed on the first + * call and the same object is returned on subsequent calls. The mapping + * is from keys to an array of values. Parameters without values will have + * an object key set but no value added to the value array. Values are + * unescaped. + * + * ...?k1=v1&k2=v2: + * { + * "k1": ["v1"], + * "k2": ["v2"] + * } + * + * ...?k1=v1&k1=v2: + * { + * "k1": ["v1", "v2"] + * } + * + * ...?k1=v1&k2: + * { + * "k1": ["v1"], + * "k2": [] + * } + * + * ...?k1=v1&k1: + * { + * "k1": ["v1"] + * } + * + * ...?k1&k1: + * { + * "k1": [] + * } + * + * @param query the query string to parse (optional, default to cached + * results from parsing window location search query). + * + * @return object mapping keys to variables. + */ +util$1.getQueryVariables = function(query) { + var parse = function(q) { + var rval = {}; + var kvpairs = q.split('&'); + for(var i = 0; i < kvpairs.length; i++) { + var pos = kvpairs[i].indexOf('='); + var key; + var val; + if(pos > 0) { + key = kvpairs[i].substring(0, pos); + val = kvpairs[i].substring(pos + 1); + } else { + key = kvpairs[i]; + val = null; + } + if(!(key in rval)) { + rval[key] = []; + } + // disallow overriding object prototype keys + if(!(key in Object.prototype) && val !== null) { + rval[key].push(unescape(val)); + } + } + return rval; + }; + + var rval; + if(typeof(query) === 'undefined') { + // set cached variables if needed + if(_queryVariables === null) { + if(typeof(window) !== 'undefined' && window.location && window.location.search) { + // parse window search query + _queryVariables = parse(window.location.search.substring(1)); + } else { + // no query variables available + _queryVariables = {}; + } + } + rval = _queryVariables; + } else { + // parse given query + rval = parse(query); + } + return rval; +}; + +/** + * Parses a fragment into a path and query. This method will take a URI + * fragment and break it up as if it were the main URI. For example: + * /bar/baz?a=1&b=2 + * results in: + * { + * path: ["bar", "baz"], + * query: {"k1": ["v1"], "k2": ["v2"]} + * } + * + * @return object with a path array and query object. + */ +util$1.parseFragment = function(fragment) { + // default to whole fragment + var fp = fragment; + var fq = ''; + // split into path and query if possible at the first '?' + var pos = fragment.indexOf('?'); + if(pos > 0) { + fp = fragment.substring(0, pos); + fq = fragment.substring(pos + 1); + } + // split path based on '/' and ignore first element if empty + var path = fp.split('/'); + if(path.length > 0 && path[0] === '') { + path.shift(); + } + // convert query into object + var query = (fq === '') ? {} : util$1.getQueryVariables(fq); + + return { + pathString: fp, + queryString: fq, + path: path, + query: query + }; +}; + +/** + * Makes a request out of a URI-like request string. This is intended to + * be used where a fragment id (after a URI '#') is parsed as a URI with + * path and query parts. The string should have a path beginning and + * delimited by '/' and optional query parameters following a '?'. The + * query should be a standard URL set of key value pairs delimited by + * '&'. For backwards compatibility the initial '/' on the path is not + * required. The request object has the following API, (fully described + * in the method code): + * { + * path: . + * query: , + * getPath(i): get part or all of the split path array, + * getQuery(k, i): get part or all of a query key array, + * getQueryLast(k, _default): get last element of a query key array. + * } + * + * @return object with request parameters. + */ +util$1.makeRequest = function(reqString) { + var frag = util$1.parseFragment(reqString); + var req = { + // full path string + path: frag.pathString, + // full query string + query: frag.queryString, + /** + * Get path or element in path. + * + * @param i optional path index. + * + * @return path or part of path if i provided. + */ + getPath: function(i) { + return (typeof(i) === 'undefined') ? frag.path : frag.path[i]; + }, + /** + * Get query, values for a key, or value for a key index. + * + * @param k optional query key. + * @param i optional query key index. + * + * @return query, values for a key, or value for a key index. + */ + getQuery: function(k, i) { + var rval; + if(typeof(k) === 'undefined') { + rval = frag.query; + } else { + rval = frag.query[k]; + if(rval && typeof(i) !== 'undefined') { + rval = rval[i]; + } + } + return rval; + }, + getQueryLast: function(k, _default) { + var rval; + var vals = req.getQuery(k); + if(vals) { + rval = vals[vals.length - 1]; + } else { + rval = _default; + } + return rval; + } + }; + return req; +}; + +/** + * Makes a URI out of a path, an object with query parameters, and a + * fragment. Uses jQuery.param() internally for query string creation. + * If the path is an array, it will be joined with '/'. + * + * @param path string path or array of strings. + * @param query object with query parameters. (optional) + * @param fragment fragment string. (optional) + * + * @return string object with request parameters. + */ +util$1.makeLink = function(path, query, fragment) { + // join path parts if needed + path = jQuery.isArray(path) ? path.join('/') : path; + + var qstr = jQuery.param(query || {}); + fragment = fragment || ''; + return path + + ((qstr.length > 0) ? ('?' + qstr) : '') + + ((fragment.length > 0) ? ('#' + fragment) : ''); +}; + +/** + * Check if an object is empty. + * + * Taken from: + * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937 + * + * @param object the object to check. + */ +util$1.isEmpty = function(obj) { + for(var prop in obj) { + if(obj.hasOwnProperty(prop)) { + return false; + } + } + return true; +}; + +/** + * Format with simple printf-style interpolation. + * + * %%: literal '%' + * %s,%o: convert next argument into a string. + * + * @param format the string to format. + * @param ... arguments to interpolate into the format string. + */ +util$1.format = function(format) { + var re = /%./g; + // current match + var match; + // current part + var part; + // current arg index + var argi = 0; + // collected parts to recombine later + var parts = []; + // last index found + var last = 0; + // loop while matches remain + while((match = re.exec(format))) { + part = format.substring(last, re.lastIndex - 2); + // don't add empty strings (ie, parts between %s%s) + if(part.length > 0) { + parts.push(part); + } + last = re.lastIndex; + // switch on % code + var code = match[0][1]; + switch(code) { + case 's': + case 'o': + // check if enough arguments were given + if(argi < arguments.length) { + parts.push(arguments[argi++ + 1]); + } else { + parts.push(''); + } + break; + // FIXME: do proper formating for numbers, etc + //case 'f': + //case 'd': + case '%': + parts.push('%'); + break; + default: + parts.push('<%' + code + '?>'); + } + } + // add trailing part of format string + parts.push(format.substring(last)); + return parts.join(''); +}; + +/** + * Formats a number. + * + * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/ + */ +util$1.formatNumber = function(number, decimals, dec_point, thousands_sep) { + // http://kevin.vanzonneveld.net + // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + bugfix by: Michael White (http://crestidg.com) + // + bugfix by: Benjamin Lupton + // + bugfix by: Allan Jensen (http://www.winternet.no) + // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) + // * example 1: number_format(1234.5678, 2, '.', ''); + // * returns 1: 1234.57 + + var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; + var d = dec_point === undefined ? ',' : dec_point; + var t = thousands_sep === undefined ? + '.' : thousands_sep, s = n < 0 ? '-' : ''; + var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; + var j = (i.length > 3) ? i.length % 3 : 0; + return s + (j ? i.substr(0, j) + t : '') + + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); +}; + +/** + * Formats a byte size. + * + * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/ + */ +util$1.formatSize = function(size) { + if(size >= 1073741824) { + size = util$1.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; + } else if(size >= 1048576) { + size = util$1.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; + } else if(size >= 1024) { + size = util$1.formatNumber(size / 1024, 0) + ' KiB'; + } else { + size = util$1.formatNumber(size, 0) + ' bytes'; + } + return size; +}; + +/** + * Converts an IPv4 or IPv6 string representation into bytes (in network order). + * + * @param ip the IPv4 or IPv6 address to convert. + * + * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't + * be parsed. + */ +util$1.bytesFromIP = function(ip) { + if(ip.indexOf('.') !== -1) { + return util$1.bytesFromIPv4(ip); + } + if(ip.indexOf(':') !== -1) { + return util$1.bytesFromIPv6(ip); + } + return null; +}; + +/** + * Converts an IPv4 string representation into bytes (in network order). + * + * @param ip the IPv4 address to convert. + * + * @return the 4-byte address or null if the address can't be parsed. + */ +util$1.bytesFromIPv4 = function(ip) { + ip = ip.split('.'); + if(ip.length !== 4) { + return null; + } + var b = util$1.createBuffer(); + for(var i = 0; i < ip.length; ++i) { + var num = parseInt(ip[i], 10); + if(isNaN(num)) { + return null; + } + b.putByte(num); + } + return b.getBytes(); +}; + +/** + * Converts an IPv6 string representation into bytes (in network order). + * + * @param ip the IPv6 address to convert. + * + * @return the 16-byte address or null if the address can't be parsed. + */ +util$1.bytesFromIPv6 = function(ip) { + var blanks = 0; + ip = ip.split(':').filter(function(e) { + if(e.length === 0) ++blanks; + return true; + }); + var zeros = (8 - ip.length + blanks) * 2; + var b = util$1.createBuffer(); + for(var i = 0; i < 8; ++i) { + if(!ip[i] || ip[i].length === 0) { + b.fillWithByte(0, zeros); + zeros = 0; + continue; + } + var bytes = util$1.hexToBytes(ip[i]); + if(bytes.length < 2) { + b.putByte(0); + } + b.putBytes(bytes); + } + return b.getBytes(); +}; + +/** + * Converts 4-bytes into an IPv4 string representation or 16-bytes into + * an IPv6 string representation. The bytes must be in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv4 or IPv6 string representation if 4 or 16 bytes, + * respectively, are given, otherwise null. + */ +util$1.bytesToIP = function(bytes) { + if(bytes.length === 4) { + return util$1.bytesToIPv4(bytes); + } + if(bytes.length === 16) { + return util$1.bytesToIPv6(bytes); + } + return null; +}; + +/** + * Converts 4-bytes into an IPv4 string representation. The bytes must be + * in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv4 string representation or null for an invalid # of bytes. + */ +util$1.bytesToIPv4 = function(bytes) { + if(bytes.length !== 4) { + return null; + } + var ip = []; + for(var i = 0; i < bytes.length; ++i) { + ip.push(bytes.charCodeAt(i)); + } + return ip.join('.'); +}; + +/** + * Converts 16-bytes into an IPv16 string representation. The bytes must be + * in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv16 string representation or null for an invalid # of bytes. + */ +util$1.bytesToIPv6 = function(bytes) { + if(bytes.length !== 16) { + return null; + } + var ip = []; + var zeroGroups = []; + var zeroMaxGroup = 0; + for(var i = 0; i < bytes.length; i += 2) { + var hex = util$1.bytesToHex(bytes[i] + bytes[i + 1]); + // canonicalize zero representation + while(hex[0] === '0' && hex !== '0') { + hex = hex.substr(1); + } + if(hex === '0') { + var last = zeroGroups[zeroGroups.length - 1]; + var idx = ip.length; + if(!last || idx !== last.end + 1) { + zeroGroups.push({start: idx, end: idx}); + } else { + last.end = idx; + if((last.end - last.start) > + (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) { + zeroMaxGroup = zeroGroups.length - 1; + } + } + } + ip.push(hex); + } + if(zeroGroups.length > 0) { + var group = zeroGroups[zeroMaxGroup]; + // only shorten group of length > 0 + if(group.end - group.start > 0) { + ip.splice(group.start, group.end - group.start + 1, ''); + if(group.start === 0) { + ip.unshift(''); + } + if(group.end === 7) { + ip.push(''); + } + } + } + return ip.join(':'); +}; + +/** + * Estimates the number of processes that can be run concurrently. If + * creating Web Workers, keep in mind that the main JavaScript process needs + * its own core. + * + * @param options the options to use: + * update true to force an update (not use the cached value). + * @param callback(err, max) called once the operation completes. + */ +util$1.estimateCores = function(options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + if('cores' in util$1 && !options.update) { + return callback(null, util$1.cores); + } + if(typeof navigator !== 'undefined' && + 'hardwareConcurrency' in navigator && + navigator.hardwareConcurrency > 0) { + util$1.cores = navigator.hardwareConcurrency; + return callback(null, util$1.cores); + } + if(typeof Worker === 'undefined') { + // workers not available + util$1.cores = 1; + return callback(null, util$1.cores); + } + if(typeof Blob === 'undefined') { + // can't estimate, default to 2 + util$1.cores = 2; + return callback(null, util$1.cores); + } + + // create worker concurrency estimation code as blob + var blobUrl = URL.createObjectURL(new Blob(['(', + function() { + self.addEventListener('message', function(e) { + // run worker for 4 ms + var st = Date.now(); + var et = st + 4; + self.postMessage({st: st, et: et}); + }); + }.toString(), + ')()'], {type: 'application/javascript'})); + + // take 5 samples using 16 workers + sample([], 5, 16); + + function sample(max, samples, numWorkers) { + if(samples === 0) { + // get overlap average + var avg = Math.floor(max.reduce(function(avg, x) { + return avg + x; + }, 0) / max.length); + util$1.cores = Math.max(1, avg); + URL.revokeObjectURL(blobUrl); + return callback(null, util$1.cores); + } + map(numWorkers, function(err, results) { + max.push(reduce(numWorkers, results)); + sample(max, samples - 1, numWorkers); + }); + } + + function map(numWorkers, callback) { + var workers = []; + var results = []; + for(var i = 0; i < numWorkers; ++i) { + var worker = new Worker(blobUrl); + worker.addEventListener('message', function(e) { + results.push(e.data); + if(results.length === numWorkers) { + for(var i = 0; i < numWorkers; ++i) { + workers[i].terminate(); + } + callback(null, results); + } + }); + workers.push(worker); + } + for(var i = 0; i < numWorkers; ++i) { + workers[i].postMessage(i); + } + } + + function reduce(numWorkers, results) { + // find overlapping time windows + var overlaps = []; + for(var n = 0; n < numWorkers; ++n) { + var r1 = results[n]; + var overlap = overlaps[n] = []; + for(var i = 0; i < numWorkers; ++i) { + if(n === i) { + continue; + } + var r2 = results[i]; + if((r1.st > r2.st && r1.st < r2.et) || + (r2.st > r1.st && r2.st < r1.et)) { + overlap.push(i); + } + } + } + // get maximum overlaps ... don't include overlapping worker itself + // as the main JS process was also being scheduled during the work and + // would have to be subtracted from the estimate anyway + return overlaps.reduce(function(max, overlap) { + return Math.max(max, overlap.length); + }, 0); + } +}; + +/** + * Cipher base API. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ + +var forge$D = forge$F; + + +forge$D.cipher = forge$D.cipher || {}; + +// registered algorithms +forge$D.cipher.algorithms = forge$D.cipher.algorithms || {}; + +/** + * Creates a cipher object that can be used to encrypt data using the given + * algorithm and key. The algorithm may be provided as a string value for a + * previously registered algorithm or it may be given as a cipher algorithm + * API object. + * + * @param algorithm the algorithm to use, either a string or an algorithm API + * object. + * @param key the key to use, as a binary-encoded string of bytes or a + * byte buffer. + * + * @return the cipher. + */ +forge$D.cipher.createCipher = function(algorithm, key) { + var api = algorithm; + if(typeof api === 'string') { + api = forge$D.cipher.getAlgorithm(api); + if(api) { + api = api(); + } + } + if(!api) { + throw new Error('Unsupported algorithm: ' + algorithm); + } + + // assume block cipher + return new forge$D.cipher.BlockCipher({ + algorithm: api, + key: key, + decrypt: false + }); +}; + +/** + * Creates a decipher object that can be used to decrypt data using the given + * algorithm and key. The algorithm may be provided as a string value for a + * previously registered algorithm or it may be given as a cipher algorithm + * API object. + * + * @param algorithm the algorithm to use, either a string or an algorithm API + * object. + * @param key the key to use, as a binary-encoded string of bytes or a + * byte buffer. + * + * @return the cipher. + */ +forge$D.cipher.createDecipher = function(algorithm, key) { + var api = algorithm; + if(typeof api === 'string') { + api = forge$D.cipher.getAlgorithm(api); + if(api) { + api = api(); + } + } + if(!api) { + throw new Error('Unsupported algorithm: ' + algorithm); + } + + // assume block cipher + return new forge$D.cipher.BlockCipher({ + algorithm: api, + key: key, + decrypt: true + }); +}; + +/** + * Registers an algorithm by name. If the name was already registered, the + * algorithm API object will be overwritten. + * + * @param name the name of the algorithm. + * @param algorithm the algorithm API object. + */ +forge$D.cipher.registerAlgorithm = function(name, algorithm) { + name = name.toUpperCase(); + forge$D.cipher.algorithms[name] = algorithm; +}; + +/** + * Gets a registered algorithm by name. + * + * @param name the name of the algorithm. + * + * @return the algorithm, if found, null if not. + */ +forge$D.cipher.getAlgorithm = function(name) { + name = name.toUpperCase(); + if(name in forge$D.cipher.algorithms) { + return forge$D.cipher.algorithms[name]; + } + return null; +}; + +var BlockCipher = forge$D.cipher.BlockCipher = function(options) { + this.algorithm = options.algorithm; + this.mode = this.algorithm.mode; + this.blockSize = this.mode.blockSize; + this._finish = false; + this._input = null; + this.output = null; + this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; + this._decrypt = options.decrypt; + this.algorithm.initialize(options); +}; + +/** + * Starts or restarts the encryption or decryption process, whichever + * was previously configured. + * + * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array + * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in + * bytes, then it must be Nb (16) bytes in length. If the IV is given in as + * 32-bit integers, then it must be 4 integers long. + * + * Note: an IV is not required or used in ECB mode. + * + * For GCM-mode, the IV must be given as a binary-encoded string of bytes or + * a byte buffer. The number of bytes should be 12 (96 bits) as recommended + * by NIST SP-800-38D but another length may be given. + * + * @param options the options to use: + * iv the initialization vector to use as a binary-encoded string of + * bytes, null to reuse the last ciphered block from a previous + * update() (this "residue" method is for legacy support only). + * additionalData additional authentication data as a binary-encoded + * string of bytes, for 'GCM' mode, (default: none). + * tagLength desired length of authentication tag, in bits, for + * 'GCM' mode (0-128, default: 128). + * tag the authentication tag to check if decrypting, as a + * binary-encoded string of bytes. + * output the output the buffer to write to, null to create one. + */ +BlockCipher.prototype.start = function(options) { + options = options || {}; + var opts = {}; + for(var key in options) { + opts[key] = options[key]; + } + opts.decrypt = this._decrypt; + this._finish = false; + this._input = forge$D.util.createBuffer(); + this.output = options.output || forge$D.util.createBuffer(); + this.mode.start(opts); +}; + +/** + * Updates the next block according to the cipher mode. + * + * @param input the buffer to read from. + */ +BlockCipher.prototype.update = function(input) { + if(input) { + // input given, so empty it into the input buffer + this._input.putBuffer(input); + } + + // do cipher operation until it needs more input and not finished + while(!this._op.call(this.mode, this._input, this.output, this._finish) && + !this._finish) {} + + // free consumed memory from input buffer + this._input.compact(); +}; + +/** + * Finishes encrypting or decrypting. + * + * @param pad a padding function to use in CBC mode, null for default, + * signature(blockSize, buffer, decrypt). + * + * @return true if successful, false on error. + */ +BlockCipher.prototype.finish = function(pad) { + // backwards-compatibility w/deprecated padding API + // Note: will overwrite padding functions even after another start() call + if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) { + this.mode.pad = function(input) { + return pad(this.blockSize, input, false); + }; + this.mode.unpad = function(output) { + return pad(this.blockSize, output, true); + }; + } + + // build options for padding and afterFinish functions + var options = {}; + options.decrypt = this._decrypt; + + // get # of bytes that won't fill a block + options.overflow = this._input.length() % this.blockSize; + + if(!this._decrypt && this.mode.pad) { + if(!this.mode.pad(this._input, options)) { + return false; + } + } + + // do final update + this._finish = true; + this.update(); + + if(this._decrypt && this.mode.unpad) { + if(!this.mode.unpad(this.output, options)) { + return false; + } + } + + if(this.mode.afterFinish) { + if(!this.mode.afterFinish(this.output, options)) { + return false; + } + } + + return true; +}; + +/** + * Supported cipher modes. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ + +var forge$C = forge$F; + + +forge$C.cipher = forge$C.cipher || {}; + +// supported cipher modes +var modes = forge$C.cipher.modes = forge$C.cipher.modes || {}; + +/** Electronic codebook (ECB) (Don't use this; it's not secure) **/ + +modes.ecb = function(options) { + options = options || {}; + this.name = 'ECB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); +}; + +modes.ecb.prototype.start = function(options) {}; + +modes.ecb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // write output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } +}; + +modes.ecb.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // decrypt block + this.cipher.decrypt(this._inBlock, this._outBlock); + + // write output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } +}; + +modes.ecb.prototype.pad = function(input, options) { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (input.length() === this.blockSize ? + this.blockSize : (this.blockSize - input.length())); + input.fillWithByte(padding, padding); + return true; +}; + +modes.ecb.prototype.unpad = function(output, options) { + // check for error: input data not a multiple of blockSize + if(options.overflow > 0) { + return false; + } + + // ensure padding byte count is valid + var len = output.length(); + var count = output.at(len - 1); + if(count > (this.blockSize << 2)) { + return false; + } + + // trim off padding bytes + output.truncate(count); + return true; +}; + +/** Cipher-block Chaining (CBC) **/ + +modes.cbc = function(options) { + options = options || {}; + this.name = 'CBC'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); +}; + +modes.cbc.prototype.start = function(options) { + // Note: legacy support for using IV residue (has security flaws) + // if IV is null, reuse block from previous processing + if(options.iv === null) { + // must have a previous block + if(!this._prev) { + throw new Error('Invalid IV parameter.'); + } + this._iv = this._prev.slice(0); + } else if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } else { + // save IV as "previous" block + this._iv = transformIV(options.iv, this.blockSize); + this._prev = this._iv.slice(0); + } +}; + +modes.cbc.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + // CBC XOR's IV (or previous block) with plaintext + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._prev[i] ^ input.getInt32(); + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // write output, save previous block + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } + this._prev = this._outBlock; +}; + +modes.cbc.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // decrypt block + this.cipher.decrypt(this._inBlock, this._outBlock); + + // write output, save previous ciphered block + // CBC XOR's IV (or previous block) with ciphertext + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._prev[i] ^ this._outBlock[i]); + } + this._prev = this._inBlock.slice(0); +}; + +modes.cbc.prototype.pad = function(input, options) { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (input.length() === this.blockSize ? + this.blockSize : (this.blockSize - input.length())); + input.fillWithByte(padding, padding); + return true; +}; + +modes.cbc.prototype.unpad = function(output, options) { + // check for error: input data not a multiple of blockSize + if(options.overflow > 0) { + return false; + } + + // ensure padding byte count is valid + var len = output.length(); + var count = output.at(len - 1); + if(count > (this.blockSize << 2)) { + return false; + } + + // trim off padding bytes + output.truncate(count); + return true; +}; + +/** Cipher feedback (CFB) **/ + +modes.cfb = function(options) { + options = options || {}; + this.name = 'CFB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialBlock = new Array(this._ints); + this._partialOutput = forge$C.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.cfb.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.cfb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output, write input as output + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; + output.putInt32(this._inBlock[i]); + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output, write input as partial output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; + this._partialOutput.putInt32(this._partialBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +modes.cfb.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block (CFB always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output, write input as output + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + output.putInt32(this._inBlock[i] ^ this._outBlock[i]); + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output, write input as partial output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32(); + this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +/** Output feedback (OFB) **/ + +modes.ofb = function(options) { + options = options || {}; + this.name = 'OFB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge$C.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.ofb.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.ofb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(input.length() === 0) { + return true; + } + + // encrypt block (OFB always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output and update next input + for(var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + this._inBlock[i] = this._outBlock[i]; + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._outBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; + +/** Counter (CTR) **/ + +modes.ctr = function(options) { + options = options || {}; + this.name = 'CTR'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge$C.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.ctr.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.ctr.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block (CTR always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + } + } else { + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; + } + + // block complete, increment counter (input block) + inc32(this._inBlock); +}; + +modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; + +/** Galois/Counter Mode (GCM) **/ + +modes.gcm = function(options) { + options = options || {}; + this.name = 'GCM'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + this._partialOutput = forge$C.util.createBuffer(); + this._partialBytes = 0; + + // R is actually this value concatenated with 120 more zero bits, but + // we only XOR against R so the other zeros have no effect -- we just + // apply this value to the first integer in a block + this._R = 0xE1000000; +}; + +modes.gcm.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // ensure IV is a byte buffer + var iv = forge$C.util.createBuffer(options.iv); + + // no ciphered data processed yet + this._cipherLength = 0; + + // default additional data is none + var additionalData; + if('additionalData' in options) { + additionalData = forge$C.util.createBuffer(options.additionalData); + } else { + additionalData = forge$C.util.createBuffer(); + } + + // default tag length is 128 bits + if('tagLength' in options) { + this._tagLength = options.tagLength; + } else { + this._tagLength = 128; + } + + // if tag is given, ensure tag matches tag length + this._tag = null; + if(options.decrypt) { + // save tag to check later + this._tag = forge$C.util.createBuffer(options.tag).getBytes(); + if(this._tag.length !== (this._tagLength / 8)) { + throw new Error('Authentication tag does not match tag length.'); + } + } + + // create tmp storage for hash calculation + this._hashBlock = new Array(this._ints); + + // no tag generated yet + this.tag = null; + + // generate hash subkey + // (apply block cipher to "zero" block) + this._hashSubkey = new Array(this._ints); + this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); + + // generate table M + // use 4-bit tables (32 component decomposition of a 16 byte value) + // 8-bit tables take more space and are known to have security + // vulnerabilities (in native implementations) + this.componentBits = 4; + this._m = this.generateHashTable(this._hashSubkey, this.componentBits); + + // Note: support IV length different from 96 bits? (only supporting + // 96 bits is recommended by NIST SP-800-38D) + // generate J_0 + var ivLength = iv.length(); + if(ivLength === 12) { + // 96-bit IV + this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; + } else { + // IV is NOT 96-bits + this._j0 = [0, 0, 0, 0]; + while(iv.length() > 0) { + this._j0 = this.ghash( + this._hashSubkey, this._j0, + [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]); + } + this._j0 = this.ghash( + this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8))); + } + + // generate ICB (initial counter block) + this._inBlock = this._j0.slice(0); + inc32(this._inBlock); + this._partialBytes = 0; + + // consume authentication data + additionalData = forge$C.util.createBuffer(additionalData); + // save additional data length as a BE 64-bit number + this._aDataLength = from64To32(additionalData.length() * 8); + // pad additional data to 128 bit (16 byte) block size + var overflow = additionalData.length() % this.blockSize; + if(overflow) { + additionalData.fillWithByte(0, this.blockSize - overflow); + } + this._s = [0, 0, 0, 0]; + while(additionalData.length() > 0) { + this._s = this.ghash(this._hashSubkey, this._s, [ + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32() + ]); + } +}; + +modes.gcm.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^= input.getInt32()); + } + this._cipherLength += this.blockSize; + } else { + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes <= 0 || finish) { + // handle overflow prior to hashing + if(finish) { + // get block overflow + var overflow = inputLength % this.blockSize; + this._cipherLength += overflow; + // truncate for hash function + this._partialOutput.truncate(this.blockSize - overflow); + } else { + this._cipherLength += this.blockSize; + } + + // get output block for hashing + for(var i = 0; i < this._ints; ++i) { + this._outBlock[i] = this._partialOutput.getInt32(); + } + this._partialOutput.read -= this.blockSize; + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + // block still incomplete, restore input buffer, get partial output, + // and return early + input.read -= this.blockSize; + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; + } + + // update hash block S + this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); + + // increment counter (input block) + inc32(this._inBlock); +}; + +modes.gcm.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + var inputLength = input.length(); + if(inputLength < this.blockSize && !(finish && inputLength > 0)) { + return true; + } + + // encrypt block (GCM always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // increment counter (input block) + inc32(this._inBlock); + + // update hash block S + this._hashBlock[0] = input.getInt32(); + this._hashBlock[1] = input.getInt32(); + this._hashBlock[2] = input.getInt32(); + this._hashBlock[3] = input.getInt32(); + this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); + + // XOR hash input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); + } + + // increment cipher data length + if(inputLength < this.blockSize) { + this._cipherLength += inputLength % this.blockSize; + } else { + this._cipherLength += this.blockSize; + } +}; + +modes.gcm.prototype.afterFinish = function(output, options) { + var rval = true; + + // handle overflow + if(options.decrypt && options.overflow) { + output.truncate(this.blockSize - options.overflow); + } + + // handle authentication tag + this.tag = forge$C.util.createBuffer(); + + // concatenate additional data length with cipher length + var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); + + // include lengths in hash + this._s = this.ghash(this._hashSubkey, this._s, lengths); + + // do GCTR(J_0, S) + var tag = []; + this.cipher.encrypt(this._j0, tag); + for(var i = 0; i < this._ints; ++i) { + this.tag.putInt32(this._s[i] ^ tag[i]); + } + + // trim tag to length + this.tag.truncate(this.tag.length() % (this._tagLength / 8)); + + // check authentication tag + if(options.decrypt && this.tag.bytes() !== this._tag) { + rval = false; + } + + return rval; +}; + +/** + * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois + * field multiplication. The field, GF(2^128), is defined by the polynomial: + * + * x^128 + x^7 + x^2 + x + 1 + * + * Which is represented in little-endian binary form as: 11100001 (0xe1). When + * the value of a coefficient is 1, a bit is set. The value R, is the + * concatenation of this value and 120 zero bits, yielding a 128-bit value + * which matches the block size. + * + * This function will multiply two elements (vectors of bytes), X and Y, in + * the field GF(2^128). The result is initialized to zero. For each bit of + * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd) + * by the current value of Y. For each bit, the value of Y will be raised by + * a power of x (multiplied by the polynomial x). This can be achieved by + * shifting Y once to the right. If the current value of Y, prior to being + * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial. + * Otherwise, we must divide by R after shifting to find the remainder. + * + * @param x the first block to multiply by the second. + * @param y the second block to multiply by the first. + * + * @return the block result of the multiplication. + */ +modes.gcm.prototype.multiply = function(x, y) { + var z_i = [0, 0, 0, 0]; + var v_i = y.slice(0); + + // calculate Z_128 (block has 128 bits) + for(var i = 0; i < 128; ++i) { + // if x_i is 0, Z_{i+1} = Z_i (unchanged) + // else Z_{i+1} = Z_i ^ V_i + // get x_i by finding 32-bit int position, then left shift 1 by remainder + var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32)); + if(x_i) { + z_i[0] ^= v_i[0]; + z_i[1] ^= v_i[1]; + z_i[2] ^= v_i[2]; + z_i[3] ^= v_i[3]; + } + + // if LSB(V_i) is 1, V_i = V_i >> 1 + // else V_i = (V_i >> 1) ^ R + this.pow(v_i, v_i); + } + + return z_i; +}; + +modes.gcm.prototype.pow = function(x, out) { + // if LSB(x) is 1, x = x >>> 1 + // else x = (x >>> 1) ^ R + var lsb = x[3] & 1; + + // always do x >>> 1: + // starting with the rightmost integer, shift each integer to the right + // one bit, pulling in the bit from the integer to the left as its top + // most bit (do this for the last 3 integers) + for(var i = 3; i > 0; --i) { + out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31); + } + // shift the first integer normally + out[0] = x[0] >>> 1; + + // if lsb was not set, then polynomial had a degree of 127 and doesn't + // need to divided; otherwise, XOR with R to find the remainder; we only + // need to XOR the first integer since R technically ends w/120 zero bits + if(lsb) { + out[0] ^= this._R; + } +}; + +modes.gcm.prototype.tableMultiply = function(x) { + // assumes 4-bit tables are used + var z = [0, 0, 0, 0]; + for(var i = 0; i < 32; ++i) { + var idx = (i / 8) | 0; + var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF; + var ah = this._m[i][x_i]; + z[0] ^= ah[0]; + z[1] ^= ah[1]; + z[2] ^= ah[2]; + z[3] ^= ah[3]; + } + return z; +}; + +/** + * A continuing version of the GHASH algorithm that operates on a single + * block. The hash block, last hash value (Ym) and the new block to hash + * are given. + * + * @param h the hash block. + * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash. + * @param x the block to hash. + * + * @return the hashed value (Ym). + */ +modes.gcm.prototype.ghash = function(h, y, x) { + y[0] ^= x[0]; + y[1] ^= x[1]; + y[2] ^= x[2]; + y[3] ^= x[3]; + return this.tableMultiply(y); + //return this.multiply(y, h); +}; + +/** + * Precomputes a table for multiplying against the hash subkey. This + * mechanism provides a substantial speed increase over multiplication + * performed without a table. The table-based multiplication this table is + * for solves X * H by multiplying each component of X by H and then + * composing the results together using XOR. + * + * This function can be used to generate tables with different bit sizes + * for the components, however, this implementation assumes there are + * 32 components of X (which is a 16 byte vector), therefore each component + * takes 4-bits (so the table is constructed with bits=4). + * + * @param h the hash subkey. + * @param bits the bit size for a component. + */ +modes.gcm.prototype.generateHashTable = function(h, bits) { + // TODO: There are further optimizations that would use only the + // first table M_0 (or some variant) along with a remainder table; + // this can be explored in the future + var multiplier = 8 / bits; + var perInt = 4 * multiplier; + var size = 16 * multiplier; + var m = new Array(size); + for(var i = 0; i < size; ++i) { + var tmp = [0, 0, 0, 0]; + var idx = (i / perInt) | 0; + var shft = ((perInt - 1 - (i % perInt)) * bits); + tmp[idx] = (1 << (bits - 1)) << shft; + m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); + } + return m; +}; + +/** + * Generates a table for multiplying against the hash subkey for one + * particular component (out of all possible component values). + * + * @param mid the pre-multiplied value for the middle key of the table. + * @param bits the bit size for a component. + */ +modes.gcm.prototype.generateSubHashTable = function(mid, bits) { + // compute the table quickly by minimizing the number of + // POW operations -- they only need to be performed for powers of 2, + // all other entries can be composed from those powers using XOR + var size = 1 << bits; + var half = size >>> 1; + var m = new Array(size); + m[half] = mid.slice(0); + var i = half >>> 1; + while(i > 0) { + // raise m0[2 * i] and store in m0[i] + this.pow(m[2 * i], m[i] = []); + i >>= 1; + } + i = 2; + while(i < half) { + for(var j = 1; j < i; ++j) { + var m_i = m[i]; + var m_j = m[j]; + m[i + j] = [ + m_i[0] ^ m_j[0], + m_i[1] ^ m_j[1], + m_i[2] ^ m_j[2], + m_i[3] ^ m_j[3] + ]; + } + i *= 2; + } + m[0] = [0, 0, 0, 0]; + /* Note: We could avoid storing these by doing composition during multiply + calculate top half using composition by speed is preferred. */ + for(i = half + 1; i < size; ++i) { + var c = m[i ^ half]; + m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; + } + return m; +}; + +/** Utility functions */ + +function transformIV(iv, blockSize) { + if(typeof iv === 'string') { + // convert iv string into byte buffer + iv = forge$C.util.createBuffer(iv); + } + + if(forge$C.util.isArray(iv) && iv.length > 4) { + // convert iv byte array into byte buffer + var tmp = iv; + iv = forge$C.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + iv.putByte(tmp[i]); + } + } + + if(iv.length() < blockSize) { + throw new Error( + 'Invalid IV length; got ' + iv.length() + + ' bytes and expected ' + blockSize + ' bytes.'); + } + + if(!forge$C.util.isArray(iv)) { + // convert iv byte buffer into 32-bit integer array + var ints = []; + var blocks = blockSize / 4; + for(var i = 0; i < blocks; ++i) { + ints.push(iv.getInt32()); + } + iv = ints; + } + + return iv; +} + +function inc32(block) { + // increment last 32 bits of block only + block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF; +} + +function from64To32(num) { + // convert 64-bit number to two BE Int32s + return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; +} + +/** + * Advanced Encryption Standard (AES) implementation. + * + * This implementation is based on the public domain library 'jscrypto' which + * was written by: + * + * Emily Stark (estark@stanford.edu) + * Mike Hamburg (mhamburg@stanford.edu) + * Dan Boneh (dabo@cs.stanford.edu) + * + * Parts of this code are based on the OpenSSL implementation of AES: + * http://www.openssl.org + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ + +var forge$B = forge$F; + + + + +/* AES API */ +forge$B.aes = forge$B.aes || {}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('AES-', key); + * cipher.start({iv: iv}); + * + * Creates an AES cipher object to encrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as a string of bytes, an array of bytes, + * a byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge$B.aes.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher$1({ + key: key, + output: output, + decrypt: false, + mode: mode + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('AES-', key); + * + * Creates an AES cipher object to encrypt data using the given symmetric key. + * + * The key may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge$B.aes.createEncryptionCipher = function(key, mode) { + return _createCipher$1({ + key: key, + output: null, + decrypt: false, + mode: mode + }); +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('AES-', key); + * decipher.start({iv: iv}); + * + * Creates an AES cipher object to decrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as a string of bytes, an array of bytes, + * a byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge$B.aes.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher$1({ + key: key, + output: output, + decrypt: true, + mode: mode + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('AES-', key); + * + * Creates an AES cipher object to decrypt data using the given symmetric key. + * + * The key may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge$B.aes.createDecryptionCipher = function(key, mode) { + return _createCipher$1({ + key: key, + output: null, + decrypt: true, + mode: mode + }); +}; + +/** + * Creates a new AES cipher algorithm object. + * + * @param name the name of the algorithm. + * @param mode the mode factory function. + * + * @return the AES algorithm object. + */ +forge$B.aes.Algorithm = function(name, mode) { + if(!init) { + initialize(); + } + var self = this; + self.name = name; + self.mode = new mode({ + blockSize: 16, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock$1(self._w, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock$1(self._w, inBlock, outBlock, true); + } + } + }); + self._init = false; +}; + +/** + * Initializes this AES algorithm by expanding its key. + * + * @param options the options to use. + * key the key to use with this algorithm. + * decrypt true if the algorithm should be initialized for decryption, + * false for encryption. + */ +forge$B.aes.Algorithm.prototype.initialize = function(options) { + if(this._init) { + return; + } + + var key = options.key; + var tmp; + + /* Note: The key may be a string of bytes, an array of bytes, a byte + buffer, or an array of 32-bit integers. If the key is in bytes, then + it must be 16, 24, or 32 bytes in length. If it is in 32-bit + integers, it must be 4, 6, or 8 integers long. */ + + if(typeof key === 'string' && + (key.length === 16 || key.length === 24 || key.length === 32)) { + // convert key string into byte buffer + key = forge$B.util.createBuffer(key); + } else if(forge$B.util.isArray(key) && + (key.length === 16 || key.length === 24 || key.length === 32)) { + // convert key integer array into byte buffer + tmp = key; + key = forge$B.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + + // convert key byte buffer into 32-bit integer array + if(!forge$B.util.isArray(key)) { + tmp = key; + key = []; + + // key lengths of 16, 24, 32 bytes allowed + var len = tmp.length(); + if(len === 16 || len === 24 || len === 32) { + len = len >>> 2; + for(var i = 0; i < len; ++i) { + key.push(tmp.getInt32()); + } + } + } + + // key must be an array of 32-bit integers by now + if(!forge$B.util.isArray(key) || + !(key.length === 4 || key.length === 6 || key.length === 8)) { + throw new Error('Invalid key parameter.'); + } + + // encryption operation is always used for these modes + var mode = this.mode.name; + var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1); + + // do key expansion + this._w = _expandKey(key, options.decrypt && !encryptOp); + this._init = true; +}; + +/** + * Expands a key. Typically only used for testing. + * + * @param key the symmetric key to expand, as an array of 32-bit words. + * @param decrypt true to expand for decryption, false for encryption. + * + * @return the expanded key. + */ +forge$B.aes._expandKey = function(key, decrypt) { + if(!init) { + initialize(); + } + return _expandKey(key, decrypt); +}; + +/** + * Updates a single block. Typically only used for testing. + * + * @param w the expanded key to use. + * @param input an array of block-size 32-bit words. + * @param output an array of block-size 32-bit words. + * @param decrypt true to decrypt, false to encrypt. + */ +forge$B.aes._updateBlock = _updateBlock$1; + +/** Register AES algorithms **/ + +registerAlgorithm$1('AES-ECB', forge$B.cipher.modes.ecb); +registerAlgorithm$1('AES-CBC', forge$B.cipher.modes.cbc); +registerAlgorithm$1('AES-CFB', forge$B.cipher.modes.cfb); +registerAlgorithm$1('AES-OFB', forge$B.cipher.modes.ofb); +registerAlgorithm$1('AES-CTR', forge$B.cipher.modes.ctr); +registerAlgorithm$1('AES-GCM', forge$B.cipher.modes.gcm); + +function registerAlgorithm$1(name, mode) { + var factory = function() { + return new forge$B.aes.Algorithm(name, mode); + }; + forge$B.cipher.registerAlgorithm(name, factory); +} + +/** AES implementation **/ + +var init = false; // not yet initialized +var Nb = 4; // number of words comprising the state (AES = 4) +var sbox; // non-linear substitution table used in key expansion +var isbox; // inversion of sbox +var rcon; // round constant word array +var mix; // mix-columns table +var imix; // inverse mix-columns table + +/** + * Performs initialization, ie: precomputes tables to optimize for speed. + * + * One way to understand how AES works is to imagine that 'addition' and + * 'multiplication' are interfaces that require certain mathematical + * properties to hold true (ie: they are associative) but they might have + * different implementations and produce different kinds of results ... + * provided that their mathematical properties remain true. AES defines + * its own methods of addition and multiplication but keeps some important + * properties the same, ie: associativity and distributivity. The + * explanation below tries to shed some light on how AES defines addition + * and multiplication of bytes and 32-bit words in order to perform its + * encryption and decryption algorithms. + * + * The basics: + * + * The AES algorithm views bytes as binary representations of polynomials + * that have either 1 or 0 as the coefficients. It defines the addition + * or subtraction of two bytes as the XOR operation. It also defines the + * multiplication of two bytes as a finite field referred to as GF(2^8) + * (Note: 'GF' means "Galois Field" which is a field that contains a finite + * number of elements so GF(2^8) has 256 elements). + * + * This means that any two bytes can be represented as binary polynomials; + * when they multiplied together and modularly reduced by an irreducible + * polynomial of the 8th degree, the results are the field GF(2^8). The + * specific irreducible polynomial that AES uses in hexadecimal is 0x11b. + * This multiplication is associative with 0x01 as the identity: + * + * (b * 0x01 = GF(b, 0x01) = b). + * + * The operation GF(b, 0x02) can be performed at the byte level by left + * shifting b once and then XOR'ing it (to perform the modular reduction) + * with 0x11b if b is >= 128. Repeated application of the multiplication + * of 0x02 can be used to implement the multiplication of any two bytes. + * + * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can + * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these + * factors can each be multiplied by 0x57 and then added together. To do + * the multiplication, values for 0x57 multiplied by each of these 3 factors + * can be precomputed and stored in a table. To add them, the values from + * the table are XOR'd together. + * + * AES also defines addition and multiplication of words, that is 4-byte + * numbers represented as polynomials of 3 degrees where the coefficients + * are the values of the bytes. + * + * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0. + * + * Addition is performed by XOR'ing like powers of x. Multiplication + * is performed in two steps, the first is an algebriac expansion as + * you would do normally (where addition is XOR). But the result is + * a polynomial larger than 3 degrees and thus it cannot fit in a word. So + * next the result is modularly reduced by an AES-specific polynomial of + * degree 4 which will always produce a polynomial of less than 4 degrees + * such that it will fit in a word. In AES, this polynomial is x^4 + 1. + * + * The modular product of two polynomials 'a' and 'b' is thus: + * + * d(x) = d3x^3 + d2x^2 + d1x + d0 + * with + * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3) + * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3) + * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3) + * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3) + * + * As a matrix: + * + * [d0] = [a0 a3 a2 a1][b0] + * [d1] [a1 a0 a3 a2][b1] + * [d2] [a2 a1 a0 a3][b2] + * [d3] [a3 a2 a1 a0][b3] + * + * Special polynomials defined by AES (0x02 == {02}): + * a(x) = {03}x^3 + {01}x^2 + {01}x + {02} + * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}. + * + * These polynomials are used in the MixColumns() and InverseMixColumns() + * operations, respectively, to cause each element in the state to affect + * the output (referred to as diffusing). + * + * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the + * polynomial x3. + * + * The ShiftRows() method modifies the last 3 rows in the state (where + * the state is 4 words with 4 bytes per word) by shifting bytes cyclically. + * The 1st byte in the second row is moved to the end of the row. The 1st + * and 2nd bytes in the third row are moved to the end of the row. The 1st, + * 2nd, and 3rd bytes are moved in the fourth row. + * + * More details on how AES arithmetic works: + * + * In the polynomial representation of binary numbers, XOR performs addition + * and subtraction and multiplication in GF(2^8) denoted as GF(a, b) + * corresponds with the multiplication of polynomials modulo an irreducible + * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply + * polynomial 'a' with polynomial 'b' and then do a modular reduction by + * an AES-specific irreducible polynomial of degree 8. + * + * A polynomial is irreducible if its only divisors are one and itself. For + * the AES algorithm, this irreducible polynomial is: + * + * m(x) = x^8 + x^4 + x^3 + x + 1, + * + * or {01}{1b} in hexadecimal notation, where each coefficient is a bit: + * 100011011 = 283 = 0x11b. + * + * For example, GF(0x57, 0x83) = 0xc1 because + * + * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1 + * 0x85 = 131 = 10000101 = x^7 + x + 1 + * + * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1) + * = x^13 + x^11 + x^9 + x^8 + x^7 + + * x^7 + x^5 + x^3 + x^2 + x + + * x^6 + x^4 + x^2 + x + 1 + * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y + * y modulo (x^8 + x^4 + x^3 + x + 1) + * = x^7 + x^6 + 1. + * + * The modular reduction by m(x) guarantees the result will be a binary + * polynomial of less than degree 8, so that it can fit in a byte. + * + * The operation to multiply a binary polynomial b with x (the polynomial + * x in binary representation is 00000010) is: + * + * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1 + * + * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the + * most significant bit is 0 in b) then the result is already reduced. If + * it is 1, then we can reduce it by subtracting m(x) via an XOR. + * + * It follows that multiplication by x (00000010 or 0x02) can be implemented + * by performing a left shift followed by a conditional bitwise XOR with + * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by + * higher powers of x can be implemented by repeated application of xtime(). + * + * By adding intermediate results, multiplication by any constant can be + * implemented. For instance: + * + * GF(0x57, 0x13) = 0xfe because: + * + * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1) + * + * Note: We XOR with 0x11b instead of 0x1b because in javascript our + * datatype for b can be larger than 1 byte, so a left shift will not + * automatically eliminate bits that overflow a byte ... by XOR'ing the + * overflow bit with 1 (the extra one from 0x11b) we zero it out. + * + * GF(0x57, 0x02) = xtime(0x57) = 0xae + * GF(0x57, 0x04) = xtime(0xae) = 0x47 + * GF(0x57, 0x08) = xtime(0x47) = 0x8e + * GF(0x57, 0x10) = xtime(0x8e) = 0x07 + * + * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10)) + * + * And by the distributive property (since XOR is addition and GF() is + * multiplication): + * + * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10) + * = 0x57 ^ 0xae ^ 0x07 + * = 0xfe. + */ +function initialize() { + init = true; + + /* Populate the Rcon table. These are the values given by + [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02) + in the field of GF(2^8), where i starts at 1. + + rcon[0] = [0x00, 0x00, 0x00, 0x00] + rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1 + rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2 + ... + rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B + rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36 + + We only store the first byte because it is the only one used. + */ + rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]; + + // compute xtime table which maps i onto GF(i, 0x02) + var xtime = new Array(256); + for(var i = 0; i < 128; ++i) { + xtime[i] = i << 1; + xtime[i + 128] = (i + 128) << 1 ^ 0x11B; + } + + // compute all other tables + sbox = new Array(256); + isbox = new Array(256); + mix = new Array(4); + imix = new Array(4); + for(var i = 0; i < 4; ++i) { + mix[i] = new Array(256); + imix[i] = new Array(256); + } + var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; + for(var i = 0; i < 256; ++i) { + /* We need to generate the SubBytes() sbox and isbox tables so that + we can perform byte substitutions. This requires us to traverse + all of the elements in GF, find their multiplicative inverses, + and apply to each the following affine transformation: + + bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^ + b(i + 7) mod 8 ^ ci + for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the + ith bit of a byte c with the value {63} or {01100011}. + + It is possible to traverse every possible value in a Galois field + using what is referred to as a 'generator'. There are many + generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully + traverse GF we iterate 255 times, multiplying by our generator + each time. + + On each iteration we can determine the multiplicative inverse for + the current element. + + Suppose there is an element in GF 'e'. For a given generator 'g', + e = g^x. The multiplicative inverse of e is g^(255 - x). It turns + out that if use the inverse of a generator as another generator + it will produce all of the corresponding multiplicative inverses + at the same time. For this reason, we choose 5 as our inverse + generator because it only requires 2 multiplies and 1 add and its + inverse, 82, requires relatively few operations as well. + + In order to apply the affine transformation, the multiplicative + inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a + bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and + 'x'. Then 's' is left shifted and the high bit of 's' is made the + low bit. The resulting value is stored in 's'. Then 'x' is XOR'd + with 's' and stored in 'x'. On each subsequent iteration the same + operation is performed. When 4 iterations are complete, 'x' is + XOR'd with 'c' (0x63) and the transformed value is stored in 'x'. + For example: + + s = 01000001 + x = 01000001 + + iteration 1: s = 10000010, x ^= s + iteration 2: s = 00000101, x ^= s + iteration 3: s = 00001010, x ^= s + iteration 4: s = 00010100, x ^= s + x ^= 0x63 + + This can be done with a loop where s = (s << 1) | (s >> 7). However, + it can also be done by using a single 16-bit (in this case 32-bit) + number 'sx'. Since XOR is an associative operation, we can set 'sx' + to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times. + The most significant bits will flow into the high 8 bit positions + and be correctly XOR'd with one another. All that remains will be + to cycle the high 8 bits by XOR'ing them all with the lower 8 bits + afterwards. + + At the same time we're populating sbox and isbox we can precompute + the multiplication we'll need to do to do MixColumns() later. + */ + + // apply affine transformation + sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4); + sx = (sx >> 8) ^ (sx & 255) ^ 0x63; + + // update tables + sbox[e] = sx; + isbox[sx] = e; + + /* Mixing columns is done using matrix multiplication. The columns + that are to be mixed are each a single word in the current state. + The state has Nb columns (4 columns). Therefore each column is a + 4 byte word. So to mix the columns in a single column 'c' where + its rows are r0, r1, r2, and r3, we use the following matrix + multiplication: + + [2 3 1 1]*[r0,c]=[r'0,c] + [1 2 3 1] [r1,c] [r'1,c] + [1 1 2 3] [r2,c] [r'2,c] + [3 1 1 2] [r3,c] [r'3,c] + + r0, r1, r2, and r3 are each 1 byte of one of the words in the + state (a column). To do matrix multiplication for each mixed + column c' we multiply the corresponding row from the left matrix + with the corresponding column from the right matrix. In total, we + get 4 equations: + + r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c + r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c + r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c + r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c + + As usual, the multiplication is as previously defined and the + addition is XOR. In order to optimize mixing columns we can store + the multiplication results in tables. If you think of the whole + column as a word (it might help to visualize by mentally rotating + the equations above by counterclockwise 90 degrees) then you can + see that it would be useful to map the multiplications performed on + each byte (r0, r1, r2, r3) onto a word as well. For instance, we + could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the + highest 8 bits and 3*r0 in the lowest 8 bits (with the other two + respectively in the middle). This means that a table can be + constructed that uses r0 as an index to the word. We can do the + same with r1, r2, and r3, creating a total of 4 tables. + + To construct a full c', we can just look up each byte of c in + their respective tables and XOR the results together. + + Also, to build each table we only have to calculate the word + for 2,1,1,3 for every byte ... which we can do on each iteration + of this loop since we will iterate over every byte. After we have + calculated 2,1,1,3 we can get the results for the other tables + by cycling the byte at the end to the beginning. For instance + we can take the result of table 2,1,1,3 and produce table 3,2,1,1 + by moving the right most byte to the left most position just like + how you can imagine the 3 moved out of 2,1,1,3 and to the front + to produce 3,2,1,1. + + There is another optimization in that the same multiples of + the current element we need in order to advance our generator + to the next iteration can be reused in performing the 2,1,1,3 + calculation. We also calculate the inverse mix column tables, + with e,9,d,b being the inverse of 2,1,1,3. + + When we're done, and we need to actually mix columns, the first + byte of each state word should be put through mix[0] (2,1,1,3), + the second through mix[1] (3,2,1,1) and so forth. Then they should + be XOR'd together to produce the fully mixed column. + */ + + // calculate mix and imix table values + sx2 = xtime[sx]; + e2 = xtime[e]; + e4 = xtime[e2]; + e8 = xtime[e4]; + me = + (sx2 << 24) ^ // 2 + (sx << 16) ^ // 1 + (sx << 8) ^ // 1 + (sx ^ sx2); // 3 + ime = + (e2 ^ e4 ^ e8) << 24 ^ // E (14) + (e ^ e8) << 16 ^ // 9 + (e ^ e4 ^ e8) << 8 ^ // D (13) + (e ^ e2 ^ e8); // B (11) + // produce each of the mix tables by rotating the 2,1,1,3 value + for(var n = 0; n < 4; ++n) { + mix[n][e] = me; + imix[n][sx] = ime; + // cycle the right most byte to the left most position + // ie: 2,1,1,3 becomes 3,2,1,1 + me = me << 24 | me >>> 8; + ime = ime << 24 | ime >>> 8; + } + + // get next element and inverse + if(e === 0) { + // 1 is the inverse of 1 + e = ei = 1; + } else { + // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator) + // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator) + e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; + ei ^= xtime[xtime[ei]]; + } + } +} + +/** + * Generates a key schedule using the AES key expansion algorithm. + * + * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion + * routine to generate a key schedule. The Key Expansion generates a total + * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words, + * and each of the Nr rounds requires Nb words of key data. The resulting + * key schedule consists of a linear array of 4-byte words, denoted [wi ], + * with i in the range 0 <= i < Nb(Nr + 1). + * + * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk) + * AES-128 (Nb=4, Nk=4, Nr=10) + * AES-192 (Nb=4, Nk=6, Nr=12) + * AES-256 (Nb=4, Nk=8, Nr=14) + * Note: Nr=Nk+6. + * + * Nb is the number of columns (32-bit words) comprising the State (or + * number of bytes in a block). For AES, Nb=4. + * + * @param key the key to schedule (as an array of 32-bit words). + * @param decrypt true to modify the key schedule to decrypt, false not to. + * + * @return the generated key schedule. + */ +function _expandKey(key, decrypt) { + // copy the key's words to initialize the key schedule + var w = key.slice(0); + + /* RotWord() will rotate a word, moving the first byte to the last + byte's position (shifting the other bytes left). + + We will be getting the value of Rcon at i / Nk. 'i' will iterate + from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in + a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from + 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will + increase by 1. We use a counter iNk to keep track of this. + */ + + // go through the rounds expanding the key + var temp, iNk = 1; + var Nk = w.length; + var Nr1 = Nk + 6 + 1; + var end = Nb * Nr1; + for(var i = Nk; i < end; ++i) { + temp = w[i - 1]; + if(i % Nk === 0) { + // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk] + temp = + sbox[temp >>> 16 & 255] << 24 ^ + sbox[temp >>> 8 & 255] << 16 ^ + sbox[temp & 255] << 8 ^ + sbox[temp >>> 24] ^ (rcon[iNk] << 24); + iNk++; + } else if(Nk > 6 && (i % Nk === 4)) { + // temp = SubWord(temp) + temp = + sbox[temp >>> 24] << 24 ^ + sbox[temp >>> 16 & 255] << 16 ^ + sbox[temp >>> 8 & 255] << 8 ^ + sbox[temp & 255]; + } + w[i] = w[i - Nk] ^ temp; + } + + /* When we are updating a cipher block we always use the code path for + encryption whether we are decrypting or not (to shorten code and + simplify the generation of look up tables). However, because there + are differences in the decryption algorithm, other than just swapping + in different look up tables, we must transform our key schedule to + account for these changes: + + 1. The decryption algorithm gets its key rounds in reverse order. + 2. The decryption algorithm adds the round key before mixing columns + instead of afterwards. + + We don't need to modify our key schedule to handle the first case, + we can just traverse the key schedule in reverse order when decrypting. + + The second case requires a little work. + + The tables we built for performing rounds will take an input and then + perform SubBytes() and MixColumns() or, for the decrypt version, + InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires + us to AddRoundKey() before InvMixColumns(). This means we'll need to + apply some transformations to the round key to inverse-mix its columns + so they'll be correct for moving AddRoundKey() to after the state has + had its columns inverse-mixed. + + To inverse-mix the columns of the state when we're decrypting we use a + lookup table that will apply InvSubBytes() and InvMixColumns() at the + same time. However, the round key's bytes are not inverse-substituted + in the decryption algorithm. To get around this problem, we can first + substitute the bytes in the round key so that when we apply the + transformation via the InvSubBytes()+InvMixColumns() table, it will + undo our substitution leaving us with the original value that we + want -- and then inverse-mix that value. + + This change will correctly alter our key schedule so that we can XOR + each round key with our already transformed decryption state. This + allows us to use the same code path as the encryption algorithm. + + We make one more change to the decryption key. Since the decryption + algorithm runs in reverse from the encryption algorithm, we reverse + the order of the round keys to avoid having to iterate over the key + schedule backwards when running the encryption algorithm later in + decryption mode. In addition to reversing the order of the round keys, + we also swap each round key's 2nd and 4th rows. See the comments + section where rounds are performed for more details about why this is + done. These changes are done inline with the other substitution + described above. + */ + if(decrypt) { + var tmp; + var m0 = imix[0]; + var m1 = imix[1]; + var m2 = imix[2]; + var m3 = imix[3]; + var wnew = w.slice(0); + end = w.length; + for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { + // do not sub the first or last round key (round keys are Nb + // words) as no column mixing is performed before they are added, + // but do change the key order + if(i === 0 || i === (end - Nb)) { + wnew[i] = w[wi]; + wnew[i + 1] = w[wi + 3]; + wnew[i + 2] = w[wi + 2]; + wnew[i + 3] = w[wi + 1]; + } else { + // substitute each round key byte because the inverse-mix + // table will inverse-substitute it (effectively cancel the + // substitution because round key bytes aren't sub'd in + // decryption mode) and swap indexes 3 and 1 + for(var n = 0; n < Nb; ++n) { + tmp = w[wi + n]; + wnew[i + (3&-n)] = + m0[sbox[tmp >>> 24]] ^ + m1[sbox[tmp >>> 16 & 255]] ^ + m2[sbox[tmp >>> 8 & 255]] ^ + m3[sbox[tmp & 255]]; + } + } + } + w = wnew; + } + + return w; +} + +/** + * Updates a single block (16 bytes) using AES. The update will either + * encrypt or decrypt the block. + * + * @param w the key schedule. + * @param input the input block (an array of 32-bit words). + * @param output the updated output block. + * @param decrypt true to decrypt the block, false to encrypt it. + */ +function _updateBlock$1(w, input, output, decrypt) { + /* + Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) + begin + byte state[4,Nb] + state = in + AddRoundKey(state, w[0, Nb-1]) + for round = 1 step 1 to Nr-1 + SubBytes(state) + ShiftRows(state) + MixColumns(state) + AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) + end for + SubBytes(state) + ShiftRows(state) + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + out = state + end + + InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) + begin + byte state[4,Nb] + state = in + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + for round = Nr-1 step -1 downto 1 + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) + InvMixColumns(state) + end for + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[0, Nb-1]) + out = state + end + */ + + // Encrypt: AddRoundKey(state, w[0, Nb-1]) + // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + var Nr = w.length / 4 - 1; + var m0, m1, m2, m3, sub; + if(decrypt) { + m0 = imix[0]; + m1 = imix[1]; + m2 = imix[2]; + m3 = imix[3]; + sub = isbox; + } else { + m0 = mix[0]; + m1 = mix[1]; + m2 = mix[2]; + m3 = mix[3]; + sub = sbox; + } + var a, b, c, d, a2, b2, c2; + a = input[0] ^ w[0]; + b = input[decrypt ? 3 : 1] ^ w[1]; + c = input[2] ^ w[2]; + d = input[decrypt ? 1 : 3] ^ w[3]; + var i = 3; + + /* In order to share code we follow the encryption algorithm when both + encrypting and decrypting. To account for the changes required in the + decryption algorithm, we use different lookup tables when decrypting + and use a modified key schedule to account for the difference in the + order of transformations applied when performing rounds. We also get + key rounds in reverse order (relative to encryption). */ + for(var round = 1; round < Nr; ++round) { + /* As described above, we'll be using table lookups to perform the + column mixing. Each column is stored as a word in the state (the + array 'input' has one column as a word at each index). In order to + mix a column, we perform these transformations on each row in c, + which is 1 byte in each word. The new column for c0 is c'0: + + m0 m1 m2 m3 + r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0 + r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0 + r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0 + r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0 + + So using mix tables where c0 is a word with r0 being its upper + 8 bits and r3 being its lower 8 bits: + + m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0] + ... + m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3] + + Therefore to mix the columns in each word in the state we + do the following (& 255 omitted for brevity): + c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + + However, before mixing, the algorithm requires us to perform + ShiftRows(). The ShiftRows() transformation cyclically shifts the + last 3 rows of the state over different offsets. The first row + (r = 0) is not shifted. + + s'_r,c = s_r,(c + shift(r, Nb) mod Nb + for 0 < r < 4 and 0 <= c < Nb and + shift(1, 4) = 1 + shift(2, 4) = 2 + shift(3, 4) = 3. + + This causes the first byte in r = 1 to be moved to the end of + the row, the first 2 bytes in r = 2 to be moved to the end of + the row, the first 3 bytes in r = 3 to be moved to the end of + the row: + + r1: [c0 c1 c2 c3] => [c1 c2 c3 c0] + r2: [c0 c1 c2 c3] [c2 c3 c0 c1] + r3: [c0 c1 c2 c3] [c3 c0 c1 c2] + + We can make these substitutions inline with our column mixing to + generate an updated set of equations to produce each word in the + state (note the columns have changed positions): + + c0 c1 c2 c3 => c0 c1 c2 c3 + c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte) + c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes) + c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes) + + Therefore: + + c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3 + c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3 + c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3 + c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3 + + c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0 + c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0 + c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0 + c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0 + + ... and so forth for c'2 and c'3. The important distinction is + that the columns are cycling, with c0 being used with the m0 + map when calculating c0, but c1 being used with the m0 map when + calculating c1 ... and so forth. + + When performing the inverse we transform the mirror image and + skip the bottom row, instead of the top one, and move upwards: + + c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption + c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes) + c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption + c3 c2 c1 c0 c3 c2 c1 c0 + + If you compare the resulting matrices for ShiftRows()+MixColumns() + and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are + different (in encrypt mode vs. decrypt mode). So in order to use + the same code to handle both encryption and decryption, we will + need to do some mapping. + + If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be + a row number in the state, then the resulting matrix in encryption + mode for applying the above transformations would be: + + r1: a b c d + r2: b c d a + r3: c d a b + r4: d a b c + + If we did the same in decryption mode we would get: + + r1: a d c b + r2: b a d c + r3: c b a d + r4: d c b a + + If instead we swap d and b (set b=c3 and d=c1), then we get: + + r1: a b c d + r2: d a b c + r3: c d a b + r4: b c d a + + Now the 1st and 3rd rows are the same as the encryption matrix. All + we need to do then to make the mapping exactly the same is to swap + the 2nd and 4th rows when in decryption mode. To do this without + having to do it on each iteration, we swapped the 2nd and 4th rows + in the decryption key schedule. We also have to do the swap above + when we first pull in the input and when we set the final output. */ + a2 = + m0[a >>> 24] ^ + m1[b >>> 16 & 255] ^ + m2[c >>> 8 & 255] ^ + m3[d & 255] ^ w[++i]; + b2 = + m0[b >>> 24] ^ + m1[c >>> 16 & 255] ^ + m2[d >>> 8 & 255] ^ + m3[a & 255] ^ w[++i]; + c2 = + m0[c >>> 24] ^ + m1[d >>> 16 & 255] ^ + m2[a >>> 8 & 255] ^ + m3[b & 255] ^ w[++i]; + d = + m0[d >>> 24] ^ + m1[a >>> 16 & 255] ^ + m2[b >>> 8 & 255] ^ + m3[c & 255] ^ w[++i]; + a = a2; + b = b2; + c = c2; + } + + /* + Encrypt: + SubBytes(state) + ShiftRows(state) + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + + Decrypt: + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[0, Nb-1]) + */ + // Note: rows are shifted inline + output[0] = + (sub[a >>> 24] << 24) ^ + (sub[b >>> 16 & 255] << 16) ^ + (sub[c >>> 8 & 255] << 8) ^ + (sub[d & 255]) ^ w[++i]; + output[decrypt ? 3 : 1] = + (sub[b >>> 24] << 24) ^ + (sub[c >>> 16 & 255] << 16) ^ + (sub[d >>> 8 & 255] << 8) ^ + (sub[a & 255]) ^ w[++i]; + output[2] = + (sub[c >>> 24] << 24) ^ + (sub[d >>> 16 & 255] << 16) ^ + (sub[a >>> 8 & 255] << 8) ^ + (sub[b & 255]) ^ w[++i]; + output[decrypt ? 1 : 3] = + (sub[d >>> 24] << 24) ^ + (sub[a >>> 16 & 255] << 16) ^ + (sub[b >>> 8 & 255] << 8) ^ + (sub[c & 255]) ^ w[++i]; +} + +/** + * Deprecated. Instead, use: + * + * forge.cipher.createCipher('AES-', key); + * forge.cipher.createDecipher('AES-', key); + * + * Creates a deprecated AES cipher object. This object's mode will default to + * CBC (cipher-block-chaining). + * + * The key and iv may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param options the options to use. + * key the symmetric key to use. + * output the buffer to write to. + * decrypt true for decryption, false for encryption. + * mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +function _createCipher$1(options) { + options = options || {}; + var mode = (options.mode || 'CBC').toUpperCase(); + var algorithm = 'AES-' + mode; + + var cipher; + if(options.decrypt) { + cipher = forge$B.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge$B.cipher.createCipher(algorithm, options.key); + } + + // backwards compatible start API + var start = cipher.start; + cipher.start = function(iv, options) { + // backwards compatibility: support second arg as output buffer + var output = null; + if(options instanceof forge$B.util.ByteBuffer) { + output = options; + options = {}; + } + options = options || {}; + options.output = output; + options.iv = iv; + start.call(cipher, options); + }; + + return cipher; +} + +/** + * Object IDs for ASN.1. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ + +var forge$A = forge$F; + +forge$A.pki = forge$A.pki || {}; +var oids$2 = forge$A.pki.oids = forge$A.oids = forge$A.oids || {}; + +// set id to name mapping and name to id mapping +function _IN(id, name) { + oids$2[id] = name; + oids$2[name] = id; +} +// set id to name mapping only +function _I_(id, name) { + oids$2[id] = name; +} + +// algorithm OIDs +_IN('1.2.840.113549.1.1.1', 'rsaEncryption'); +// Note: md2 & md4 not implemented +//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption'); +//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption'); +_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption'); +_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption'); +_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP'); +_IN('1.2.840.113549.1.1.8', 'mgf1'); +_IN('1.2.840.113549.1.1.9', 'pSpecified'); +_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS'); +_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption'); +_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption'); +_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption'); +// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519 +_IN('1.3.101.112', 'EdDSA25519'); + +_IN('1.2.840.10040.4.3', 'dsa-with-sha1'); + +_IN('1.3.14.3.2.7', 'desCBC'); + +_IN('1.3.14.3.2.26', 'sha1'); +_IN('2.16.840.1.101.3.4.2.1', 'sha256'); +_IN('2.16.840.1.101.3.4.2.2', 'sha384'); +_IN('2.16.840.1.101.3.4.2.3', 'sha512'); +_IN('1.2.840.113549.2.5', 'md5'); + +// pkcs#7 content types +_IN('1.2.840.113549.1.7.1', 'data'); +_IN('1.2.840.113549.1.7.2', 'signedData'); +_IN('1.2.840.113549.1.7.3', 'envelopedData'); +_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData'); +_IN('1.2.840.113549.1.7.5', 'digestedData'); +_IN('1.2.840.113549.1.7.6', 'encryptedData'); + +// pkcs#9 oids +_IN('1.2.840.113549.1.9.1', 'emailAddress'); +_IN('1.2.840.113549.1.9.2', 'unstructuredName'); +_IN('1.2.840.113549.1.9.3', 'contentType'); +_IN('1.2.840.113549.1.9.4', 'messageDigest'); +_IN('1.2.840.113549.1.9.5', 'signingTime'); +_IN('1.2.840.113549.1.9.6', 'counterSignature'); +_IN('1.2.840.113549.1.9.7', 'challengePassword'); +_IN('1.2.840.113549.1.9.8', 'unstructuredAddress'); +_IN('1.2.840.113549.1.9.14', 'extensionRequest'); + +_IN('1.2.840.113549.1.9.20', 'friendlyName'); +_IN('1.2.840.113549.1.9.21', 'localKeyId'); +_IN('1.2.840.113549.1.9.22.1', 'x509Certificate'); + +// pkcs#12 safe bags +_IN('1.2.840.113549.1.12.10.1.1', 'keyBag'); +_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag'); +_IN('1.2.840.113549.1.12.10.1.3', 'certBag'); +_IN('1.2.840.113549.1.12.10.1.4', 'crlBag'); +_IN('1.2.840.113549.1.12.10.1.5', 'secretBag'); +_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag'); + +// password-based-encryption for pkcs#12 +_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2'); +_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2'); + +_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4'); +_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4'); +_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC'); +_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC'); +_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC'); +_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC'); + +// hmac OIDs +_IN('1.2.840.113549.2.7', 'hmacWithSHA1'); +_IN('1.2.840.113549.2.8', 'hmacWithSHA224'); +_IN('1.2.840.113549.2.9', 'hmacWithSHA256'); +_IN('1.2.840.113549.2.10', 'hmacWithSHA384'); +_IN('1.2.840.113549.2.11', 'hmacWithSHA512'); + +// symmetric key algorithm oids +_IN('1.2.840.113549.3.7', 'des-EDE3-CBC'); +_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC'); +_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC'); +_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC'); + +// certificate issuer/subject OIDs +_IN('2.5.4.3', 'commonName'); +_IN('2.5.4.5', 'serialName'); +_IN('2.5.4.6', 'countryName'); +_IN('2.5.4.7', 'localityName'); +_IN('2.5.4.8', 'stateOrProvinceName'); +_IN('2.5.4.9', 'streetAddress'); +_IN('2.5.4.10', 'organizationName'); +_IN('2.5.4.11', 'organizationalUnitName'); +_IN('2.5.4.13', 'description'); +_IN('2.5.4.15', 'businessCategory'); +_IN('2.5.4.17', 'postalCode'); +_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName'); +_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName'); + +// X.509 extension OIDs +_IN('2.16.840.1.113730.1.1', 'nsCertType'); +_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used +_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35 +_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15 +_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32 +_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15 +_I_('2.5.29.5', 'policyMapping'); // deprecated use .33 +_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30 +_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17 +_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18 +_I_('2.5.29.9', 'subjectDirectoryAttributes'); +_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19 +_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30 +_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36 +_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19 +_IN('2.5.29.14', 'subjectKeyIdentifier'); +_IN('2.5.29.15', 'keyUsage'); +_I_('2.5.29.16', 'privateKeyUsagePeriod'); +_IN('2.5.29.17', 'subjectAltName'); +_IN('2.5.29.18', 'issuerAltName'); +_IN('2.5.29.19', 'basicConstraints'); +_I_('2.5.29.20', 'cRLNumber'); +_I_('2.5.29.21', 'cRLReason'); +_I_('2.5.29.22', 'expirationDate'); +_I_('2.5.29.23', 'instructionCode'); +_I_('2.5.29.24', 'invalidityDate'); +_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31 +_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28 +_I_('2.5.29.27', 'deltaCRLIndicator'); +_I_('2.5.29.28', 'issuingDistributionPoint'); +_I_('2.5.29.29', 'certificateIssuer'); +_I_('2.5.29.30', 'nameConstraints'); +_IN('2.5.29.31', 'cRLDistributionPoints'); +_IN('2.5.29.32', 'certificatePolicies'); +_I_('2.5.29.33', 'policyMappings'); +_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36 +_IN('2.5.29.35', 'authorityKeyIdentifier'); +_I_('2.5.29.36', 'policyConstraints'); +_IN('2.5.29.37', 'extKeyUsage'); +_I_('2.5.29.46', 'freshestCRL'); +_I_('2.5.29.54', 'inhibitAnyPolicy'); + +// extKeyUsage purposes +_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList'); +_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess'); +_IN('1.3.6.1.5.5.7.3.1', 'serverAuth'); +_IN('1.3.6.1.5.5.7.3.2', 'clientAuth'); +_IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); +_IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); +_IN('1.3.6.1.5.5.7.3.8', 'timeStamping'); + +/** + * Javascript implementation of Abstract Syntax Notation Number One. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + * + * An API for storing data using the Abstract Syntax Notation Number One + * format using DER (Distinguished Encoding Rules) encoding. This encoding is + * commonly used to store data for PKI, i.e. X.509 Certificates, and this + * implementation exists for that purpose. + * + * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract + * syntax of information without restricting the way the information is encoded + * for transmission. It provides a standard that allows for open systems + * communication. ASN.1 defines the syntax of information data and a number of + * simple data types as well as a notation for describing them and specifying + * values for them. + * + * The RSA algorithm creates public and private keys that are often stored in + * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This + * class provides the most basic functionality required to store and load DSA + * keys that are encoded according to ASN.1. + * + * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules) + * and DER (Distinguished Encoding Rules). DER is just a subset of BER that + * has stricter requirements for how data must be encoded. + * + * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type) + * and a byte array for the value of this ASN1 structure which may be data or a + * list of ASN.1 structures. + * + * Each ASN.1 structure using BER is (Tag-Length-Value): + * + * | byte 0 | bytes X | bytes Y | + * |--------|---------|---------- + * | tag | length | value | + * + * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to + * be two or more octets, but that is not supported by this class. A tag is + * only 1 byte. Bits 1-5 give the tag number (ie the data type within a + * particular 'class'), 6 indicates whether or not the ASN.1 value is + * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If + * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set, + * then the class is APPLICATION. If only bit 8 is set, then the class is + * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE. + * The tag numbers for the data types for the class UNIVERSAL are listed below: + * + * UNIVERSAL 0 Reserved for use by the encoding rules + * UNIVERSAL 1 Boolean type + * UNIVERSAL 2 Integer type + * UNIVERSAL 3 Bitstring type + * UNIVERSAL 4 Octetstring type + * UNIVERSAL 5 Null type + * UNIVERSAL 6 Object identifier type + * UNIVERSAL 7 Object descriptor type + * UNIVERSAL 8 External type and Instance-of type + * UNIVERSAL 9 Real type + * UNIVERSAL 10 Enumerated type + * UNIVERSAL 11 Embedded-pdv type + * UNIVERSAL 12 UTF8String type + * UNIVERSAL 13 Relative object identifier type + * UNIVERSAL 14-15 Reserved for future editions + * UNIVERSAL 16 Sequence and Sequence-of types + * UNIVERSAL 17 Set and Set-of types + * UNIVERSAL 18-22, 25-30 Character string types + * UNIVERSAL 23-24 Time types + * + * The length of an ASN.1 structure is specified after the tag identifier. + * There is a definite form and an indefinite form. The indefinite form may + * be used if the encoding is constructed and not all immediately available. + * The indefinite form is encoded using a length byte with only the 8th bit + * set. The end of the constructed object is marked using end-of-contents + * octets (two zero bytes). + * + * The definite form looks like this: + * + * The length may take up 1 or more bytes, it depends on the length of the + * value of the ASN.1 structure. DER encoding requires that if the ASN.1 + * structure has a value that has a length greater than 127, more than 1 byte + * will be used to store its length, otherwise just one byte will be used. + * This is strict. + * + * In the case that the length of the ASN.1 value is less than 127, 1 octet + * (byte) is used to store the "short form" length. The 8th bit has a value of + * 0 indicating the length is "short form" and not "long form" and bits 7-1 + * give the length of the data. (The 8th bit is the left-most, most significant + * bit: also known as big endian or network format). + * + * In the case that the length of the ASN.1 value is greater than 127, 2 to + * 127 octets (bytes) are used to store the "long form" length. The first + * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1 + * give the number of additional octets. All following octets are in base 256 + * with the most significant digit first (typical big-endian binary unsigned + * integer storage). So, for instance, if the length of a value was 257, the + * first byte would be set to: + * + * 10000010 = 130 = 0x82. + * + * This indicates there are 2 octets (base 256) for the length. The second and + * third bytes (the octets just mentioned) would store the length in base 256: + * + * octet 2: 00000001 = 1 * 256^1 = 256 + * octet 3: 00000001 = 1 * 256^0 = 1 + * total = 257 + * + * The algorithm for converting a js integer value of 257 to base-256 is: + * + * var value = 257; + * var bytes = []; + * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first + * bytes[1] = value & 0xFF; // least significant byte last + * + * On the ASN.1 UNIVERSAL Object Identifier (OID) type: + * + * An OID can be written like: "value1.value2.value3...valueN" + * + * The DER encoding rules: + * + * The first byte has the value 40 * value1 + value2. + * The following bytes, if any, encode the remaining values. Each value is + * encoded in base 128, most significant digit first (big endian), with as + * few digits as possible, and the most significant bit of each byte set + * to 1 except the last in each value's encoding. For example: Given the + * OID "1.2.840.113549", its DER encoding is (remember each byte except the + * last one in each encoding is OR'd with 0x80): + * + * byte 1: 40 * 1 + 2 = 42 = 0x2A. + * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648 + * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D + * + * The final value is: 0x2A864886F70D. + * The full OID (including ASN.1 tag and length of 6 bytes) is: + * 0x06062A864886F70D + */ + +var forge$z = forge$F; + + + +/* ASN.1 API */ +var asn1$8 = forge$z.asn1 = forge$z.asn1 || {}; + +/** + * ASN.1 classes. + */ +asn1$8.Class = { + UNIVERSAL: 0x00, + APPLICATION: 0x40, + CONTEXT_SPECIFIC: 0x80, + PRIVATE: 0xC0 +}; + +/** + * ASN.1 types. Not all types are supported by this implementation, only + * those necessary to implement a simple PKI are implemented. + */ +asn1$8.Type = { + NONE: 0, + BOOLEAN: 1, + INTEGER: 2, + BITSTRING: 3, + OCTETSTRING: 4, + NULL: 5, + OID: 6, + ODESC: 7, + EXTERNAL: 8, + REAL: 9, + ENUMERATED: 10, + EMBEDDED: 11, + UTF8: 12, + ROID: 13, + SEQUENCE: 16, + SET: 17, + PRINTABLESTRING: 19, + IA5STRING: 22, + UTCTIME: 23, + GENERALIZEDTIME: 24, + BMPSTRING: 30 +}; + +/** + * Creates a new asn1 object. + * + * @param tagClass the tag class for the object. + * @param type the data type (tag number) for the object. + * @param constructed true if the asn1 object is in constructed form. + * @param value the value for the object, if it is not constructed. + * @param [options] the options to use: + * [bitStringContents] the plain BIT STRING content including padding + * byte. + * + * @return the asn1 object. + */ +asn1$8.create = function(tagClass, type, constructed, value, options) { + /* An asn1 object has a tagClass, a type, a constructed flag, and a + value. The value's type depends on the constructed flag. If + constructed, it will contain a list of other asn1 objects. If not, + it will contain the ASN.1 value as an array of bytes formatted + according to the ASN.1 data type. */ + + // remove undefined values + if(forge$z.util.isArray(value)) { + var tmp = []; + for(var i = 0; i < value.length; ++i) { + if(value[i] !== undefined) { + tmp.push(value[i]); + } + } + value = tmp; + } + + var obj = { + tagClass: tagClass, + type: type, + constructed: constructed, + composed: constructed || forge$z.util.isArray(value), + value: value + }; + if(options && 'bitStringContents' in options) { + // TODO: copy byte buffer if it's a buffer not a string + obj.bitStringContents = options.bitStringContents; + // TODO: add readonly flag to avoid this overhead + // save copy to detect changes + obj.original = asn1$8.copy(obj); + } + return obj; +}; + +/** + * Copies an asn1 object. + * + * @param obj the asn1 object. + * @param [options] copy options: + * [excludeBitStringContents] true to not copy bitStringContents + * + * @return the a copy of the asn1 object. + */ +asn1$8.copy = function(obj, options) { + var copy; + + if(forge$z.util.isArray(obj)) { + copy = []; + for(var i = 0; i < obj.length; ++i) { + copy.push(asn1$8.copy(obj[i], options)); + } + return copy; + } + + if(typeof obj === 'string') { + // TODO: copy byte buffer if it's a buffer not a string + return obj; + } + + copy = { + tagClass: obj.tagClass, + type: obj.type, + constructed: obj.constructed, + composed: obj.composed, + value: asn1$8.copy(obj.value, options) + }; + if(options && !options.excludeBitStringContents) { + // TODO: copy byte buffer if it's a buffer not a string + copy.bitStringContents = obj.bitStringContents; + } + return copy; +}; + +/** + * Compares asn1 objects for equality. + * + * Note this function does not run in constant time. + * + * @param obj1 the first asn1 object. + * @param obj2 the second asn1 object. + * @param [options] compare options: + * [includeBitStringContents] true to compare bitStringContents + * + * @return true if the asn1 objects are equal. + */ +asn1$8.equals = function(obj1, obj2, options) { + if(forge$z.util.isArray(obj1)) { + if(!forge$z.util.isArray(obj2)) { + return false; + } + if(obj1.length !== obj2.length) { + return false; + } + for(var i = 0; i < obj1.length; ++i) { + if(!asn1$8.equals(obj1[i], obj2[i])) { + return false; + } + } + return true; + } + + if(typeof obj1 !== typeof obj2) { + return false; + } + + if(typeof obj1 === 'string') { + return obj1 === obj2; + } + + var equal = obj1.tagClass === obj2.tagClass && + obj1.type === obj2.type && + obj1.constructed === obj2.constructed && + obj1.composed === obj2.composed && + asn1$8.equals(obj1.value, obj2.value); + if(options && options.includeBitStringContents) { + equal = equal && (obj1.bitStringContents === obj2.bitStringContents); + } + + return equal; +}; + +/** + * Gets the length of a BER-encoded ASN.1 value. + * + * In case the length is not specified, undefined is returned. + * + * @param b the BER-encoded ASN.1 byte buffer, starting with the first + * length byte. + * + * @return the length of the BER-encoded ASN.1 value or undefined. + */ +asn1$8.getBerValueLength = function(b) { + // TODO: move this function and related DER/BER functions to a der.js + // file; better abstract ASN.1 away from der/ber. + var b2 = b.getByte(); + if(b2 === 0x80) { + return undefined; + } + + // see if the length is "short form" or "long form" (bit 8 set) + var length; + var longForm = b2 & 0x80; + if(!longForm) { + // length is just the first byte + length = b2; + } else { + // the number of bytes the length is specified in bits 7 through 1 + // and each length byte is in big-endian base-256 + length = b.getInt((b2 & 0x7F) << 3); + } + return length; +}; + +/** + * Check if the byte buffer has enough bytes. Throws an Error if not. + * + * @param bytes the byte buffer to parse from. + * @param remaining the bytes remaining in the current parsing state. + * @param n the number of bytes the buffer must have. + */ +function _checkBufferLength(bytes, remaining, n) { + if(n > remaining) { + var error = new Error('Too few bytes to parse DER.'); + error.available = bytes.length(); + error.remaining = remaining; + error.requested = n; + throw error; + } +} + +/** + * Gets the length of a BER-encoded ASN.1 value. + * + * In case the length is not specified, undefined is returned. + * + * @param bytes the byte buffer to parse from. + * @param remaining the bytes remaining in the current parsing state. + * + * @return the length of the BER-encoded ASN.1 value or undefined. + */ +var _getValueLength = function(bytes, remaining) { + // TODO: move this function and related DER/BER functions to a der.js + // file; better abstract ASN.1 away from der/ber. + // fromDer already checked that this byte exists + var b2 = bytes.getByte(); + remaining--; + if(b2 === 0x80) { + return undefined; + } + + // see if the length is "short form" or "long form" (bit 8 set) + var length; + var longForm = b2 & 0x80; + if(!longForm) { + // length is just the first byte + length = b2; + } else { + // the number of bytes the length is specified in bits 7 through 1 + // and each length byte is in big-endian base-256 + var longFormBytes = b2 & 0x7F; + _checkBufferLength(bytes, remaining, longFormBytes); + length = bytes.getInt(longFormBytes << 3); + } + // FIXME: this will only happen for 32 bit getInt with high bit set + if(length < 0) { + throw new Error('Negative length: ' + length); + } + return length; +}; + +/** + * Parses an asn1 object from a byte buffer in DER format. + * + * @param bytes the byte buffer to parse from. + * @param [strict] true to be strict when checking value lengths, false to + * allow truncated values (default: true). + * @param [options] object with options or boolean strict flag + * [strict] true to be strict when checking value lengths, false to + * allow truncated values (default: true). + * [decodeBitStrings] true to attempt to decode the content of + * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that + * without schema support to understand the data context this can + * erroneously decode values that happen to be valid ASN.1. This + * flag will be deprecated or removed as soon as schema support is + * available. (default: true) + * + * @return the parsed asn1 object. + */ +asn1$8.fromDer = function(bytes, options) { + if(options === undefined) { + options = { + strict: true, + decodeBitStrings: true + }; + } + if(typeof options === 'boolean') { + options = { + strict: options, + decodeBitStrings: true + }; + } + if(!('strict' in options)) { + options.strict = true; + } + if(!('decodeBitStrings' in options)) { + options.decodeBitStrings = true; + } + + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge$z.util.createBuffer(bytes); + } + + return _fromDer(bytes, bytes.length(), 0, options); +}; + +/** + * Internal function to parse an asn1 object from a byte buffer in DER format. + * + * @param bytes the byte buffer to parse from. + * @param remaining the number of bytes remaining for this chunk. + * @param depth the current parsing depth. + * @param options object with same options as fromDer(). + * + * @return the parsed asn1 object. + */ +function _fromDer(bytes, remaining, depth, options) { + // temporary storage for consumption calculations + var start; + + // minimum length for ASN.1 DER structure is 2 + _checkBufferLength(bytes, remaining, 2); + + // get the first byte + var b1 = bytes.getByte(); + // consumed one byte + remaining--; + + // get the tag class + var tagClass = (b1 & 0xC0); + + // get the type (bits 1-5) + var type = b1 & 0x1F; + + // get the variable value length and adjust remaining bytes + start = bytes.length(); + var length = _getValueLength(bytes, remaining); + remaining -= start - bytes.length(); + + // ensure there are enough bytes to get the value + if(length !== undefined && length > remaining) { + if(options.strict) { + var error = new Error('Too few bytes to read ASN.1 value.'); + error.available = bytes.length(); + error.remaining = remaining; + error.requested = length; + throw error; + } + // Note: be lenient with truncated values and use remaining state bytes + length = remaining; + } + + // value storage + var value; + // possible BIT STRING contents storage + var bitStringContents; + + // constructed flag is bit 6 (32 = 0x20) of the first byte + var constructed = ((b1 & 0x20) === 0x20); + if(constructed) { + // parse child asn1 objects from the value + value = []; + if(length === undefined) { + // asn1 object of indefinite length, read until end tag + for(;;) { + _checkBufferLength(bytes, remaining, 2); + if(bytes.bytes(2) === String.fromCharCode(0, 0)) { + bytes.getBytes(2); + remaining -= 2; + break; + } + start = bytes.length(); + value.push(_fromDer(bytes, remaining, depth + 1, options)); + remaining -= start - bytes.length(); + } + } else { + // parsing asn1 object of definite length + while(length > 0) { + start = bytes.length(); + value.push(_fromDer(bytes, length, depth + 1, options)); + remaining -= start - bytes.length(); + length -= start - bytes.length(); + } + } + } + + // if a BIT STRING, save the contents including padding + if(value === undefined && tagClass === asn1$8.Class.UNIVERSAL && + type === asn1$8.Type.BITSTRING) { + bitStringContents = bytes.bytes(length); + } + + // determine if a non-constructed value should be decoded as a composed + // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs) + // can be used this way. + if(value === undefined && options.decodeBitStrings && + tagClass === asn1$8.Class.UNIVERSAL && + // FIXME: OCTET STRINGs not yet supported here + // .. other parts of forge expect to decode OCTET STRINGs manually + (type === asn1$8.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) && + length > 1) { + // save read position + var savedRead = bytes.read; + var savedRemaining = remaining; + var unused = 0; + if(type === asn1$8.Type.BITSTRING) { + /* The first octet gives the number of bits by which the length of the + bit string is less than the next multiple of eight (this is called + the "number of unused bits"). + + The second and following octets give the value of the bit string + converted to an octet string. */ + _checkBufferLength(bytes, remaining, 1); + unused = bytes.getByte(); + remaining--; + } + // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs + if(unused === 0) { + try { + // attempt to parse child asn1 object from the value + // (stored in array to signal composed value) + start = bytes.length(); + var subOptions = { + // enforce strict mode to avoid parsing ASN.1 from plain data + verbose: options.verbose, + strict: true, + decodeBitStrings: true + }; + var composed = _fromDer(bytes, remaining, depth + 1, subOptions); + var used = start - bytes.length(); + remaining -= used; + if(type == asn1$8.Type.BITSTRING) { + used++; + } + + // if the data all decoded and the class indicates UNIVERSAL or + // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object + var tc = composed.tagClass; + if(used === length && + (tc === asn1$8.Class.UNIVERSAL || tc === asn1$8.Class.CONTEXT_SPECIFIC)) { + value = [composed]; + } + } catch(ex) { + } + } + if(value === undefined) { + // restore read position + bytes.read = savedRead; + remaining = savedRemaining; + } + } + + if(value === undefined) { + // asn1 not constructed or composed, get raw value + // TODO: do DER to OID conversion and vice-versa in .toDer? + + if(length === undefined) { + if(options.strict) { + throw new Error('Non-constructed ASN.1 object of indefinite length.'); + } + // be lenient and use remaining state bytes + length = remaining; + } + + if(type === asn1$8.Type.BMPSTRING) { + value = ''; + for(; length > 0; length -= 2) { + _checkBufferLength(bytes, remaining, 2); + value += String.fromCharCode(bytes.getInt16()); + remaining -= 2; + } + } else { + value = bytes.getBytes(length); + } + } + + // add BIT STRING contents if available + var asn1Options = bitStringContents === undefined ? null : { + bitStringContents: bitStringContents + }; + + // create and return asn1 object + return asn1$8.create(tagClass, type, constructed, value, asn1Options); +} + +/** + * Converts the given asn1 object to a buffer of bytes in DER format. + * + * @param asn1 the asn1 object to convert to bytes. + * + * @return the buffer of bytes. + */ +asn1$8.toDer = function(obj) { + var bytes = forge$z.util.createBuffer(); + + // build the first byte + var b1 = obj.tagClass | obj.type; + + // for storing the ASN.1 value + var value = forge$z.util.createBuffer(); + + // use BIT STRING contents if available and data not changed + var useBitStringContents = false; + if('bitStringContents' in obj) { + useBitStringContents = true; + if(obj.original) { + useBitStringContents = asn1$8.equals(obj, obj.original); + } + } + + if(useBitStringContents) { + value.putBytes(obj.bitStringContents); + } else if(obj.composed) { + // if composed, use each child asn1 object's DER bytes as value + // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed + // from other asn1 objects + if(obj.constructed) { + b1 |= 0x20; + } else { + // type is a bit string, add unused bits of 0x00 + value.putByte(0x00); + } + + // add all of the child DER bytes together + for(var i = 0; i < obj.value.length; ++i) { + if(obj.value[i] !== undefined) { + value.putBuffer(asn1$8.toDer(obj.value[i])); + } + } + } else { + // use asn1.value directly + if(obj.type === asn1$8.Type.BMPSTRING) { + for(var i = 0; i < obj.value.length; ++i) { + value.putInt16(obj.value.charCodeAt(i)); + } + } else { + // ensure integer is minimally-encoded + // TODO: should all leading bytes be stripped vs just one? + // .. ex '00 00 01' => '01'? + if(obj.type === asn1$8.Type.INTEGER && + obj.value.length > 1 && + // leading 0x00 for positive integer + ((obj.value.charCodeAt(0) === 0 && + (obj.value.charCodeAt(1) & 0x80) === 0) || + // leading 0xFF for negative integer + (obj.value.charCodeAt(0) === 0xFF && + (obj.value.charCodeAt(1) & 0x80) === 0x80))) { + value.putBytes(obj.value.substr(1)); + } else { + value.putBytes(obj.value); + } + } + } + + // add tag byte + bytes.putByte(b1); + + // use "short form" encoding + if(value.length() <= 127) { + // one byte describes the length + // bit 8 = 0 and bits 7-1 = length + bytes.putByte(value.length() & 0x7F); + } else { + // use "long form" encoding + // 2 to 127 bytes describe the length + // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes + // other bytes: length in base 256, big-endian + var len = value.length(); + var lenBytes = ''; + do { + lenBytes += String.fromCharCode(len & 0xFF); + len = len >>> 8; + } while(len > 0); + + // set first byte to # bytes used to store the length and turn on + // bit 8 to indicate long-form length is used + bytes.putByte(lenBytes.length | 0x80); + + // concatenate length bytes in reverse since they were generated + // little endian and we need big endian + for(var i = lenBytes.length - 1; i >= 0; --i) { + bytes.putByte(lenBytes.charCodeAt(i)); + } + } + + // concatenate value bytes + bytes.putBuffer(value); + return bytes; +}; + +/** + * Converts an OID dot-separated string to a byte buffer. The byte buffer + * contains only the DER-encoded value, not any tag or length bytes. + * + * @param oid the OID dot-separated string. + * + * @return the byte buffer. + */ +asn1$8.oidToDer = function(oid) { + // split OID into individual values + var values = oid.split('.'); + var bytes = forge$z.util.createBuffer(); + + // first byte is 40 * value1 + value2 + bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); + // other bytes are each value in base 128 with 8th bit set except for + // the last byte for each value + var last, valueBytes, value, b; + for(var i = 2; i < values.length; ++i) { + // produce value bytes in reverse because we don't know how many + // bytes it will take to store the value + last = true; + valueBytes = []; + value = parseInt(values[i], 10); + do { + b = value & 0x7F; + value = value >>> 7; + // if value is not last, then turn on 8th bit + if(!last) { + b |= 0x80; + } + valueBytes.push(b); + last = false; + } while(value > 0); + + // add value bytes in reverse (needs to be in big endian) + for(var n = valueBytes.length - 1; n >= 0; --n) { + bytes.putByte(valueBytes[n]); + } + } + + return bytes; +}; + +/** + * Converts a DER-encoded byte buffer to an OID dot-separated string. The + * byte buffer should contain only the DER-encoded value, not any tag or + * length bytes. + * + * @param bytes the byte buffer. + * + * @return the OID dot-separated string. + */ +asn1$8.derToOid = function(bytes) { + var oid; + + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge$z.util.createBuffer(bytes); + } + + // first byte is 40 * value1 + value2 + var b = bytes.getByte(); + oid = Math.floor(b / 40) + '.' + (b % 40); + + // other bytes are each value in base 128 with 8th bit set except for + // the last byte for each value + var value = 0; + while(bytes.length() > 0) { + b = bytes.getByte(); + value = value << 7; + // not the last byte for the value + if(b & 0x80) { + value += b & 0x7F; + } else { + // last byte + oid += '.' + (value + b); + value = 0; + } + } + + return oid; +}; + +/** + * Converts a UTCTime value to a date. + * + * Note: GeneralizedTime has 4 digits for the year and is used for X.509 + * dates past 2049. Parsing that structure hasn't been implemented yet. + * + * @param utc the UTCTime value to convert. + * + * @return the date. + */ +asn1$8.utcTimeToDate = function(utc) { + /* The following formats can be used: + + YYMMDDhhmmZ + YYMMDDhhmm+hh'mm' + YYMMDDhhmm-hh'mm' + YYMMDDhhmmssZ + YYMMDDhhmmss+hh'mm' + YYMMDDhhmmss-hh'mm' + + Where: + + YY is the least significant two digits of the year + MM is the month (01 to 12) + DD is the day (01 to 31) + hh is the hour (00 to 23) + mm are the minutes (00 to 59) + ss are the seconds (00 to 59) + Z indicates that local time is GMT, + indicates that local time is + later than GMT, and - indicates that local time is earlier than GMT + hh' is the absolute value of the offset from GMT in hours + mm' is the absolute value of the offset from GMT in minutes */ + var date = new Date(); + + // if YY >= 50 use 19xx, if YY < 50 use 20xx + var year = parseInt(utc.substr(0, 2), 10); + year = (year >= 50) ? 1900 + year : 2000 + year; + var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month + var DD = parseInt(utc.substr(4, 2), 10); + var hh = parseInt(utc.substr(6, 2), 10); + var mm = parseInt(utc.substr(8, 2), 10); + var ss = 0; + + // not just YYMMDDhhmmZ + if(utc.length > 11) { + // get character after minutes + var c = utc.charAt(10); + var end = 10; + + // see if seconds are present + if(c !== '+' && c !== '-') { + // get seconds + ss = parseInt(utc.substr(10, 2), 10); + end += 2; + } + } + + // update date + date.setUTCFullYear(year, MM, DD); + date.setUTCHours(hh, mm, ss, 0); + + if(end) { + // get +/- after end of time + c = utc.charAt(end); + if(c === '+' || c === '-') { + // get hours+minutes offset + var hhoffset = parseInt(utc.substr(end + 1, 2), 10); + var mmoffset = parseInt(utc.substr(end + 4, 2), 10); + + // calculate offset in milliseconds + var offset = hhoffset * 60 + mmoffset; + offset *= 60000; + + // apply offset + if(c === '+') { + date.setTime(+date - offset); + } else { + date.setTime(+date + offset); + } + } + } + + return date; +}; + +/** + * Converts a GeneralizedTime value to a date. + * + * @param gentime the GeneralizedTime value to convert. + * + * @return the date. + */ +asn1$8.generalizedTimeToDate = function(gentime) { + /* The following formats can be used: + + YYYYMMDDHHMMSS + YYYYMMDDHHMMSS.fff + YYYYMMDDHHMMSSZ + YYYYMMDDHHMMSS.fffZ + YYYYMMDDHHMMSS+hh'mm' + YYYYMMDDHHMMSS.fff+hh'mm' + YYYYMMDDHHMMSS-hh'mm' + YYYYMMDDHHMMSS.fff-hh'mm' + + Where: + + YYYY is the year + MM is the month (01 to 12) + DD is the day (01 to 31) + hh is the hour (00 to 23) + mm are the minutes (00 to 59) + ss are the seconds (00 to 59) + .fff is the second fraction, accurate to three decimal places + Z indicates that local time is GMT, + indicates that local time is + later than GMT, and - indicates that local time is earlier than GMT + hh' is the absolute value of the offset from GMT in hours + mm' is the absolute value of the offset from GMT in minutes */ + var date = new Date(); + + var YYYY = parseInt(gentime.substr(0, 4), 10); + var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month + var DD = parseInt(gentime.substr(6, 2), 10); + var hh = parseInt(gentime.substr(8, 2), 10); + var mm = parseInt(gentime.substr(10, 2), 10); + var ss = parseInt(gentime.substr(12, 2), 10); + var fff = 0; + var offset = 0; + var isUTC = false; + + if(gentime.charAt(gentime.length - 1) === 'Z') { + isUTC = true; + } + + var end = gentime.length - 5, c = gentime.charAt(end); + if(c === '+' || c === '-') { + // get hours+minutes offset + var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); + var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); + + // calculate offset in milliseconds + offset = hhoffset * 60 + mmoffset; + offset *= 60000; + + // apply offset + if(c === '+') { + offset *= -1; + } + + isUTC = true; + } + + // check for second fraction + if(gentime.charAt(14) === '.') { + fff = parseFloat(gentime.substr(14), 10) * 1000; + } + + if(isUTC) { + date.setUTCFullYear(YYYY, MM, DD); + date.setUTCHours(hh, mm, ss, fff); + + // apply offset + date.setTime(+date + offset); + } else { + date.setFullYear(YYYY, MM, DD); + date.setHours(hh, mm, ss, fff); + } + + return date; +}; + +/** + * Converts a date to a UTCTime value. + * + * Note: GeneralizedTime has 4 digits for the year and is used for X.509 + * dates past 2049. Converting to a GeneralizedTime hasn't been + * implemented yet. + * + * @param date the date to convert. + * + * @return the UTCTime value. + */ +asn1$8.dateToUtcTime = function(date) { + // TODO: validate; currently assumes proper format + if(typeof date === 'string') { + return date; + } + + var rval = ''; + + // create format YYMMDDhhmmssZ + var format = []; + format.push(('' + date.getUTCFullYear()).substr(2)); + format.push('' + (date.getUTCMonth() + 1)); + format.push('' + date.getUTCDate()); + format.push('' + date.getUTCHours()); + format.push('' + date.getUTCMinutes()); + format.push('' + date.getUTCSeconds()); + + // ensure 2 digits are used for each format entry + for(var i = 0; i < format.length; ++i) { + if(format[i].length < 2) { + rval += '0'; + } + rval += format[i]; + } + rval += 'Z'; + + return rval; +}; + +/** + * Converts a date to a GeneralizedTime value. + * + * @param date the date to convert. + * + * @return the GeneralizedTime value as a string. + */ +asn1$8.dateToGeneralizedTime = function(date) { + // TODO: validate; currently assumes proper format + if(typeof date === 'string') { + return date; + } + + var rval = ''; + + // create format YYYYMMDDHHMMSSZ + var format = []; + format.push('' + date.getUTCFullYear()); + format.push('' + (date.getUTCMonth() + 1)); + format.push('' + date.getUTCDate()); + format.push('' + date.getUTCHours()); + format.push('' + date.getUTCMinutes()); + format.push('' + date.getUTCSeconds()); + + // ensure 2 digits are used for each format entry + for(var i = 0; i < format.length; ++i) { + if(format[i].length < 2) { + rval += '0'; + } + rval += format[i]; + } + rval += 'Z'; + + return rval; +}; + +/** + * Converts a javascript integer to a DER-encoded byte buffer to be used + * as the value for an INTEGER type. + * + * @param x the integer. + * + * @return the byte buffer. + */ +asn1$8.integerToDer = function(x) { + var rval = forge$z.util.createBuffer(); + if(x >= -0x80 && x < 0x80) { + return rval.putSignedInt(x, 8); + } + if(x >= -0x8000 && x < 0x8000) { + return rval.putSignedInt(x, 16); + } + if(x >= -0x800000 && x < 0x800000) { + return rval.putSignedInt(x, 24); + } + if(x >= -0x80000000 && x < 0x80000000) { + return rval.putSignedInt(x, 32); + } + var error = new Error('Integer too large; max is 32-bits.'); + error.integer = x; + throw error; +}; + +/** + * Converts a DER-encoded byte buffer to a javascript integer. This is + * typically used to decode the value of an INTEGER type. + * + * @param bytes the byte buffer. + * + * @return the integer. + */ +asn1$8.derToInteger = function(bytes) { + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge$z.util.createBuffer(bytes); + } + + var n = bytes.length() * 8; + if(n > 32) { + throw new Error('Integer too large; max is 32-bits.'); + } + return bytes.getSignedInt(n); +}; + +/** + * Validates that the given ASN.1 object is at least a super set of the + * given ASN.1 structure. Only tag classes and types are checked. An + * optional map may also be provided to capture ASN.1 values while the + * structure is checked. + * + * To capture an ASN.1 value, set an object in the validator's 'capture' + * parameter to the key to use in the capture map. To capture the full + * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including + * the leading unused bits counter byte, specify 'captureBitStringContents'. + * To capture BIT STRING bytes, without the leading unused bits counter byte, + * specify 'captureBitStringValue'. + * + * Objects in the validator may set a field 'optional' to true to indicate + * that it isn't necessary to pass validation. + * + * @param obj the ASN.1 object to validate. + * @param v the ASN.1 structure validator. + * @param capture an optional map to capture values in. + * @param errors an optional array for storing validation errors. + * + * @return true on success, false on failure. + */ +asn1$8.validate = function(obj, v, capture, errors) { + var rval = false; + + // ensure tag class and type are the same if specified + if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') && + (obj.type === v.type || typeof(v.type) === 'undefined')) { + // ensure constructed flag is the same if specified + if(obj.constructed === v.constructed || + typeof(v.constructed) === 'undefined') { + rval = true; + + // handle sub values + if(v.value && forge$z.util.isArray(v.value)) { + var j = 0; + for(var i = 0; rval && i < v.value.length; ++i) { + rval = v.value[i].optional || false; + if(obj.value[j]) { + rval = asn1$8.validate(obj.value[j], v.value[i], capture, errors); + if(rval) { + ++j; + } else if(v.value[i].optional) { + rval = true; + } + } + if(!rval && errors) { + errors.push( + '[' + v.name + '] ' + + 'Tag class "' + v.tagClass + '", type "' + + v.type + '" expected value length "' + + v.value.length + '", got "' + + obj.value.length + '"'); + } + } + } + + if(rval && capture) { + if(v.capture) { + capture[v.capture] = obj.value; + } + if(v.captureAsn1) { + capture[v.captureAsn1] = obj; + } + if(v.captureBitStringContents && 'bitStringContents' in obj) { + capture[v.captureBitStringContents] = obj.bitStringContents; + } + if(v.captureBitStringValue && 'bitStringContents' in obj) { + if(obj.bitStringContents.length < 2) { + capture[v.captureBitStringValue] = ''; + } else { + // FIXME: support unused bits with data shifting + var unused = obj.bitStringContents.charCodeAt(0); + if(unused !== 0) { + throw new Error( + 'captureBitStringValue only supported for zero unused bits'); + } + capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); + } + } + } + } else if(errors) { + errors.push( + '[' + v.name + '] ' + + 'Expected constructed "' + v.constructed + '", got "' + + obj.constructed + '"'); + } + } else if(errors) { + if(obj.tagClass !== v.tagClass) { + errors.push( + '[' + v.name + '] ' + + 'Expected tag class "' + v.tagClass + '", got "' + + obj.tagClass + '"'); + } + if(obj.type !== v.type) { + errors.push( + '[' + v.name + '] ' + + 'Expected type "' + v.type + '", got "' + obj.type + '"'); + } + } + return rval; +}; + +// regex for testing for non-latin characters +var _nonLatinRegex = /[^\\u0000-\\u00ff]/; + +/** + * Pretty prints an ASN.1 object to a string. + * + * @param obj the object to write out. + * @param level the level in the tree. + * @param indentation the indentation to use. + * + * @return the string. + */ +asn1$8.prettyPrint = function(obj, level, indentation) { + var rval = ''; + + // set default level and indentation + level = level || 0; + indentation = indentation || 2; + + // start new line for deep levels + if(level > 0) { + rval += '\n'; + } + + // create indent + var indent = ''; + for(var i = 0; i < level * indentation; ++i) { + indent += ' '; + } + + // print class:type + rval += indent + 'Tag: '; + switch(obj.tagClass) { + case asn1$8.Class.UNIVERSAL: + rval += 'Universal:'; + break; + case asn1$8.Class.APPLICATION: + rval += 'Application:'; + break; + case asn1$8.Class.CONTEXT_SPECIFIC: + rval += 'Context-Specific:'; + break; + case asn1$8.Class.PRIVATE: + rval += 'Private:'; + break; + } + + if(obj.tagClass === asn1$8.Class.UNIVERSAL) { + rval += obj.type; + + // known types + switch(obj.type) { + case asn1$8.Type.NONE: + rval += ' (None)'; + break; + case asn1$8.Type.BOOLEAN: + rval += ' (Boolean)'; + break; + case asn1$8.Type.INTEGER: + rval += ' (Integer)'; + break; + case asn1$8.Type.BITSTRING: + rval += ' (Bit string)'; + break; + case asn1$8.Type.OCTETSTRING: + rval += ' (Octet string)'; + break; + case asn1$8.Type.NULL: + rval += ' (Null)'; + break; + case asn1$8.Type.OID: + rval += ' (Object Identifier)'; + break; + case asn1$8.Type.ODESC: + rval += ' (Object Descriptor)'; + break; + case asn1$8.Type.EXTERNAL: + rval += ' (External or Instance of)'; + break; + case asn1$8.Type.REAL: + rval += ' (Real)'; + break; + case asn1$8.Type.ENUMERATED: + rval += ' (Enumerated)'; + break; + case asn1$8.Type.EMBEDDED: + rval += ' (Embedded PDV)'; + break; + case asn1$8.Type.UTF8: + rval += ' (UTF8)'; + break; + case asn1$8.Type.ROID: + rval += ' (Relative Object Identifier)'; + break; + case asn1$8.Type.SEQUENCE: + rval += ' (Sequence)'; + break; + case asn1$8.Type.SET: + rval += ' (Set)'; + break; + case asn1$8.Type.PRINTABLESTRING: + rval += ' (Printable String)'; + break; + case asn1$8.Type.IA5String: + rval += ' (IA5String (ASCII))'; + break; + case asn1$8.Type.UTCTIME: + rval += ' (UTC time)'; + break; + case asn1$8.Type.GENERALIZEDTIME: + rval += ' (Generalized time)'; + break; + case asn1$8.Type.BMPSTRING: + rval += ' (BMP String)'; + break; + } + } else { + rval += obj.type; + } + + rval += '\n'; + rval += indent + 'Constructed: ' + obj.constructed + '\n'; + + if(obj.composed) { + var subvalues = 0; + var sub = ''; + for(var i = 0; i < obj.value.length; ++i) { + if(obj.value[i] !== undefined) { + subvalues += 1; + sub += asn1$8.prettyPrint(obj.value[i], level + 1, indentation); + if((i + 1) < obj.value.length) { + sub += ','; + } + } + } + rval += indent + 'Sub values: ' + subvalues + sub; + } else { + rval += indent + 'Value: '; + if(obj.type === asn1$8.Type.OID) { + var oid = asn1$8.derToOid(obj.value); + rval += oid; + if(forge$z.pki && forge$z.pki.oids) { + if(oid in forge$z.pki.oids) { + rval += ' (' + forge$z.pki.oids[oid] + ') '; + } + } + } + if(obj.type === asn1$8.Type.INTEGER) { + try { + rval += asn1$8.derToInteger(obj.value); + } catch(ex) { + rval += '0x' + forge$z.util.bytesToHex(obj.value); + } + } else if(obj.type === asn1$8.Type.BITSTRING) { + // TODO: shift bits as needed to display without padding + if(obj.value.length > 1) { + // remove unused bits field + rval += '0x' + forge$z.util.bytesToHex(obj.value.slice(1)); + } else { + rval += '(none)'; + } + // show unused bit count + if(obj.value.length > 0) { + var unused = obj.value.charCodeAt(0); + if(unused == 1) { + rval += ' (1 unused bit shown)'; + } else if(unused > 1) { + rval += ' (' + unused + ' unused bits shown)'; + } + } + } else if(obj.type === asn1$8.Type.OCTETSTRING) { + if(!_nonLatinRegex.test(obj.value)) { + rval += '(' + obj.value + ') '; + } + rval += '0x' + forge$z.util.bytesToHex(obj.value); + } else if(obj.type === asn1$8.Type.UTF8) { + rval += forge$z.util.decodeUtf8(obj.value); + } else if(obj.type === asn1$8.Type.PRINTABLESTRING || + obj.type === asn1$8.Type.IA5String) { + rval += obj.value; + } else if(_nonLatinRegex.test(obj.value)) { + rval += '0x' + forge$z.util.bytesToHex(obj.value); + } else if(obj.value.length === 0) { + rval += '[null]'; + } else { + rval += obj.value; + } + } + + return rval; +}; + +/** + * Node.js module for Forge message digests. + * + * @author Dave Longley + * + * Copyright 2011-2017 Digital Bazaar, Inc. + */ + +var forge$y = forge$F; + +forge$y.md = forge$y.md || {}; +forge$y.md.algorithms = forge$y.md.algorithms || {}; + +/** + * Hash-based Message Authentication Code implementation. Requires a message + * digest object that can be obtained, for example, from forge.md.sha1 or + * forge.md.md5. + * + * @author Dave Longley + * + * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved. + */ + +var forge$x = forge$F; + + + +/* HMAC API */ +var hmac = forge$x.hmac = forge$x.hmac || {}; + +/** + * Creates an HMAC object that uses the given message digest object. + * + * @return an HMAC object. + */ +hmac.create = function() { + // the hmac key to use + var _key = null; + + // the message digest to use + var _md = null; + + // the inner padding + var _ipadding = null; + + // the outer padding + var _opadding = null; + + // hmac context + var ctx = {}; + + /** + * Starts or restarts the HMAC with the given key and message digest. + * + * @param md the message digest to use, null to reuse the previous one, + * a string to use builtin 'sha1', 'md5', 'sha256'. + * @param key the key to use as a string, array of bytes, byte buffer, + * or null to reuse the previous key. + */ + ctx.start = function(md, key) { + if(md !== null) { + if(typeof md === 'string') { + // create builtin message digest + md = md.toLowerCase(); + if(md in forge$x.md.algorithms) { + _md = forge$x.md.algorithms[md].create(); + } else { + throw new Error('Unknown hash algorithm "' + md + '"'); + } + } else { + // store message digest + _md = md; + } + } + + if(key === null) { + // reuse previous key + key = _key; + } else { + if(typeof key === 'string') { + // convert string into byte buffer + key = forge$x.util.createBuffer(key); + } else if(forge$x.util.isArray(key)) { + // convert byte array into byte buffer + var tmp = key; + key = forge$x.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + + // if key is longer than blocksize, hash it + var keylen = key.length(); + if(keylen > _md.blockLength) { + _md.start(); + _md.update(key.bytes()); + key = _md.digest(); + } + + // mix key into inner and outer padding + // ipadding = [0x36 * blocksize] ^ key + // opadding = [0x5C * blocksize] ^ key + _ipadding = forge$x.util.createBuffer(); + _opadding = forge$x.util.createBuffer(); + keylen = key.length(); + for(var i = 0; i < keylen; ++i) { + var tmp = key.at(i); + _ipadding.putByte(0x36 ^ tmp); + _opadding.putByte(0x5C ^ tmp); + } + + // if key is shorter than blocksize, add additional padding + if(keylen < _md.blockLength) { + var tmp = _md.blockLength - keylen; + for(var i = 0; i < tmp; ++i) { + _ipadding.putByte(0x36); + _opadding.putByte(0x5C); + } + } + _key = key; + _ipadding = _ipadding.bytes(); + _opadding = _opadding.bytes(); + } + + // digest is done like so: hash(opadding | hash(ipadding | message)) + + // prepare to do inner hash + // hash(ipadding | message) + _md.start(); + _md.update(_ipadding); + }; + + /** + * Updates the HMAC with the given message bytes. + * + * @param bytes the bytes to update with. + */ + ctx.update = function(bytes) { + _md.update(bytes); + }; + + /** + * Produces the Message Authentication Code (MAC). + * + * @return a byte buffer containing the digest value. + */ + ctx.getMac = function() { + // digest is done like so: hash(opadding | hash(ipadding | message)) + // here we do the outer hashing + var inner = _md.digest().bytes(); + _md.start(); + _md.update(_opadding); + _md.update(inner); + return _md.digest(); + }; + // alias for getMac + ctx.digest = ctx.getMac; + + return ctx; +}; + +/** + * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ + +var forge$w = forge$F; + + + +var md5 = forge$w.md5 = forge$w.md5 || {}; +forge$w.md.md5 = forge$w.md.algorithms.md5 = md5; + +/** + * Creates an MD5 message digest object. + * + * @return a message digest object. + */ +md5.create = function() { + // do initialization as necessary + if(!_initialized$3) { + _init$3(); + } + + // MD5 state contains four 32-bit integers + var _state = null; + + // input buffer + var _input = forge$w.util.createBuffer(); + + // used for word storage + var _w = new Array(16); + + // message digest object + var md = { + algorithm: 'md5', + blockLength: 64, + digestLength: 16, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge$w.util.createBuffer(); + _state = { + h0: 0x67452301, + h1: 0xEFCDAB89, + h2: 0x98BADCFE, + h3: 0x10325476 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge$w.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = (len[1] / 0x100000000) >>> 0; + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update$3(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate MD5 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge$w.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding$3.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in little-endian order; since length + // is stored in bytes we multiply by 8 and add carry + var bits, carry = 0; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + bits = md.fullMessageLength[i] * 8 + carry; + carry = (bits / 0x100000000) >>> 0; + finalBlock.putInt32Le(bits >>> 0); + } + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3 + }; + _update$3(s2, _w, finalBlock); + var rval = forge$w.util.createBuffer(); + rval.putInt32Le(s2.h0); + rval.putInt32Le(s2.h1); + rval.putInt32Le(s2.h2); + rval.putInt32Le(s2.h3); + return rval; + }; + + return md; +}; + +// padding, constant tables for calculating md5 +var _padding$3 = null; +var _g = null; +var _r = null; +var _k$2 = null; +var _initialized$3 = false; + +/** + * Initializes the constant tables. + */ +function _init$3() { + // create padding + _padding$3 = String.fromCharCode(128); + _padding$3 += forge$w.util.fillString(String.fromCharCode(0x00), 64); + + // g values + _g = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, + 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, + 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9]; + + // rounds table + _r = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]; + + // get the result of abs(sin(i + 1)) as a 32-bit integer + _k$2 = new Array(64); + for(var i = 0; i < 64; ++i) { + _k$2[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000); + } + + // now initialized + _initialized$3 = true; +} + +/** + * Updates an MD5 state with the given byte buffer. + * + * @param s the MD5 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update$3(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t, a, b, c, d, f, r, i; + var len = bytes.length(); + while(len >= 64) { + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + + // round 1 + for(i = 0; i < 16; ++i) { + w[i] = bytes.getInt32Le(); + f = d ^ (b & (c ^ d)); + t = (a + f + _k$2[i] + w[i]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 2 + for(; i < 32; ++i) { + f = c ^ (d & (b ^ c)); + t = (a + f + _k$2[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 3 + for(; i < 48; ++i) { + f = b ^ c ^ d; + t = (a + f + _k$2[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 4 + for(; i < 64; ++i) { + f = c ^ (b | ~d); + t = (a + f + _k$2[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + + len -= 64; + } +} + +/** + * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms. + * + * See: RFC 1421. + * + * @author Dave Longley + * + * Copyright (c) 2013-2014 Digital Bazaar, Inc. + * + * A Forge PEM object has the following fields: + * + * type: identifies the type of message (eg: "RSA PRIVATE KEY"). + * + * procType: identifies the type of processing performed on the message, + * it has two subfields: version and type, eg: 4,ENCRYPTED. + * + * contentDomain: identifies the type of content in the message, typically + * only uses the value: "RFC822". + * + * dekInfo: identifies the message encryption algorithm and mode and includes + * any parameters for the algorithm, it has two subfields: algorithm and + * parameters, eg: DES-CBC,F8143EDE5960C597. + * + * headers: contains all other PEM encapsulated headers -- where order is + * significant (for pairing data like recipient ID + key info). + * + * body: the binary-encoded body. + */ + +var forge$v = forge$F; + + +// shortcut for pem API +var pem = forge$v.pem = forge$v.pem || {}; + +/** + * Encodes (serializes) the given PEM object. + * + * @param msg the PEM message object to encode. + * @param options the options to use: + * maxline the maximum characters per line for the body, (default: 64). + * + * @return the PEM-formatted string. + */ +pem.encode = function(msg, options) { + options = options || {}; + var rval = '-----BEGIN ' + msg.type + '-----\r\n'; + + // encode special headers + var header; + if(msg.procType) { + header = { + name: 'Proc-Type', + values: [String(msg.procType.version), msg.procType.type] + }; + rval += foldHeader(header); + } + if(msg.contentDomain) { + header = {name: 'Content-Domain', values: [msg.contentDomain]}; + rval += foldHeader(header); + } + if(msg.dekInfo) { + header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]}; + if(msg.dekInfo.parameters) { + header.values.push(msg.dekInfo.parameters); + } + rval += foldHeader(header); + } + + if(msg.headers) { + // encode all other headers + for(var i = 0; i < msg.headers.length; ++i) { + rval += foldHeader(msg.headers[i]); + } + } + + // terminate header + if(msg.procType) { + rval += '\r\n'; + } + + // add body + rval += forge$v.util.encode64(msg.body, options.maxline || 64) + '\r\n'; + + rval += '-----END ' + msg.type + '-----\r\n'; + return rval; +}; + +/** + * Decodes (deserializes) all PEM messages found in the given string. + * + * @param str the PEM-formatted string to decode. + * + * @return the PEM message objects in an array. + */ +pem.decode = function(str) { + var rval = []; + + // split string into PEM messages (be lenient w/EOF on BEGIN line) + var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; + var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; + var rCRLF = /\r?\n/; + var match; + while(true) { + match = rMessage.exec(str); + if(!match) { + break; + } + + var msg = { + type: match[1], + procType: null, + contentDomain: null, + dekInfo: null, + headers: [], + body: forge$v.util.decode64(match[3]) + }; + rval.push(msg); + + // no headers + if(!match[2]) { + continue; + } + + // parse headers + var lines = match[2].split(rCRLF); + var li = 0; + while(match && li < lines.length) { + // get line, trim any rhs whitespace + var line = lines[li].replace(/\s+$/, ''); + + // RFC2822 unfold any following folded lines + for(var nl = li + 1; nl < lines.length; ++nl) { + var next = lines[nl]; + if(!/\s/.test(next[0])) { + break; + } + line += next; + li = nl; + } + + // parse header + match = line.match(rHeader); + if(match) { + var header = {name: match[1], values: []}; + var values = match[2].split(','); + for(var vi = 0; vi < values.length; ++vi) { + header.values.push(ltrim(values[vi])); + } + + // Proc-Type must be the first header + if(!msg.procType) { + if(header.name !== 'Proc-Type') { + throw new Error('Invalid PEM formatted message. The first ' + + 'encapsulated header must be "Proc-Type".'); + } else if(header.values.length !== 2) { + throw new Error('Invalid PEM formatted message. The "Proc-Type" ' + + 'header must have two subfields.'); + } + msg.procType = {version: values[0], type: values[1]}; + } else if(!msg.contentDomain && header.name === 'Content-Domain') { + // special-case Content-Domain + msg.contentDomain = values[0] || ''; + } else if(!msg.dekInfo && header.name === 'DEK-Info') { + // special-case DEK-Info + if(header.values.length === 0) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + + 'header must have at least one subfield.'); + } + msg.dekInfo = {algorithm: values[0], parameters: values[1] || null}; + } else { + msg.headers.push(header); + } + } + + ++li; + } + + if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + + 'header must be present if "Proc-Type" is "ENCRYPTED".'); + } + } + + if(rval.length === 0) { + throw new Error('Invalid PEM formatted message.'); + } + + return rval; +}; + +function foldHeader(header) { + var rval = header.name + ': '; + + // ensure values with CRLF are folded + var values = []; + var insertSpace = function(match, $1) { + return ' ' + $1; + }; + for(var i = 0; i < header.values.length; ++i) { + values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); + } + rval += values.join(',') + '\r\n'; + + // do folding + var length = 0; + var candidate = -1; + for(var i = 0; i < rval.length; ++i, ++length) { + if(length > 65 && candidate !== -1) { + var insert = rval[candidate]; + if(insert === ',') { + ++candidate; + rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate); + } else { + rval = rval.substr(0, candidate) + + '\r\n' + insert + rval.substr(candidate + 1); + } + length = (i - candidate - 1); + candidate = -1; + ++i; + } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') { + candidate = i; + } + } + + return rval; +} + +function ltrim(str) { + return str.replace(/^\s+/, ''); +} + +/** + * DES (Data Encryption Standard) implementation. + * + * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode. + * It is based on the BSD-licensed implementation by Paul Tero: + * + * Paul Tero, July 2001 + * http://www.tero.co.uk/des/ + * + * Optimised for performance with large blocks by + * Michael Hayworth, November 2001 + * http://www.netdealing.com + * + * THIS SOFTWARE IS PROVIDED "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2012-2014 Digital Bazaar, Inc. + */ + +var forge$u = forge$F; + + + + +/* DES API */ +forge$u.des = forge$u.des || {}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('DES-', key); + * cipher.start({iv: iv}); + * + * Creates an DES cipher object to encrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as binary-encoded strings of bytes or + * byte buffers. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC' if IV is + * given, 'ECB' if null). + * + * @return the cipher. + */ +forge$u.des.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: false, + mode: mode || (iv === null ? 'ECB' : 'CBC') + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('DES-', key); + * + * Creates an DES cipher object to encrypt data using the given symmetric key. + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge$u.des.createEncryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: false, + mode: mode + }); +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('DES-', key); + * decipher.start({iv: iv}); + * + * Creates an DES cipher object to decrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as binary-encoded strings of bytes or + * byte buffers. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC' if IV is + * given, 'ECB' if null). + * + * @return the cipher. + */ +forge$u.des.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: true, + mode: mode || (iv === null ? 'ECB' : 'CBC') + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('DES-', key); + * + * Creates an DES cipher object to decrypt data using the given symmetric key. + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge$u.des.createDecryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: true, + mode: mode + }); +}; + +/** + * Creates a new DES cipher algorithm object. + * + * @param name the name of the algorithm. + * @param mode the mode factory function. + * + * @return the DES algorithm object. + */ +forge$u.des.Algorithm = function(name, mode) { + var self = this; + self.name = name; + self.mode = new mode({ + blockSize: 8, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock(self._keys, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock(self._keys, inBlock, outBlock, true); + } + } + }); + self._init = false; +}; + +/** + * Initializes this DES algorithm by expanding its key. + * + * @param options the options to use. + * key the key to use with this algorithm. + * decrypt true if the algorithm should be initialized for decryption, + * false for encryption. + */ +forge$u.des.Algorithm.prototype.initialize = function(options) { + if(this._init) { + return; + } + + var key = forge$u.util.createBuffer(options.key); + if(this.name.indexOf('3DES') === 0) { + if(key.length() !== 24) { + throw new Error('Invalid Triple-DES key size: ' + key.length() * 8); + } + } + + // do key expansion to 16 or 48 subkeys (single or triple DES) + this._keys = _createKeys(key); + this._init = true; +}; + +/** Register DES algorithms **/ + +registerAlgorithm('DES-ECB', forge$u.cipher.modes.ecb); +registerAlgorithm('DES-CBC', forge$u.cipher.modes.cbc); +registerAlgorithm('DES-CFB', forge$u.cipher.modes.cfb); +registerAlgorithm('DES-OFB', forge$u.cipher.modes.ofb); +registerAlgorithm('DES-CTR', forge$u.cipher.modes.ctr); + +registerAlgorithm('3DES-ECB', forge$u.cipher.modes.ecb); +registerAlgorithm('3DES-CBC', forge$u.cipher.modes.cbc); +registerAlgorithm('3DES-CFB', forge$u.cipher.modes.cfb); +registerAlgorithm('3DES-OFB', forge$u.cipher.modes.ofb); +registerAlgorithm('3DES-CTR', forge$u.cipher.modes.ctr); + +function registerAlgorithm(name, mode) { + var factory = function() { + return new forge$u.des.Algorithm(name, mode); + }; + forge$u.cipher.registerAlgorithm(name, factory); +} + +/** DES implementation **/ + +var spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004]; +var spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000]; +var spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200]; +var spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080]; +var spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100]; +var spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010]; +var spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002]; +var spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000]; + +/** + * Create necessary sub keys. + * + * @param key the 64-bit or 192-bit key. + * + * @return the expanded keys. + */ +function _createKeys(key) { + var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204], + pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101], + pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808], + pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000], + pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010], + pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420], + pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002], + pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800], + pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002], + pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408], + pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020], + pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200], + pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010], + pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105]; + + // how many iterations (1 for des, 3 for triple des) + // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys + var iterations = key.length() > 8 ? 3 : 1; + + // stores the return keys + var keys = []; + + // now define the left shifts which need to be done + var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + + var n = 0, tmp; + for(var j = 0; j < iterations; j++) { + var left = key.getInt32(); + var right = key.getInt32(); + + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + tmp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= tmp; + right ^= (tmp << -16); + + tmp = ((left >>> 2) ^ right) & 0x33333333; + right ^= tmp; + left ^= (tmp << 2); + + tmp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= tmp; + right ^= (tmp << -16); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + // right needs to be shifted and OR'd with last four bits of left + tmp = (left << 8) | ((right >>> 20) & 0x000000f0); + + // left needs to be put upside down + left = ((right << 24) | ((right << 8) & 0xff0000) | + ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0)); + right = tmp; + + // now go through and perform these shifts on the left and right keys + for(var i = 0; i < shifts.length; ++i) { + //shift the keys either one or two bits to the left + if(shifts[i]) { + left = (left << 2) | (left >>> 26); + right = (right << 2) | (right >>> 26); + } else { + left = (left << 1) | (left >>> 27); + right = (right << 1) | (right >>> 27); + } + left &= -0xf; + right &= -0xf; + + // now apply PC-2, in such a way that E is easier when encrypting or + // decrypting this conversion will look like PC-2 except only the last 6 + // bits of each byte are used rather than 48 consecutive bits and the + // order of lines will be according to how the S selection functions will + // be applied: S2, S4, S6, S8, S1, S3, S5, S7 + var lefttmp = ( + pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | + pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] | + pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | + pc2bytes6[(left >>> 4) & 0xf]); + var righttmp = ( + pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | + pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] | + pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | + pc2bytes13[(right >>> 4) & 0xf]); + tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff; + keys[n++] = lefttmp ^ tmp; + keys[n++] = righttmp ^ (tmp << 16); + } + } + + return keys; +} + +/** + * Updates a single block (1 byte) using DES. The update will either + * encrypt or decrypt the block. + * + * @param keys the expanded keys. + * @param input the input block (an array of 32-bit words). + * @param output the updated output block. + * @param decrypt true to decrypt the block, false to encrypt it. + */ +function _updateBlock(keys, input, output, decrypt) { + // set up loops for single or triple DES + var iterations = keys.length === 32 ? 3 : 9; + var looping; + if(iterations === 3) { + looping = decrypt ? [30, -2, -2] : [0, 32, 2]; + } else { + looping = (decrypt ? + [94, 62, -2, 32, 64, 2, 30, -2, -2] : + [0, 32, 2, 62, 30, -2, 64, 96, 2]); + } + + var tmp; + + var left = input[0]; + var right = input[1]; + + // first each 64 bit chunk of the message must be permuted according to IP + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + tmp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= tmp; + left ^= (tmp << 16); + + tmp = ((right >>> 2) ^ left) & 0x33333333; + left ^= tmp; + right ^= (tmp << 2); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + // rotate left 1 bit + left = ((left << 1) | (left >>> 31)); + right = ((right << 1) | (right >>> 31)); + + for(var j = 0; j < iterations; j += 3) { + var endloop = looping[j + 1]; + var loopinc = looping[j + 2]; + + // now go through and perform the encryption or decryption + for(var i = looping[j]; i != endloop; i += loopinc) { + var right1 = right ^ keys[i]; + var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; + + // passing these bytes through the S selection functions + tmp = left; + left = right; + right = tmp ^ ( + spfunction2[(right1 >>> 24) & 0x3f] | + spfunction4[(right1 >>> 16) & 0x3f] | + spfunction6[(right1 >>> 8) & 0x3f] | + spfunction8[right1 & 0x3f] | + spfunction1[(right2 >>> 24) & 0x3f] | + spfunction3[(right2 >>> 16) & 0x3f] | + spfunction5[(right2 >>> 8) & 0x3f] | + spfunction7[right2 & 0x3f]); + } + // unreverse left and right + tmp = left; + left = right; + right = tmp; + } + + // rotate right 1 bit + left = ((left >>> 1) | (left << 31)); + right = ((right >>> 1) | (right << 31)); + + // now perform IP-1, which is IP in the opposite direction + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((right >>> 2) ^ left) & 0x33333333; + left ^= tmp; + right ^= (tmp << 2); + + tmp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= tmp; + left ^= (tmp << 16); + + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + output[0] = left; + output[1] = right; +} + +/** + * Deprecated. Instead, use: + * + * forge.cipher.createCipher('DES-', key); + * forge.cipher.createDecipher('DES-', key); + * + * Creates a deprecated DES cipher object. This object's mode will default to + * CBC (cipher-block-chaining). + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param options the options to use. + * key the symmetric key to use (64 or 192 bits). + * output the buffer to write to. + * decrypt true for decryption, false for encryption. + * mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +function _createCipher(options) { + options = options || {}; + var mode = (options.mode || 'CBC').toUpperCase(); + var algorithm = 'DES-' + mode; + + var cipher; + if(options.decrypt) { + cipher = forge$u.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge$u.cipher.createCipher(algorithm, options.key); + } + + // backwards compatible start API + var start = cipher.start; + cipher.start = function(iv, options) { + // backwards compatibility: support second arg as output buffer + var output = null; + if(options instanceof forge$u.util.ByteBuffer) { + output = options; + options = {}; + } + options = options || {}; + options.output = output; + options.iv = iv; + start.call(cipher, options); + }; + + return cipher; +} + +/** + * Password-Based Key-Derivation Function #2 implementation. + * + * See RFC 2898 for details. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ + +var forge$t = forge$F; + + + + +var pkcs5 = forge$t.pkcs5 = forge$t.pkcs5 || {}; + +var crypto; +if(forge$t.util.isNodejs && !forge$t.options.usePureJavaScript) { + crypto = require$$1__default; +} + +/** + * Derives a key from a password. + * + * @param p the password as a binary-encoded string of bytes. + * @param s the salt as a binary-encoded string of bytes. + * @param c the iteration count, a positive integer. + * @param dkLen the intended length, in bytes, of the derived key, + * (max: 2^32 - 1) * hash length of the PRF. + * @param [md] the message digest (or algorithm identifier as a string) to use + * in the PRF, defaults to SHA-1. + * @param [callback(err, key)] presence triggers asynchronous version, called + * once the operation completes. + * + * @return the derived key, as a binary-encoded string of bytes, for the + * synchronous version (if no callback is specified). + */ +forge$t.pbkdf2 = pkcs5.pbkdf2 = function( + p, s, c, dkLen, md, callback) { + if(typeof md === 'function') { + callback = md; + md = null; + } + + // use native implementation if possible and not disabled, note that + // some node versions only support SHA-1, others allow digest to be changed + if(forge$t.util.isNodejs && !forge$t.options.usePureJavaScript && + crypto.pbkdf2 && (md === null || typeof md !== 'object') && + (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) { + if(typeof md !== 'string') { + // default prf to SHA-1 + md = 'sha1'; + } + p = Buffer.from(p, 'binary'); + s = Buffer.from(s, 'binary'); + if(!callback) { + if(crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary'); + } + return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary'); + } + if(crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2(p, s, c, dkLen, function(err, key) { + if(err) { + return callback(err); + } + callback(null, key.toString('binary')); + }); + } + return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) { + if(err) { + return callback(err); + } + callback(null, key.toString('binary')); + }); + } + + if(typeof md === 'undefined' || md === null) { + // default prf to SHA-1 + md = 'sha1'; + } + if(typeof md === 'string') { + if(!(md in forge$t.md.algorithms)) { + throw new Error('Unknown hash algorithm: ' + md); + } + md = forge$t.md[md].create(); + } + + var hLen = md.digestLength; + + /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and + stop. */ + if(dkLen > (0xFFFFFFFF * hLen)) { + var err = new Error('Derived key is too long.'); + if(callback) { + return callback(err); + } + throw err; + } + + /* 2. Let len be the number of hLen-octet blocks in the derived key, + rounding up, and let r be the number of octets in the last + block: + + len = CEIL(dkLen / hLen), + r = dkLen - (len - 1) * hLen. */ + var len = Math.ceil(dkLen / hLen); + var r = dkLen - (len - 1) * hLen; + + /* 3. For each block of the derived key apply the function F defined + below to the password P, the salt S, the iteration count c, and + the block index to compute the block: + + T_1 = F(P, S, c, 1), + T_2 = F(P, S, c, 2), + ... + T_len = F(P, S, c, len), + + where the function F is defined as the exclusive-or sum of the + first c iterates of the underlying pseudorandom function PRF + applied to the password P and the concatenation of the salt S + and the block index i: + + F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c + + where + + u_1 = PRF(P, S || INT(i)), + u_2 = PRF(P, u_1), + ... + u_c = PRF(P, u_{c-1}). + + Here, INT(i) is a four-octet encoding of the integer i, most + significant octet first. */ + var prf = forge$t.hmac.create(); + prf.start(md, p); + var dk = ''; + var xor, u_c, u_c1; + + // sync version + if(!callback) { + for(var i = 1; i <= len; ++i) { + // PRF(P, S || INT(i)) (first iteration) + prf.start(null, null); + prf.update(s); + prf.update(forge$t.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + + // PRF(P, u_{c-1}) (other iterations) + for(var j = 2; j <= c; ++j) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + // F(p, s, c, i) + xor = forge$t.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + } + + /* 4. Concatenate the blocks and extract the first dkLen octets to + produce a derived key DK: + + DK = T_1 || T_2 || ... || T_len<0..r-1> */ + dk += (i < len) ? xor : xor.substr(0, r); + } + /* 5. Output the derived key DK. */ + return dk; + } + + // async version + var i = 1, j; + function outer() { + if(i > len) { + // done + return callback(null, dk); + } + + // PRF(P, S || INT(i)) (first iteration) + prf.start(null, null); + prf.update(s); + prf.update(forge$t.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + + // PRF(P, u_{c-1}) (other iterations) + j = 2; + inner(); + } + + function inner() { + if(j <= c) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + // F(p, s, c, i) + xor = forge$t.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + ++j; + return forge$t.util.setImmediate(inner); + } + + /* 4. Concatenate the blocks and extract the first dkLen octets to + produce a derived key DK: + + DK = T_1 || T_2 || ... || T_len<0..r-1> */ + dk += (i < len) ? xor : xor.substr(0, r); + + ++i; + outer(); + } + + outer(); +}; + +/** + * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. + * + * See FIPS 180-2 for details. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + */ + +var forge$s = forge$F; + + + +var sha256 = forge$s.sha256 = forge$s.sha256 || {}; +forge$s.md.sha256 = forge$s.md.algorithms.sha256 = sha256; + +/** + * Creates a SHA-256 message digest object. + * + * @return a message digest object. + */ +sha256.create = function() { + // do initialization as necessary + if(!_initialized$2) { + _init$2(); + } + + // SHA-256 state contains eight 32-bit integers + var _state = null; + + // input buffer + var _input = forge$s.util.createBuffer(); + + // used for word storage + var _w = new Array(64); + + // message digest object + var md = { + algorithm: 'sha256', + blockLength: 64, + digestLength: 32, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge$s.util.createBuffer(); + _state = { + h0: 0x6A09E667, + h1: 0xBB67AE85, + h2: 0x3C6EF372, + h3: 0xA54FF53A, + h4: 0x510E527F, + h5: 0x9B05688C, + h6: 0x1F83D9AB, + h7: 0x5BE0CD19 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge$s.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update$2(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-256 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge$s.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding$2.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4, + h5: _state.h5, + h6: _state.h6, + h7: _state.h7 + }; + _update$2(s2, _w, finalBlock); + var rval = forge$s.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + rval.putInt32(s2.h5); + rval.putInt32(s2.h6); + rval.putInt32(s2.h7); + return rval; + }; + + return md; +}; + +// sha-256 padding bytes not initialized yet +var _padding$2 = null; +var _initialized$2 = false; + +// table of constants +var _k$1 = null; + +/** + * Initializes the constant tables. + */ +function _init$2() { + // create padding + _padding$2 = String.fromCharCode(128); + _padding$2 += forge$s.util.fillString(String.fromCharCode(0x00), 64); + + // create K table for SHA-256 + _k$1 = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; + + // now initialized + _initialized$2 = true; +} + +/** + * Updates a SHA-256 state with the given byte buffer. + * + * @param s the SHA-256 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update$2(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; + var len = bytes.length(); + while(len >= 64) { + // the w array will be populated with sixteen 32-bit big-endian words + // and then extended into 64 32-bit words according to SHA-256 + for(i = 0; i < 16; ++i) { + w[i] = bytes.getInt32(); + } + for(; i < 64; ++i) { + // XOR word 2 words ago rot right 17, rot right 19, shft right 10 + t1 = w[i - 2]; + t1 = + ((t1 >>> 17) | (t1 << 15)) ^ + ((t1 >>> 19) | (t1 << 13)) ^ + (t1 >>> 10); + // XOR word 15 words ago rot right 7, rot right 18, shft right 3 + t2 = w[i - 15]; + t2 = + ((t2 >>> 7) | (t2 << 25)) ^ + ((t2 >>> 18) | (t2 << 14)) ^ + (t2 >>> 3); + // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32 + w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0; + } + + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + f = s.h5; + g = s.h6; + h = s.h7; + + // round function + for(i = 0; i < 64; ++i) { + // Sum1(e) + s1 = + ((e >>> 6) | (e << 26)) ^ + ((e >>> 11) | (e << 21)) ^ + ((e >>> 25) | (e << 7)); + // Ch(e, f, g) (optimized the same way as SHA-1) + ch = g ^ (e & (f ^ g)); + // Sum0(a) + s0 = + ((a >>> 2) | (a << 30)) ^ + ((a >>> 13) | (a << 19)) ^ + ((a >>> 22) | (a << 10)); + // Maj(a, b, c) (optimized the same way as SHA-1) + maj = (a & b) | (c & (a ^ b)); + + // main algorithm + t1 = h + s1 + ch + _k$1[i] + w[i]; + t2 = s0 + maj; + h = g; + g = f; + f = e; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + // can't truncate with `| 0` + e = (d + t1) >>> 0; + d = c; + c = b; + b = a; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + // can't truncate with `| 0` + a = (t1 + t2) >>> 0; + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + s.h5 = (s.h5 + f) | 0; + s.h6 = (s.h6 + g) | 0; + s.h7 = (s.h7 + h) | 0; + len -= 64; + } +} + +/** + * A javascript implementation of a cryptographically-secure + * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed + * here though the use of SHA-256 is not enforced; when generating an + * a PRNG context, the hashing algorithm and block cipher used for + * the generator are specified via a plugin. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ + +var forge$r = forge$F; + + +var _crypto$1 = null; +if(forge$r.util.isNodejs && !forge$r.options.usePureJavaScript && + !process.versions['node-webkit']) { + _crypto$1 = require$$1__default; +} + +/* PRNG API */ +var prng = forge$r.prng = forge$r.prng || {}; + +/** + * Creates a new PRNG context. + * + * A PRNG plugin must be passed in that will provide: + * + * 1. A function that initializes the key and seed of a PRNG context. It + * will be given a 16 byte key and a 16 byte seed. Any key expansion + * or transformation of the seed from a byte string into an array of + * integers (or similar) should be performed. + * 2. The cryptographic function used by the generator. It takes a key and + * a seed. + * 3. A seed increment function. It takes the seed and returns seed + 1. + * 4. An api to create a message digest. + * + * For an example, see random.js. + * + * @param plugin the PRNG plugin to use. + */ +prng.create = function(plugin) { + var ctx = { + plugin: plugin, + key: null, + seed: null, + time: null, + // number of reseeds so far + reseeds: 0, + // amount of data generated so far + generated: 0, + // no initial key bytes + keyBytes: '' + }; + + // create 32 entropy pools (each is a message digest) + var md = plugin.md; + var pools = new Array(32); + for(var i = 0; i < 32; ++i) { + pools[i] = md.create(); + } + ctx.pools = pools; + + // entropy pools are written to cyclically, starting at index 0 + ctx.pool = 0; + + /** + * Generates random bytes. The bytes may be generated synchronously or + * asynchronously. Web workers must use the asynchronous interface or + * else the behavior is undefined. + * + * @param count the number of random bytes to generate. + * @param [callback(err, bytes)] called once the operation completes. + * + * @return count random bytes as a string. + */ + ctx.generate = function(count, callback) { + // do synchronously + if(!callback) { + return ctx.generateSync(count); + } + + // simple generator using counter-based CBC + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + var b = forge$r.util.createBuffer(); + + // paranoid deviation from Fortuna: + // reset key for every request to protect previously + // generated random bytes should the key be discovered; + // there is no 100ms based reseeding because of this + // forced reseed for every `generate` call + ctx.key = null; + + generate(); + + function generate(err) { + if(err) { + return callback(err); + } + + // sufficient bytes generated + if(b.length() >= count) { + return callback(null, b.getBytes(count)); + } + + // if amount of data generated is greater than 1 MiB, trigger reseed + if(ctx.generated > 0xfffff) { + ctx.key = null; + } + + if(ctx.key === null) { + // prevent stack overflow + return forge$r.util.nextTick(function() { + _reseed(generate); + }); + } + + // generate the random bytes + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + + // generate bytes for a new key and seed + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + + forge$r.util.setImmediate(generate); + } + }; + + /** + * Generates random bytes synchronously. + * + * @param count the number of random bytes to generate. + * + * @return count random bytes as a string. + */ + ctx.generateSync = function(count) { + // simple generator using counter-based CBC + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + + // paranoid deviation from Fortuna: + // reset key for every request to protect previously + // generated random bytes should the key be discovered; + // there is no 100ms based reseeding because of this + // forced reseed for every `generateSync` call + ctx.key = null; + + var b = forge$r.util.createBuffer(); + while(b.length() < count) { + // if amount of data generated is greater than 1 MiB, trigger reseed + if(ctx.generated > 0xfffff) { + ctx.key = null; + } + + if(ctx.key === null) { + _reseedSync(); + } + + // generate the random bytes + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + + // generate bytes for a new key and seed + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + } + + return b.getBytes(count); + }; + + /** + * Private function that asynchronously reseeds a generator. + * + * @param callback(err) called once the operation completes. + */ + function _reseed(callback) { + if(ctx.pools[0].messageLength >= 32) { + _seed(); + return callback(); + } + // not enough seed data... + var needed = (32 - ctx.pools[0].messageLength) << 5; + ctx.seedFile(needed, function(err, bytes) { + if(err) { + return callback(err); + } + ctx.collect(bytes); + _seed(); + callback(); + }); + } + + /** + * Private function that synchronously reseeds a generator. + */ + function _reseedSync() { + if(ctx.pools[0].messageLength >= 32) { + return _seed(); + } + // not enough seed data... + var needed = (32 - ctx.pools[0].messageLength) << 5; + ctx.collect(ctx.seedFileSync(needed)); + _seed(); + } + + /** + * Private function that seeds a generator once enough bytes are available. + */ + function _seed() { + // update reseed count + ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1; + + // goal is to update `key` via: + // key = hash(key + s) + // where 's' is all collected entropy from selected pools, then... + + // create a plugin-based message digest + var md = ctx.plugin.md.create(); + + // consume current key bytes + md.update(ctx.keyBytes); + + // digest the entropy of pools whose index k meet the + // condition 'n mod 2^k == 0' where n is the number of reseeds + var _2powK = 1; + for(var k = 0; k < 32; ++k) { + if(ctx.reseeds % _2powK === 0) { + md.update(ctx.pools[k].digest().getBytes()); + ctx.pools[k].start(); + } + _2powK = _2powK << 1; + } + + // get digest for key bytes + ctx.keyBytes = md.digest().getBytes(); + + // paranoid deviation from Fortuna: + // update `seed` via `seed = hash(key)` + // instead of initializing to zero once and only + // ever incrementing it + md.start(); + md.update(ctx.keyBytes); + var seedBytes = md.digest().getBytes(); + + // update state + ctx.key = ctx.plugin.formatKey(ctx.keyBytes); + ctx.seed = ctx.plugin.formatSeed(seedBytes); + ctx.generated = 0; + } + + /** + * The built-in default seedFile. This seedFile is used when entropy + * is needed immediately. + * + * @param needed the number of bytes that are needed. + * + * @return the random bytes. + */ + function defaultSeedFile(needed) { + // use window.crypto.getRandomValues strong source of entropy if available + var getRandomValues = null; + var globalScope = forge$r.util.globalScope; + var _crypto = globalScope.crypto || globalScope.msCrypto; + if(_crypto && _crypto.getRandomValues) { + getRandomValues = function(arr) { + return _crypto.getRandomValues(arr); + }; + } + + var b = forge$r.util.createBuffer(); + if(getRandomValues) { + while(b.length() < needed) { + // max byte length is 65536 before QuotaExceededError is thrown + // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues + var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); + var entropy = new Uint32Array(Math.floor(count)); + try { + getRandomValues(entropy); + for(var i = 0; i < entropy.length; ++i) { + b.putInt32(entropy[i]); + } + } catch(e) { + /* only ignore QuotaExceededError */ + if(!(typeof QuotaExceededError !== 'undefined' && + e instanceof QuotaExceededError)) { + throw e; + } + } + } + } + + // be sad and add some weak random data + if(b.length() < needed) { + /* Draws from Park-Miller "minimal standard" 31 bit PRNG, + implemented with David G. Carta's optimization: with 32 bit math + and without division (Public Domain). */ + var hi, lo, next; + var seed = Math.floor(Math.random() * 0x010000); + while(b.length() < needed) { + lo = 16807 * (seed & 0xFFFF); + hi = 16807 * (seed >> 16); + lo += (hi & 0x7FFF) << 16; + lo += hi >> 15; + lo = (lo & 0x7FFFFFFF) + (lo >> 31); + seed = lo & 0xFFFFFFFF; + + // consume lower 3 bytes of seed + for(var i = 0; i < 3; ++i) { + // throw in more pseudo random + next = seed >>> (i << 3); + next ^= Math.floor(Math.random() * 0x0100); + b.putByte(String.fromCharCode(next & 0xFF)); + } + } + } + + return b.getBytes(needed); + } + // initialize seed file APIs + if(_crypto$1) { + // use nodejs async API + ctx.seedFile = function(needed, callback) { + _crypto$1.randomBytes(needed, function(err, bytes) { + if(err) { + return callback(err); + } + callback(null, bytes.toString()); + }); + }; + // use nodejs sync API + ctx.seedFileSync = function(needed) { + return _crypto$1.randomBytes(needed).toString(); + }; + } else { + ctx.seedFile = function(needed, callback) { + try { + callback(null, defaultSeedFile(needed)); + } catch(e) { + callback(e); + } + }; + ctx.seedFileSync = defaultSeedFile; + } + + /** + * Adds entropy to a prng ctx's accumulator. + * + * @param bytes the bytes of entropy as a string. + */ + ctx.collect = function(bytes) { + // iterate over pools distributing entropy cyclically + var count = bytes.length; + for(var i = 0; i < count; ++i) { + ctx.pools[ctx.pool].update(bytes.substr(i, 1)); + ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1; + } + }; + + /** + * Collects an integer of n bits. + * + * @param i the integer entropy. + * @param n the number of bits in the integer. + */ + ctx.collectInt = function(i, n) { + var bytes = ''; + for(var x = 0; x < n; x += 8) { + bytes += String.fromCharCode((i >> x) & 0xFF); + } + ctx.collect(bytes); + }; + + /** + * Registers a Web Worker to receive immediate entropy from the main thread. + * This method is required until Web Workers can access the native crypto + * API. This method should be called twice for each created worker, once in + * the main thread, and once in the worker itself. + * + * @param worker the worker to register. + */ + ctx.registerWorker = function(worker) { + // worker receives random bytes + if(worker === self) { + ctx.seedFile = function(needed, callback) { + function listener(e) { + var data = e.data; + if(data.forge && data.forge.prng) { + self.removeEventListener('message', listener); + callback(data.forge.prng.err, data.forge.prng.bytes); + } + } + self.addEventListener('message', listener); + self.postMessage({forge: {prng: {needed: needed}}}); + }; + } else { + // main thread sends random bytes upon request + var listener = function(e) { + var data = e.data; + if(data.forge && data.forge.prng) { + ctx.seedFile(data.forge.prng.needed, function(err, bytes) { + worker.postMessage({forge: {prng: {err: err, bytes: bytes}}}); + }); + } + }; + // TODO: do we need to remove the event listener when the worker dies? + worker.addEventListener('message', listener); + } + }; + + return ctx; +}; + +/** + * An API for getting cryptographically-secure random bytes. The bytes are + * generated using the Fortuna algorithm devised by Bruce Schneier and + * Niels Ferguson. + * + * Getting strong random bytes is not yet easy to do in javascript. The only + * truish random entropy that can be collected is from the mouse, keyboard, or + * from timing with respect to page loads, etc. This generator makes a poor + * attempt at providing random bytes when those sources haven't yet provided + * enough entropy to initially seed or to reseed the PRNG. + * + * @author Dave Longley + * + * Copyright (c) 2009-2014 Digital Bazaar, Inc. + */ + +var forge$q = forge$F; + + + + + +(function() { + +// forge.random already defined +if(forge$q.random && forge$q.random.getBytes) { + return; +} + +(function(jQuery) { + +// the default prng plugin, uses AES-128 +var prng_aes = {}; +var _prng_aes_output = new Array(4); +var _prng_aes_buffer = forge$q.util.createBuffer(); +prng_aes.formatKey = function(key) { + // convert the key into 32-bit integers + var tmp = forge$q.util.createBuffer(key); + key = new Array(4); + key[0] = tmp.getInt32(); + key[1] = tmp.getInt32(); + key[2] = tmp.getInt32(); + key[3] = tmp.getInt32(); + + // return the expanded key + return forge$q.aes._expandKey(key, false); +}; +prng_aes.formatSeed = function(seed) { + // convert seed into 32-bit integers + var tmp = forge$q.util.createBuffer(seed); + seed = new Array(4); + seed[0] = tmp.getInt32(); + seed[1] = tmp.getInt32(); + seed[2] = tmp.getInt32(); + seed[3] = tmp.getInt32(); + return seed; +}; +prng_aes.cipher = function(key, seed) { + forge$q.aes._updateBlock(key, seed, _prng_aes_output, false); + _prng_aes_buffer.putInt32(_prng_aes_output[0]); + _prng_aes_buffer.putInt32(_prng_aes_output[1]); + _prng_aes_buffer.putInt32(_prng_aes_output[2]); + _prng_aes_buffer.putInt32(_prng_aes_output[3]); + return _prng_aes_buffer.getBytes(); +}; +prng_aes.increment = function(seed) { + // FIXME: do we care about carry or signed issues? + ++seed[3]; + return seed; +}; +prng_aes.md = forge$q.md.sha256; + +/** + * Creates a new PRNG. + */ +function spawnPrng() { + var ctx = forge$q.prng.create(prng_aes); + + /** + * Gets random bytes. If a native secure crypto API is unavailable, this + * method tries to make the bytes more unpredictable by drawing from data that + * can be collected from the user of the browser, eg: mouse movement. + * + * If a callback is given, this method will be called asynchronously. + * + * @param count the number of random bytes to get. + * @param [callback(err, bytes)] called once the operation completes. + * + * @return the random bytes in a string. + */ + ctx.getBytes = function(count, callback) { + return ctx.generate(count, callback); + }; + + /** + * Gets random bytes asynchronously. If a native secure crypto API is + * unavailable, this method tries to make the bytes more unpredictable by + * drawing from data that can be collected from the user of the browser, + * eg: mouse movement. + * + * @param count the number of random bytes to get. + * + * @return the random bytes in a string. + */ + ctx.getBytesSync = function(count) { + return ctx.generate(count); + }; + + return ctx; +} + +// create default prng context +var _ctx = spawnPrng(); + +// add other sources of entropy only if window.crypto.getRandomValues is not +// available -- otherwise this source will be automatically used by the prng +var getRandomValues = null; +var globalScope = forge$q.util.globalScope; +var _crypto = globalScope.crypto || globalScope.msCrypto; +if(_crypto && _crypto.getRandomValues) { + getRandomValues = function(arr) { + return _crypto.getRandomValues(arr); + }; +} + +if((!forge$q.util.isNodejs && !getRandomValues)) { + + // get load time entropy + _ctx.collectInt(+new Date(), 32); + + // add some entropy from navigator object + if(typeof(navigator) !== 'undefined') { + var _navBytes = ''; + for(var key in navigator) { + try { + if(typeof(navigator[key]) == 'string') { + _navBytes += navigator[key]; + } + } catch(e) { + /* Some navigator keys might not be accessible, e.g. the geolocation + attribute throws an exception if touched in Mozilla chrome:// + context. + + Silently ignore this and just don't use this as a source of + entropy. */ + } + } + _ctx.collect(_navBytes); + _navBytes = null; + } + + // add mouse and keyboard collectors if jquery is available + if(jQuery) { + // set up mouse entropy capture + jQuery().mousemove(function(e) { + // add mouse coords + _ctx.collectInt(e.clientX, 16); + _ctx.collectInt(e.clientY, 16); + }); + + // set up keyboard entropy capture + jQuery().keypress(function(e) { + _ctx.collectInt(e.charCode, 8); + }); + } +} + +/* Random API */ +if(!forge$q.random) { + forge$q.random = _ctx; +} else { + // extend forge.random with _ctx + for(var key in _ctx) { + forge$q.random[key] = _ctx[key]; + } +} + +// expose spawn PRNG +forge$q.random.createInstance = spawnPrng; + +})(typeof(jQuery) !== 'undefined' ? jQuery : null); + +})(); + +/** + * RC2 implementation. + * + * @author Stefan Siegl + * + * Copyright (c) 2012 Stefan Siegl + * + * Information on the RC2 cipher is available from RFC #2268, + * http://www.ietf.org/rfc/rfc2268.txt + */ + +var forge$p = forge$F; + + +var piTable = [ + 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, + 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, + 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, + 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, + 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, + 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, + 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, + 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, + 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, + 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, + 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, + 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, + 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, + 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, + 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, + 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad +]; + +var s = [1, 2, 3, 5]; + +/** + * Rotate a word left by given number of bits. + * + * Bits that are shifted out on the left are put back in on the right + * hand side. + * + * @param word The word to shift left. + * @param bits The number of bits to shift by. + * @return The rotated word. + */ +var rol = function(word, bits) { + return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits)); +}; + +/** + * Rotate a word right by given number of bits. + * + * Bits that are shifted out on the right are put back in on the left + * hand side. + * + * @param word The word to shift right. + * @param bits The number of bits to shift by. + * @return The rotated word. + */ +var ror = function(word, bits) { + return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff); +}; + +/* RC2 API */ +forge$p.rc2 = forge$p.rc2 || {}; + +/** + * Perform RC2 key expansion as per RFC #2268, section 2. + * + * @param key variable-length user key (between 1 and 128 bytes) + * @param effKeyBits number of effective key bits (default: 128) + * @return the expanded RC2 key (ByteBuffer of 128 bytes) + */ +forge$p.rc2.expandKey = function(key, effKeyBits) { + if(typeof key === 'string') { + key = forge$p.util.createBuffer(key); + } + effKeyBits = effKeyBits || 128; + + /* introduce variables that match the names used in RFC #2268 */ + var L = key; + var T = key.length(); + var T1 = effKeyBits; + var T8 = Math.ceil(T1 / 8); + var TM = 0xff >> (T1 & 0x07); + var i; + + for(i = T; i < 128; i++) { + L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]); + } + + L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); + + for(i = 127 - T8; i >= 0; i--) { + L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); + } + + return L; +}; + +/** + * Creates a RC2 cipher object. + * + * @param key the symmetric key to use (as base for key generation). + * @param bits the number of effective key bits. + * @param encrypt false for decryption, true for encryption. + * + * @return the cipher. + */ +var createCipher = function(key, bits, encrypt) { + var _finish = false, _input = null, _output = null, _iv = null; + var mixRound, mashRound; + var i, j, K = []; + + /* Expand key and fill into K[] Array */ + key = forge$p.rc2.expandKey(key, bits); + for(i = 0; i < 64; i++) { + K.push(key.getInt16Le()); + } + + if(encrypt) { + /** + * Perform one mixing round "in place". + * + * @param R Array of four words to perform mixing on. + */ + mixRound = function(R) { + for(i = 0; i < 4; i++) { + R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); + R[i] = rol(R[i], s[i]); + j++; + } + }; + + /** + * Perform one mashing round "in place". + * + * @param R Array of four words to perform mashing on. + */ + mashRound = function(R) { + for(i = 0; i < 4; i++) { + R[i] += K[R[(i + 3) % 4] & 63]; + } + }; + } else { + /** + * Perform one r-mixing round "in place". + * + * @param R Array of four words to perform mixing on. + */ + mixRound = function(R) { + for(i = 3; i >= 0; i--) { + R[i] = ror(R[i], s[i]); + R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); + j--; + } + }; + + /** + * Perform one r-mashing round "in place". + * + * @param R Array of four words to perform mashing on. + */ + mashRound = function(R) { + for(i = 3; i >= 0; i--) { + R[i] -= K[R[(i + 3) % 4] & 63]; + } + }; + } + + /** + * Run the specified cipher execution plan. + * + * This function takes four words from the input buffer, applies the IV on + * it (if requested) and runs the provided execution plan. + * + * The plan must be put together in form of a array of arrays. Where the + * outer one is simply a list of steps to perform and the inner one needs + * to have two elements: the first one telling how many rounds to perform, + * the second one telling what to do (i.e. the function to call). + * + * @param {Array} plan The plan to execute. + */ + var runPlan = function(plan) { + var R = []; + + /* Get data from input buffer and fill the four words into R */ + for(i = 0; i < 4; i++) { + var val = _input.getInt16Le(); + + if(_iv !== null) { + if(encrypt) { + /* We're encrypting, apply the IV first. */ + val ^= _iv.getInt16Le(); + } else { + /* We're decryption, keep cipher text for next block. */ + _iv.putInt16Le(val); + } + } + + R.push(val & 0xffff); + } + + /* Reset global "j" variable as per spec. */ + j = encrypt ? 0 : 63; + + /* Run execution plan. */ + for(var ptr = 0; ptr < plan.length; ptr++) { + for(var ctr = 0; ctr < plan[ptr][0]; ctr++) { + plan[ptr][1](R); + } + } + + /* Write back result to output buffer. */ + for(i = 0; i < 4; i++) { + if(_iv !== null) { + if(encrypt) { + /* We're encrypting in CBC-mode, feed back encrypted bytes into + IV buffer to carry it forward to next block. */ + _iv.putInt16Le(R[i]); + } else { + R[i] ^= _iv.getInt16Le(); + } + } + + _output.putInt16Le(R[i]); + } + }; + + /* Create cipher object */ + var cipher = null; + cipher = { + /** + * Starts or restarts the encryption or decryption process, whichever + * was previously configured. + * + * To use the cipher in CBC mode, iv may be given either as a string + * of bytes, or as a byte buffer. For ECB mode, give null as iv. + * + * @param iv the initialization vector to use, null for ECB mode. + * @param output the output the buffer to write to, null to create one. + */ + start: function(iv, output) { + if(iv) { + /* CBC mode */ + if(typeof iv === 'string') { + iv = forge$p.util.createBuffer(iv); + } + } + + _finish = false; + _input = forge$p.util.createBuffer(); + _output = output || new forge$p.util.createBuffer(); + _iv = iv; + + cipher.output = _output; + }, + + /** + * Updates the next block. + * + * @param input the buffer to read from. + */ + update: function(input) { + if(!_finish) { + // not finishing, so fill the input buffer with more input + _input.putBuffer(input); + } + + while(_input.length() >= 8) { + runPlan([ + [ 5, mixRound ], + [ 1, mashRound ], + [ 6, mixRound ], + [ 1, mashRound ], + [ 5, mixRound ] + ]); + } + }, + + /** + * Finishes encrypting or decrypting. + * + * @param pad a padding function to use, null for PKCS#7 padding, + * signature(blockSize, buffer, decrypt). + * + * @return true if successful, false on error. + */ + finish: function(pad) { + var rval = true; + + if(encrypt) { + if(pad) { + rval = pad(8, _input, !encrypt); + } else { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (_input.length() === 8) ? 8 : (8 - _input.length()); + _input.fillWithByte(padding, padding); + } + } + + if(rval) { + // do final update + _finish = true; + cipher.update(); + } + + if(!encrypt) { + // check for error: input data not a multiple of block size + rval = (_input.length() === 0); + if(rval) { + if(pad) { + rval = pad(8, _output, !encrypt); + } else { + // ensure padding byte count is valid + var len = _output.length(); + var count = _output.at(len - 1); + + if(count > len) { + rval = false; + } else { + // trim off padding bytes + _output.truncate(count); + } + } + } + } + + return rval; + } + }; + + return cipher; +}; + +/** + * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the + * given symmetric key. The output will be stored in the 'output' member + * of the returned cipher. + * + * The key and iv may be given as a string of bytes or a byte buffer. + * The cipher is initialized to use 128 effective key bits. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * + * @return the cipher. + */ +forge$p.rc2.startEncrypting = function(key, iv, output) { + var cipher = forge$p.rc2.createEncryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; +}; + +/** + * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the + * given symmetric key. + * + * The key may be given as a string of bytes or a byte buffer. + * + * To start encrypting call start() on the cipher with an iv and optional + * output buffer. + * + * @param key the symmetric key to use. + * + * @return the cipher. + */ +forge$p.rc2.createEncryptionCipher = function(key, bits) { + return createCipher(key, bits, true); +}; + +/** + * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the + * given symmetric key. The output will be stored in the 'output' member + * of the returned cipher. + * + * The key and iv may be given as a string of bytes or a byte buffer. + * The cipher is initialized to use 128 effective key bits. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * + * @return the cipher. + */ +forge$p.rc2.startDecrypting = function(key, iv, output) { + var cipher = forge$p.rc2.createDecryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; +}; + +/** + * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the + * given symmetric key. + * + * The key may be given as a string of bytes or a byte buffer. + * + * To start decrypting call start() on the cipher with an iv and optional + * output buffer. + * + * @param key the symmetric key to use. + * + * @return the cipher. + */ +forge$p.rc2.createDecryptionCipher = function(key, bits) { + return createCipher(key, bits, false); +}; + +// Copyright (c) 2005 Tom Wu +// All Rights Reserved. +// See "LICENSE" for details. + +// Basic JavaScript BN library - subset useful for RSA encryption. + +/* +Licensing (LICENSE) +------------------- + +This software is covered under the following copyright: +*/ +/* + * Copyright (c) 2003-2005 Tom Wu + * 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" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, + * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF + * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * In addition, the following condition applies: + * + * All redistributions must retain an intact copy of this copyright notice + * and disclaimer. + */ +/* +Address all questions regarding this license to: + + Tom Wu + tjw@cs.Stanford.EDU +*/ +var forge$o = forge$F; + +forge$o.jsbn = forge$o.jsbn || {}; + +// Bits per digit +var dbits; + +// (public) Constructor +function BigInteger$2(a,b,c) { + this.data = []; + if(a != null) + if("number" == typeof a) this.fromNumber(a,b,c); + else if(b == null && "string" != typeof a) this.fromString(a,256); + else this.fromString(a,b); +} +forge$o.jsbn.BigInteger = BigInteger$2; + +// return new, unset BigInteger +function nbi() { return new BigInteger$2(null); } + +// am: Compute w_j += (x*this_i), propagate carries, +// c is initial carry, returns final carry. +// c < 3*dvalue, x < 2*dvalue, this_i < dvalue +// We need to select the fastest one that works in this environment. + +// am1: use a single mult and divide to get the high bits, +// max digit bits should be 26 because +// max internal value = 2*dvalue^2-2*dvalue (< 2^53) +function am1(i,x,w,j,c,n) { + while(--n >= 0) { + var v = x*this.data[i++]+w.data[j]+c; + c = Math.floor(v/0x4000000); + w.data[j++] = v&0x3ffffff; + } + return c; +} +// am2 avoids a big mult-and-extract completely. +// Max digit bits should be <= 30 because we do bitwise ops +// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) +function am2(i,x,w,j,c,n) { + var xl = x&0x7fff, xh = x>>15; + while(--n >= 0) { + var l = this.data[i]&0x7fff; + var h = this.data[i++]>>15; + var m = xh*l+h*xl; + l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff); + c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); + w.data[j++] = l&0x3fffffff; + } + return c; +} +// Alternately, set max digit bits to 28 since some +// browsers slow down when dealing with 32-bit numbers. +function am3(i,x,w,j,c,n) { + var xl = x&0x3fff, xh = x>>14; + while(--n >= 0) { + var l = this.data[i]&0x3fff; + var h = this.data[i++]>>14; + var m = xh*l+h*xl; + l = xl*l+((m&0x3fff)<<14)+w.data[j]+c; + c = (l>>28)+(m>>14)+xh*h; + w.data[j++] = l&0xfffffff; + } + return c; +} + +// node.js (no browser) +if(typeof(navigator) === 'undefined') +{ + BigInteger$2.prototype.am = am3; + dbits = 28; +} else if((navigator.appName == "Microsoft Internet Explorer")) { + BigInteger$2.prototype.am = am2; + dbits = 30; +} else if((navigator.appName != "Netscape")) { + BigInteger$2.prototype.am = am1; + dbits = 26; +} else { // Mozilla/Netscape seems to prefer am3 + BigInteger$2.prototype.am = am3; + dbits = 28; +} + +BigInteger$2.prototype.DB = dbits; +BigInteger$2.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i]; + r.t = this.t; + r.s = this.s; +} + +// (protected) set from integer value x, -DV <= x < DV +function bnpFromInt(x) { + this.t = 1; + this.s = (x<0)?-1:0; + if(x > 0) this.data[0] = x; + else if(x < -1) this.data[0] = x+this.DV; + else this.t = 0; +} + +// return bigint initialized to value +function nbv(i) { var r = nbi(); r.fromInt(i); return r; } + +// (protected) set from string and radix +function bnpFromString(s,b) { + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 256) k = 8; // byte array + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else { this.fromRadix(s,b); return; } + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while(--i >= 0) { + var x = (k==8)?s[i]&0xff:intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if(sh == 0) + this.data[this.t++] = x; + else if(sh+k > this.DB) { + this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); + } else + this.data[this.t-1] |= x<= this.DB) sh -= this.DB; + } + if(k == 8 && (s[0]&0x80) != 0) { + this.s = -1; + if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t; +} + +// (public) return string representation in given radix +function bnToString(b) { + if(this.s < 0) return "-"+this.negate().toString(b); + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else return this.toRadix(b); + var km = (1< 0) { + if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); } + while(i >= 0) { + if(p < k) { + d = (this.data[i]&((1<>(p+=this.DB-k); + } else { + d = (this.data[i]>>(p-=k))&km; + if(p <= 0) { p += this.DB; --i; } + } + if(d > 0) m = true; + if(m) r += int2char(d); + } + } + return m?r:"0"; +} + +// (public) -this +function bnNegate() { var r = nbi(); BigInteger$2.ZERO.subTo(this,r); return r; } + +// (public) |this| +function bnAbs() { return (this.s<0)?this.negate():this; } + +// (public) return + if this > a, - if this < a, 0 if equal +function bnCompareTo(a) { + var r = this.s-a.s; + if(r != 0) return r; + var i = this.t; + r = i-a.t; + if(r != 0) return (this.s<0)?-r:r; + while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r; + return 0; +} + +// returns bit length of the integer x +function nbits(x) { + var r = 1, t; + if((t=x>>>16) != 0) { x = t; r += 16; } + if((t=x>>8) != 0) { x = t; r += 8; } + if((t=x>>4) != 0) { x = t; r += 4; } + if((t=x>>2) != 0) { x = t; r += 2; } + if((t=x>>1) != 0) { x = t; r += 1; } + return r; +} + +// (public) return the number of bits in "this" +function bnBitLength() { + if(this.t <= 0) return 0; + return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM)); +} + +// (protected) r = this << n*DB +function bnpDLShiftTo(n,r) { + var i; + for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i]; + for(i = n-1; i >= 0; --i) r.data[i] = 0; + r.t = this.t+n; + r.s = this.s; +} + +// (protected) r = this >> n*DB +function bnpDRShiftTo(n,r) { + for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i]; + r.t = Math.max(this.t-n,0); + r.s = this.s; +} + +// (protected) r = this << n +function bnpLShiftTo(n,r) { + var bs = n%this.DB; + var cbs = this.DB-bs; + var bm = (1<= 0; --i) { + r.data[i+ds+1] = (this.data[i]>>cbs)|c; + c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0; + r.data[ds] = c; + r.t = this.t+ds+1; + r.s = this.s; + r.clamp(); +} + +// (protected) r = this >> n +function bnpRShiftTo(n,r) { + r.s = this.s; + var ds = Math.floor(n/this.DB); + if(ds >= this.t) { r.t = 0; return; } + var bs = n%this.DB; + var cbs = this.DB-bs; + var bm = (1<>bs; + for(var i = ds+1; i < this.t; ++i) { + r.data[i-ds-1] |= (this.data[i]&bm)<>bs; + } + if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB; + } + if(a.t < this.t) { + c -= a.s; + while(i < this.t) { + c += this.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while(i < a.t) { + c -= a.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c<0)?-1:0; + if(c < -1) r.data[i++] = this.DV+c; + else if(c > 0) r.data[i++] = c; + r.t = i; + r.clamp(); +} + +// (protected) r = this * a, r != this,a (HAC 14.12) +// "this" should be the larger one if appropriate. +function bnpMultiplyTo(a,r) { + var x = this.abs(), y = a.abs(); + var i = x.t; + r.t = i+y.t; + while(--i >= 0) r.data[i] = 0; + for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t); + r.s = 0; + r.clamp(); + if(this.s != a.s) BigInteger$2.ZERO.subTo(r,r); +} + +// (protected) r = this^2, r != this (HAC 14.16) +function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2*x.t; + while(--i >= 0) r.data[i] = 0; + for(i = 0; i < x.t-1; ++i) { + var c = x.am(i,x.data[i],r,2*i,0,1); + if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { + r.data[i+x.t] -= x.DV; + r.data[i+x.t+1] = 1; + } + } + if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1); + r.s = 0; + r.clamp(); +} + +// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) +// r != q, this != m. q or r may be null. +function bnpDivRemTo(m,q,r) { + var pm = m.abs(); + if(pm.t <= 0) return; + var pt = this.abs(); + if(pt.t < pm.t) { + if(q != null) q.fromInt(0); + if(r != null) this.copyTo(r); + return; + } + if(r == null) r = nbi(); + var y = nbi(), ts = this.s, ms = m.s; + var nsh = this.DB-nbits(pm.data[pm.t-1]); // normalize modulus + if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } + var ys = y.t; + var y0 = y.data[ys-1]; + if(y0 == 0) return; + var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0); + var d1 = this.FV/yt, d2 = (1<= 0) { + r.data[r.t++] = 1; + r.subTo(t,r); + } + BigInteger$2.ONE.dlShiftTo(ys,t); + t.subTo(y,y); // "negative" y so we can replace sub with am later + while(y.t < ys) y.data[y.t++] = 0; + while(--j >= 0) { + // Estimate quotient digit + var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2); + if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out + y.dlShiftTo(j,t); + r.subTo(t,r); + while(r.data[i] < --qd) r.subTo(t,r); + } + } + if(q != null) { + r.drShiftTo(ys,q); + if(ts != ms) BigInteger$2.ZERO.subTo(q,q); + } + r.t = ys; + r.clamp(); + if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder + if(ts < 0) BigInteger$2.ZERO.subTo(r,r); +} + +// (public) this mod a +function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a,null,r); + if(this.s < 0 && r.compareTo(BigInteger$2.ZERO) > 0) a.subTo(r,r); + return r; +} + +// Modular reduction using "classic" algorithm +function Classic(m) { this.m = m; } +function cConvert(x) { + if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; +} +function cRevert(x) { return x; } +function cReduce(x) { x.divRemTo(this.m,null,x); } +function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } +function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +Classic.prototype.convert = cConvert; +Classic.prototype.revert = cRevert; +Classic.prototype.reduce = cReduce; +Classic.prototype.mulTo = cMulTo; +Classic.prototype.sqrTo = cSqrTo; + +// (protected) return "-1/this % 2^DB"; useful for Mont. reduction +// justification: +// xy == 1 (mod m) +// xy = 1+km +// xy(2-xy) = (1+km)(1-km) +// x[y(2-xy)] = 1-k^2m^2 +// x[y(2-xy)] == 1 (mod m^2) +// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 +// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. +// JS multiply "overflows" differently from C/C++, so care is needed here. +function bnpInvDigit() { + if(this.t < 1) return 0; + var x = this.data[0]; + if((x&1) == 0) return 0; + var y = x&3; // y == 1/x mod 2^2 + y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 + y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 + y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y>0)?this.DV-y:-y; +} + +// Montgomery reduction +function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp&0x7fff; + this.mph = this.mp>>15; + this.um = (1<<(m.DB-15))-1; + this.mt2 = 2*m.t; +} + +// xR mod m +function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t,r); + r.divRemTo(this.m,null,r); + if(x.s < 0 && r.compareTo(BigInteger$2.ZERO) > 0) this.m.subTo(r,r); + return r; +} + +// x/R mod m +function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; +} + +// x = x/R mod m (HAC 14.32) +function montReduce(x) { + while(x.t <= this.mt2) // pad x so am has enough room later + x.data[x.t++] = 0; + for(var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x.data[i]*mp mod DV + var j = x.data[i]&0x7fff; + var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM; + // use am to combine the multiply-shift-add into one call + j = i+this.m.t; + x.data[j] += this.m.am(0,u0,x,i,0,this.m.t); + // propagate carry + while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; } + } + x.clamp(); + x.drShiftTo(this.m.t,x); + if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +// r = "x^2/R mod m"; x != r +function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +// r = "xy/R mod m"; x,y != r +function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Montgomery.prototype.convert = montConvert; +Montgomery.prototype.revert = montRevert; +Montgomery.prototype.reduce = montReduce; +Montgomery.prototype.mulTo = montMulTo; +Montgomery.prototype.sqrTo = montSqrTo; + +// (protected) true iff this is even +function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; } + +// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) +function bnpExp(e,z) { + if(e > 0xffffffff || e < 1) return BigInteger$2.ONE; + var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; + g.copyTo(r); + while(--i >= 0) { + z.sqrTo(r,r2); + if((e&(1< 0) z.mulTo(r2,g,r); + else { var t = r; r = r2; r2 = t; } + } + return z.revert(r); +} + +// (public) this^e % m, 0 <= e < 2^32 +function bnModPowInt(e,m) { + var z; + if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); + return this.exp(e,z); +} + +// protected +BigInteger$2.prototype.copyTo = bnpCopyTo; +BigInteger$2.prototype.fromInt = bnpFromInt; +BigInteger$2.prototype.fromString = bnpFromString; +BigInteger$2.prototype.clamp = bnpClamp; +BigInteger$2.prototype.dlShiftTo = bnpDLShiftTo; +BigInteger$2.prototype.drShiftTo = bnpDRShiftTo; +BigInteger$2.prototype.lShiftTo = bnpLShiftTo; +BigInteger$2.prototype.rShiftTo = bnpRShiftTo; +BigInteger$2.prototype.subTo = bnpSubTo; +BigInteger$2.prototype.multiplyTo = bnpMultiplyTo; +BigInteger$2.prototype.squareTo = bnpSquareTo; +BigInteger$2.prototype.divRemTo = bnpDivRemTo; +BigInteger$2.prototype.invDigit = bnpInvDigit; +BigInteger$2.prototype.isEven = bnpIsEven; +BigInteger$2.prototype.exp = bnpExp; + +// public +BigInteger$2.prototype.toString = bnToString; +BigInteger$2.prototype.negate = bnNegate; +BigInteger$2.prototype.abs = bnAbs; +BigInteger$2.prototype.compareTo = bnCompareTo; +BigInteger$2.prototype.bitLength = bnBitLength; +BigInteger$2.prototype.mod = bnMod; +BigInteger$2.prototype.modPowInt = bnModPowInt; + +// "constants" +BigInteger$2.ZERO = nbv(0); +BigInteger$2.ONE = nbv(1); + +// jsbn2 lib + +//Copyright (c) 2005-2009 Tom Wu +//All Rights Reserved. +//See "LICENSE" for details (See jsbn.js for LICENSE). + +//Extended JavaScript BN functions, required for RSA private ops. + +//Version 1.1: new BigInteger("0", 10) returns "proper" zero + +//(public) +function bnClone() { var r = nbi(); this.copyTo(r); return r; } + +//(public) return value as integer +function bnIntValue() { +if(this.s < 0) { + if(this.t == 1) return this.data[0]-this.DV; + else if(this.t == 0) return -1; +} else if(this.t == 1) return this.data[0]; +else if(this.t == 0) return 0; +// assumes 16 < DB < 32 +return ((this.data[1]&((1<<(32-this.DB))-1))<>24; } + +//(public) return value as short (assumes DB>=16) +function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; } + +//(protected) return x s.t. r^x < DV +function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } + +//(public) 0 if this == 0, 1 if this > 0 +function bnSigNum() { +if(this.s < 0) return -1; +else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0; +else return 1; +} + +//(protected) convert to radix string +function bnpToRadix(b) { +if(b == null) b = 10; +if(this.signum() == 0 || b < 2 || b > 36) return "0"; +var cs = this.chunkSize(b); +var a = Math.pow(b,cs); +var d = nbv(a), y = nbi(), z = nbi(), r = ""; +this.divRemTo(d,y,z); +while(y.signum() > 0) { + r = (a+z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d,y,z); +} +return z.intValue().toString(b) + r; +} + +//(protected) convert from radix string +function bnpFromRadix(s,b) { +this.fromInt(0); +if(b == null) b = 10; +var cs = this.chunkSize(b); +var d = Math.pow(b,cs), mi = false, j = 0, w = 0; +for(var i = 0; i < s.length; ++i) { + var x = intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b*w+x; + if(++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w,0); + j = 0; + w = 0; + } +} +if(j > 0) { + this.dMultiply(Math.pow(b,j)); + this.dAddOffset(w,0); +} +if(mi) BigInteger$2.ZERO.subTo(this,this); +} + +//(protected) alternate constructor +function bnpFromNumber(a,b,c) { +if("number" == typeof b) { + // new BigInteger(int,int,RNG) + if(a < 2) this.fromInt(1); + else { + this.fromNumber(a,c); + if(!this.testBit(a-1)) // force MSB set + this.bitwiseTo(BigInteger$2.ONE.shiftLeft(a-1),op_or,this); + if(this.isEven()) this.dAddOffset(1,0); // force odd + while(!this.isProbablePrime(b)) { + this.dAddOffset(2,0); + if(this.bitLength() > a) this.subTo(BigInteger$2.ONE.shiftLeft(a-1),this); + } + } +} else { + // new BigInteger(int,RNG) + var x = new Array(), t = a&7; + x.length = (a>>3)+1; + b.nextBytes(x); + if(t > 0) x[0] &= ((1< 0) { + if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p) + r[k++] = d|(this.s<<(this.DB-p)); + while(i >= 0) { + if(p < 8) { + d = (this.data[i]&((1<>(p+=this.DB-8); + } else { + d = (this.data[i]>>(p-=8))&0xff; + if(p <= 0) { p += this.DB; --i; } + } + if((d&0x80) != 0) d |= -256; + if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; + if(k > 0 || d != this.s) r[k++] = d; + } +} +return r; +} + +function bnEquals(a) { return(this.compareTo(a)==0); } +function bnMin(a) { return (this.compareTo(a)<0)?this:a; } +function bnMax(a) { return (this.compareTo(a)>0)?this:a; } + +//(protected) r = this op a (bitwise) +function bnpBitwiseTo(a,op,r) { +var i, f, m = Math.min(a.t,this.t); +for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]); +if(a.t < this.t) { + f = a.s&this.DM; + for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f); + r.t = this.t; +} else { + f = this.s&this.DM; + for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]); + r.t = a.t; +} +r.s = op(this.s,a.s); +r.clamp(); +} + +//(public) this & a +function op_and(x,y) { return x&y; } +function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } + +//(public) this | a +function op_or(x,y) { return x|y; } +function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } + +//(public) this ^ a +function op_xor(x,y) { return x^y; } +function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } + +//(public) this & ~a +function op_andnot(x,y) { return x&~y; } +function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } + +//(public) ~this +function bnNot() { +var r = nbi(); +for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i]; +r.t = this.t; +r.s = ~this.s; +return r; +} + +//(public) this << n +function bnShiftLeft(n) { +var r = nbi(); +if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); +return r; +} + +//(public) this >> n +function bnShiftRight(n) { +var r = nbi(); +if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); +return r; +} + +//return index of lowest 1-bit in x, x < 2^31 +function lbit(x) { +if(x == 0) return -1; +var r = 0; +if((x&0xffff) == 0) { x >>= 16; r += 16; } +if((x&0xff) == 0) { x >>= 8; r += 8; } +if((x&0xf) == 0) { x >>= 4; r += 4; } +if((x&3) == 0) { x >>= 2; r += 2; } +if((x&1) == 0) ++r; +return r; +} + +//(public) returns index of lowest 1-bit (or -1 if none) +function bnGetLowestSetBit() { +for(var i = 0; i < this.t; ++i) + if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]); +if(this.s < 0) return this.t*this.DB; +return -1; +} + +//return number of 1 bits in x +function cbit(x) { +var r = 0; +while(x != 0) { x &= x-1; ++r; } +return r; +} + +//(public) return number of set bits +function bnBitCount() { +var r = 0, x = this.s&this.DM; +for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x); +return r; +} + +//(public) true iff nth bit is set +function bnTestBit(n) { +var j = Math.floor(n/this.DB); +if(j >= this.t) return(this.s!=0); +return((this.data[j]&(1<<(n%this.DB)))!=0); +} + +//(protected) this op (1<>= this.DB; +} +if(a.t < this.t) { + c += a.s; + while(i < this.t) { + c += this.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; +} else { + c += this.s; + while(i < a.t) { + c += a.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += a.s; +} +r.s = (c<0)?-1:0; +if(c > 0) r.data[i++] = c; +else if(c < -1) r.data[i++] = this.DV+c; +r.t = i; +r.clamp(); +} + +//(public) this + a +function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } + +//(public) this - a +function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } + +//(public) this * a +function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } + +//(public) this / a +function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } + +//(public) this % a +function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } + +//(public) [this/a,this%a] +function bnDivideAndRemainder(a) { +var q = nbi(), r = nbi(); +this.divRemTo(a,q,r); +return new Array(q,r); +} + +//(protected) this *= n, this >= 0, 1 < n < DV +function bnpDMultiply(n) { +this.data[this.t] = this.am(0,n-1,this,0,0,this.t); +++this.t; +this.clamp(); +} + +//(protected) this += n << w words, this >= 0 +function bnpDAddOffset(n,w) { +if(n == 0) return; +while(this.t <= w) this.data[this.t++] = 0; +this.data[w] += n; +while(this.data[w] >= this.DV) { + this.data[w] -= this.DV; + if(++w >= this.t) this.data[this.t++] = 0; + ++this.data[w]; +} +} + +//A "null" reducer +function NullExp() {} +function nNop(x) { return x; } +function nMulTo(x,y,r) { x.multiplyTo(y,r); } +function nSqrTo(x,r) { x.squareTo(r); } + +NullExp.prototype.convert = nNop; +NullExp.prototype.revert = nNop; +NullExp.prototype.mulTo = nMulTo; +NullExp.prototype.sqrTo = nSqrTo; + +//(public) this^e +function bnPow(e) { return this.exp(e,new NullExp()); } + +//(protected) r = lower n words of "this * a", a.t <= n +//"this" should be the larger one if appropriate. +function bnpMultiplyLowerTo(a,n,r) { +var i = Math.min(this.t+a.t,n); +r.s = 0; // assumes a,this >= 0 +r.t = i; +while(i > 0) r.data[--i] = 0; +var j; +for(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t); +for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i); +r.clamp(); +} + +//(protected) r = "this * a" without lower n words, n > 0 +//"this" should be the larger one if appropriate. +function bnpMultiplyUpperTo(a,n,r) { +--n; +var i = r.t = this.t+a.t-n; +r.s = 0; // assumes a,this >= 0 +while(--i >= 0) r.data[i] = 0; +for(i = Math.max(n-this.t,0); i < a.t; ++i) + r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n); +r.clamp(); +r.drShiftTo(1,r); +} + +//Barrett modular reduction +function Barrett(m) { +// setup Barrett +this.r2 = nbi(); +this.q3 = nbi(); +BigInteger$2.ONE.dlShiftTo(2*m.t,this.r2); +this.mu = this.r2.divide(m); +this.m = m; +} + +function barrettConvert(x) { +if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); +else if(x.compareTo(this.m) < 0) return x; +else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } +} + +function barrettRevert(x) { return x; } + +//x = x mod m (HAC 14.42) +function barrettReduce(x) { +x.drShiftTo(this.m.t-1,this.r2); +if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } +this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); +this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); +while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); +x.subTo(this.r2,x); +while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +//r = x^2 mod m; x != r +function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +//r = x*y mod m; x,y != r +function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Barrett.prototype.convert = barrettConvert; +Barrett.prototype.revert = barrettRevert; +Barrett.prototype.reduce = barrettReduce; +Barrett.prototype.mulTo = barrettMulTo; +Barrett.prototype.sqrTo = barrettSqrTo; + +//(public) this^e % m (HAC 14.85) +function bnModPow(e,m) { +var i = e.bitLength(), k, r = nbv(1), z; +if(i <= 0) return r; +else if(i < 18) k = 1; +else if(i < 48) k = 3; +else if(i < 144) k = 4; +else if(i < 768) k = 5; +else k = 6; +if(i < 8) + z = new Classic(m); +else if(m.isEven()) + z = new Barrett(m); +else + z = new Montgomery(m); + +// precomputation +var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { + var g2 = nbi(); + z.sqrTo(g[1],g2); + while(n <= km) { + g[n] = nbi(); + z.mulTo(g2,g[n-2],g[n]); + n += 2; + } +} + +var j = e.t-1, w, is1 = true, r2 = nbi(), t; +i = nbits(e.data[j])-1; +while(j >= 0) { + if(i >= k1) w = (e.data[j]>>(i-k1))&km; + else { + w = (e.data[j]&((1<<(i+1))-1))<<(k1-i); + if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1); + } + + n = k; + while((w&1) == 0) { w >>= 1; --n; } + if((i -= n) < 0) { i += this.DB; --j; } + if(is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } else { + while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } + if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } + z.mulTo(r2,g[w],r); + } + + while(j >= 0 && (e.data[j]&(1< 0) { + x.rShiftTo(g,x); + y.rShiftTo(g,y); +} +while(x.signum() > 0) { + if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); + if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); + if(x.compareTo(y) >= 0) { + x.subTo(y,x); + x.rShiftTo(1,x); + } else { + y.subTo(x,y); + y.rShiftTo(1,y); + } +} +if(g > 0) y.lShiftTo(g,y); +return y; +} + +//(protected) this % n, n < 2^26 +function bnpModInt(n) { +if(n <= 0) return 0; +var d = this.DV%n, r = (this.s<0)?n-1:0; +if(this.t > 0) + if(d == 0) r = this.data[0]%n; + else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n; +return r; +} + +//(public) 1/this % m (HAC 14.61) +function bnModInverse(m) { +var ac = m.isEven(); +if((this.isEven() && ac) || m.signum() == 0) return BigInteger$2.ZERO; +var u = m.clone(), v = this.clone(); +var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); +while(u.signum() != 0) { + while(u.isEven()) { + u.rShiftTo(1,u); + if(ac) { + if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } + a.rShiftTo(1,a); + } else if(!b.isEven()) b.subTo(m,b); + b.rShiftTo(1,b); + } + while(v.isEven()) { + v.rShiftTo(1,v); + if(ac) { + if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } + c.rShiftTo(1,c); + } else if(!d.isEven()) d.subTo(m,d); + d.rShiftTo(1,d); + } + if(u.compareTo(v) >= 0) { + u.subTo(v,u); + if(ac) a.subTo(c,a); + b.subTo(d,b); + } else { + v.subTo(u,v); + if(ac) c.subTo(a,c); + d.subTo(b,d); + } +} +if(v.compareTo(BigInteger$2.ONE) != 0) return BigInteger$2.ZERO; +if(d.compareTo(m) >= 0) return d.subtract(m); +if(d.signum() < 0) d.addTo(m,d); else return d; +if(d.signum() < 0) return d.add(m); else return d; +} + +var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; +var lplim = (1<<26)/lowprimes[lowprimes.length-1]; + +//(public) test primality with certainty >= 1-.5^t +function bnIsProbablePrime(t) { +var i, x = this.abs(); +if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) { + for(i = 0; i < lowprimes.length; ++i) + if(x.data[0] == lowprimes[i]) return true; + return false; +} +if(x.isEven()) return false; +i = 1; +while(i < lowprimes.length) { + var m = lowprimes[i], j = i+1; + while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while(i < j) if(m%lowprimes[i++] == 0) return false; +} +return x.millerRabin(t); +} + +//(protected) true if probably prime (HAC 4.24, Miller-Rabin) +function bnpMillerRabin(t) { +var n1 = this.subtract(BigInteger$2.ONE); +var k = n1.getLowestSetBit(); +if(k <= 0) return false; +var r = n1.shiftRight(k); +var prng = bnGetPrng(); +var a; +for(var i = 0; i < t; ++i) { + // select witness 'a' at random from between 1 and n1 + do { + a = new BigInteger$2(this.bitLength(), prng); + } + while(a.compareTo(BigInteger$2.ONE) <= 0 || a.compareTo(n1) >= 0); + var y = a.modPow(r,this); + if(y.compareTo(BigInteger$2.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while(j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2,this); + if(y.compareTo(BigInteger$2.ONE) == 0) return false; + } + if(y.compareTo(n1) != 0) return false; + } +} +return true; +} + +// get pseudo random number generator +function bnGetPrng() { + // create prng with api that matches BigInteger secure random + return { + // x is an array to fill with bytes + nextBytes: function(x) { + for(var i = 0; i < x.length; ++i) { + x[i] = Math.floor(Math.random() * 0x0100); + } + } + }; +} + +//protected +BigInteger$2.prototype.chunkSize = bnpChunkSize; +BigInteger$2.prototype.toRadix = bnpToRadix; +BigInteger$2.prototype.fromRadix = bnpFromRadix; +BigInteger$2.prototype.fromNumber = bnpFromNumber; +BigInteger$2.prototype.bitwiseTo = bnpBitwiseTo; +BigInteger$2.prototype.changeBit = bnpChangeBit; +BigInteger$2.prototype.addTo = bnpAddTo; +BigInteger$2.prototype.dMultiply = bnpDMultiply; +BigInteger$2.prototype.dAddOffset = bnpDAddOffset; +BigInteger$2.prototype.multiplyLowerTo = bnpMultiplyLowerTo; +BigInteger$2.prototype.multiplyUpperTo = bnpMultiplyUpperTo; +BigInteger$2.prototype.modInt = bnpModInt; +BigInteger$2.prototype.millerRabin = bnpMillerRabin; + +//public +BigInteger$2.prototype.clone = bnClone; +BigInteger$2.prototype.intValue = bnIntValue; +BigInteger$2.prototype.byteValue = bnByteValue; +BigInteger$2.prototype.shortValue = bnShortValue; +BigInteger$2.prototype.signum = bnSigNum; +BigInteger$2.prototype.toByteArray = bnToByteArray; +BigInteger$2.prototype.equals = bnEquals; +BigInteger$2.prototype.min = bnMin; +BigInteger$2.prototype.max = bnMax; +BigInteger$2.prototype.and = bnAnd; +BigInteger$2.prototype.or = bnOr; +BigInteger$2.prototype.xor = bnXor; +BigInteger$2.prototype.andNot = bnAndNot; +BigInteger$2.prototype.not = bnNot; +BigInteger$2.prototype.shiftLeft = bnShiftLeft; +BigInteger$2.prototype.shiftRight = bnShiftRight; +BigInteger$2.prototype.getLowestSetBit = bnGetLowestSetBit; +BigInteger$2.prototype.bitCount = bnBitCount; +BigInteger$2.prototype.testBit = bnTestBit; +BigInteger$2.prototype.setBit = bnSetBit; +BigInteger$2.prototype.clearBit = bnClearBit; +BigInteger$2.prototype.flipBit = bnFlipBit; +BigInteger$2.prototype.add = bnAdd; +BigInteger$2.prototype.subtract = bnSubtract; +BigInteger$2.prototype.multiply = bnMultiply; +BigInteger$2.prototype.divide = bnDivide; +BigInteger$2.prototype.remainder = bnRemainder; +BigInteger$2.prototype.divideAndRemainder = bnDivideAndRemainder; +BigInteger$2.prototype.modPow = bnModPow; +BigInteger$2.prototype.modInverse = bnModInverse; +BigInteger$2.prototype.pow = bnPow; +BigInteger$2.prototype.gcd = bnGCD; +BigInteger$2.prototype.isProbablePrime = bnIsProbablePrime; + +/** + * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + */ + +var forge$n = forge$F; + + + +var sha1 = forge$n.sha1 = forge$n.sha1 || {}; +forge$n.md.sha1 = forge$n.md.algorithms.sha1 = sha1; + +/** + * Creates a SHA-1 message digest object. + * + * @return a message digest object. + */ +sha1.create = function() { + // do initialization as necessary + if(!_initialized$1) { + _init$1(); + } + + // SHA-1 state contains five 32-bit integers + var _state = null; + + // input buffer + var _input = forge$n.util.createBuffer(); + + // used for word storage + var _w = new Array(80); + + // message digest object + var md = { + algorithm: 'sha1', + blockLength: 64, + digestLength: 20, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge$n.util.createBuffer(); + _state = { + h0: 0x67452301, + h1: 0xEFCDAB89, + h2: 0x98BADCFE, + h3: 0x10325476, + h4: 0xC3D2E1F0 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge$n.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update$1(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-1 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge$n.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding$1.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4 + }; + _update$1(s2, _w, finalBlock); + var rval = forge$n.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + return rval; + }; + + return md; +}; + +// sha-1 padding bytes not initialized yet +var _padding$1 = null; +var _initialized$1 = false; + +/** + * Initializes the constant tables. + */ +function _init$1() { + // create padding + _padding$1 = String.fromCharCode(128); + _padding$1 += forge$n.util.fillString(String.fromCharCode(0x00), 64); + + // now initialized + _initialized$1 = true; +} + +/** + * Updates a SHA-1 state with the given byte buffer. + * + * @param s the SHA-1 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update$1(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t, a, b, c, d, e, f, i; + var len = bytes.length(); + while(len >= 64) { + // the w array will be populated with sixteen 32-bit big-endian words + // and then extended into 80 32-bit words according to SHA-1 algorithm + // and for 32-79 using Max Locktyukhin's optimization + + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + + // round 1 + for(i = 0; i < 16; ++i) { + t = bytes.getInt32(); + w[i] = t; + f = d ^ (b & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + for(; i < 20; ++i) { + t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); + t = (t << 1) | (t >>> 31); + w[i] = t; + f = d ^ (b & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 2 + for(; i < 32; ++i) { + t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); + t = (t << 1) | (t >>> 31); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + for(; i < 40; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 3 + for(; i < 60; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = (b & c) | (d & (b ^ c)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 4 + for(; i < 80; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + + len -= 64; + } +} + +/** + * Partial implementation of PKCS#1 v2.2: RSA-OEAP + * + * Modified but based on the following MIT and BSD licensed code: + * + * https://github.com/kjur/jsjws/blob/master/rsa.js: + * + * The 'jsjws'(JSON Web Signature JavaScript Library) License + * + * Copyright (c) 2012 Kenji Urushima + * + * 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. + * + * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain: + * + * RSAES-OAEP.js + * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $ + * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002) + * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003. + * Contact: ellis@nukinetics.com + * Distributed under the BSD License. + * + * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125 + * + * @author Evan Jones (http://evanjones.ca/) + * @author Dave Longley + * + * Copyright (c) 2013-2014 Digital Bazaar, Inc. + */ + +var forge$m = forge$F; + + + + +// shortcut for PKCS#1 API +var pkcs1 = forge$m.pkcs1 = forge$m.pkcs1 || {}; + +/** + * Encode the given RSAES-OAEP message (M) using key, with optional label (L) + * and seed. + * + * This method does not perform RSA encryption, it only encodes the message + * using RSAES-OAEP. + * + * @param key the RSA key to use. + * @param message the message to encode. + * @param options the options to use: + * label an optional label to use. + * seed the seed to use. + * md the message digest object to use, undefined for SHA-1. + * mgf1 optional mgf1 parameters: + * md the message digest object to use for MGF1. + * + * @return the encoded message bytes. + */ +pkcs1.encode_rsa_oaep = function(key, message, options) { + // parse arguments + var label; + var seed; + var md; + var mgf1Md; + // legacy args (label, seed, md) + if(typeof options === 'string') { + label = options; + seed = arguments[3] || undefined; + md = arguments[4] || undefined; + } else if(options) { + label = options.label || undefined; + seed = options.seed || undefined; + md = options.md || undefined; + if(options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + + // default OAEP to SHA-1 message digest + if(!md) { + md = forge$m.md.sha1.create(); + } else { + md.start(); + } + + // default MGF-1 to same as OAEP + if(!mgf1Md) { + mgf1Md = md; + } + + // compute length in bytes and check output + var keyLength = Math.ceil(key.n.bitLength() / 8); + var maxLength = keyLength - 2 * md.digestLength - 2; + if(message.length > maxLength) { + var error = new Error('RSAES-OAEP input message length is too long.'); + error.length = message.length; + error.maxLength = maxLength; + throw error; + } + + if(!label) { + label = ''; + } + md.update(label, 'raw'); + var lHash = md.digest(); + + var PS = ''; + var PS_length = maxLength - message.length; + for(var i = 0; i < PS_length; i++) { + PS += '\x00'; + } + + var DB = lHash.getBytes() + PS + '\x01' + message; + + if(!seed) { + seed = forge$m.random.getBytes(md.digestLength); + } else if(seed.length !== md.digestLength) { + var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' + + 'match the digest length.'); + error.seedLength = seed.length; + error.digestLength = md.digestLength; + throw error; + } + + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var maskedDB = forge$m.util.xorBytes(DB, dbMask, DB.length); + + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var maskedSeed = forge$m.util.xorBytes(seed, seedMask, seed.length); + + // return encoded message + return '\x00' + maskedSeed + maskedDB; +}; + +/** + * Decode the given RSAES-OAEP encoded message (EM) using key, with optional + * label (L). + * + * This method does not perform RSA decryption, it only decodes the message + * using RSAES-OAEP. + * + * @param key the RSA key to use. + * @param em the encoded message to decode. + * @param options the options to use: + * label an optional label to use. + * md the message digest object to use for OAEP, undefined for SHA-1. + * mgf1 optional mgf1 parameters: + * md the message digest object to use for MGF1. + * + * @return the decoded message bytes. + */ +pkcs1.decode_rsa_oaep = function(key, em, options) { + // parse args + var label; + var md; + var mgf1Md; + // legacy args + if(typeof options === 'string') { + label = options; + md = arguments[3] || undefined; + } else if(options) { + label = options.label || undefined; + md = options.md || undefined; + if(options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + + // compute length in bytes + var keyLength = Math.ceil(key.n.bitLength() / 8); + + if(em.length !== keyLength) { + var error = new Error('RSAES-OAEP encoded message length is invalid.'); + error.length = em.length; + error.expectedLength = keyLength; + throw error; + } + + // default OAEP to SHA-1 message digest + if(md === undefined) { + md = forge$m.md.sha1.create(); + } else { + md.start(); + } + + // default MGF-1 to same as OAEP + if(!mgf1Md) { + mgf1Md = md; + } + + if(keyLength < 2 * md.digestLength + 2) { + throw new Error('RSAES-OAEP key is too short for the hash function.'); + } + + if(!label) { + label = ''; + } + md.update(label, 'raw'); + var lHash = md.digest().getBytes(); + + // split the message into its parts + var y = em.charAt(0); + var maskedSeed = em.substring(1, md.digestLength + 1); + var maskedDB = em.substring(1 + md.digestLength); + + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var seed = forge$m.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); + + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var db = forge$m.util.xorBytes(maskedDB, dbMask, maskedDB.length); + + var lHashPrime = db.substring(0, md.digestLength); + + // constant time check that all values match what is expected + var error = (y !== '\x00'); + + // constant time check lHash vs lHashPrime + for(var i = 0; i < md.digestLength; ++i) { + error |= (lHash.charAt(i) !== lHashPrime.charAt(i)); + } + + // "constant time" find the 0x1 byte separating the padding (zeros) from the + // message + // TODO: It must be possible to do this in a better/smarter way? + var in_ps = 1; + var index = md.digestLength; + for(var j = md.digestLength; j < db.length; j++) { + var code = db.charCodeAt(j); + + var is_0 = (code & 0x1) ^ 0x1; + + // non-zero if not 0 or 1 in the ps section + var error_mask = in_ps ? 0xfffe : 0x0000; + error |= (code & error_mask); + + // latch in_ps to zero after we find 0x1 + in_ps = in_ps & is_0; + index += in_ps; + } + + if(error || db.charCodeAt(index) !== 0x1) { + throw new Error('Invalid RSAES-OAEP padding.'); + } + + return db.substring(index + 1); +}; + +function rsa_mgf1(seed, maskLength, hash) { + // default to SHA-1 message digest + if(!hash) { + hash = forge$m.md.sha1.create(); + } + var t = ''; + var count = Math.ceil(maskLength / hash.digestLength); + for(var i = 0; i < count; ++i) { + var c = String.fromCharCode( + (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF); + hash.start(); + hash.update(seed + c); + t += hash.digest().getBytes(); + } + return t.substring(0, maskLength); +} + +/** + * Prime number generation API. + * + * @author Dave Longley + * + * Copyright (c) 2014 Digital Bazaar, Inc. + */ + +var forge$l = forge$F; + + + + +(function() { + +// forge.prime already defined +if(forge$l.prime) { + return; +} + +/* PRIME API */ +var prime = forge$l.prime = forge$l.prime || {}; + +var BigInteger = forge$l.jsbn.BigInteger; + +// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 +var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; +var THIRTY = new BigInteger(null); +THIRTY.fromInt(30); +var op_or = function(x, y) {return x|y;}; + +/** + * Generates a random probable prime with the given number of bits. + * + * Alternative algorithms can be specified by name as a string or as an + * object with custom options like so: + * + * { + * name: 'PRIMEINC', + * options: { + * maxBlockTime: , + * millerRabinTests: , + * workerScript: , + * workers: . + * workLoad: the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * } + * } + * + * @param bits the number of bits for the prime number. + * @param options the options to use. + * [algorithm] the algorithm to use (default: 'PRIMEINC'). + * [prng] a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + * + * @return callback(err, num) called once the operation completes. + */ +prime.generateProbablePrime = function(bits, options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + // default to PRIMEINC algorithm + var algorithm = options.algorithm || 'PRIMEINC'; + if(typeof algorithm === 'string') { + algorithm = {name: algorithm}; + } + algorithm.options = algorithm.options || {}; + + // create prng with api that matches BigInteger secure random + var prng = options.prng || forge$l.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for(var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; + + if(algorithm.name === 'PRIMEINC') { + return primeincFindPrime(bits, rng, algorithm.options, callback); + } + + throw new Error('Invalid prime generation algorithm: ' + algorithm.name); +}; + +function primeincFindPrime(bits, rng, options, callback) { + if('workers' in options) { + return primeincFindPrimeWithWorkers(bits, rng, options, callback); + } + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); +} + +function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { + // initialize random number + var num = generateRandom(bits, rng); + + /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The + number we are given is always aligned at 30k + 1. Each time the number is + determined not to be prime we add to get to the next 'i', eg: if the number + was at 30k + 1 we add 6. */ + var deltaIdx = 0; + + // get required number of MR tests + var mrTests = getMillerRabinTests(num.bitLength()); + if('millerRabinTests' in options) { + mrTests = options.millerRabinTests; + } + + // find prime nearest to 'num' for maxBlockTime ms + // 10 ms gives 5ms of leeway for other calculations before dropping + // below 60fps (1000/60 == 16.67), but in reality, the number will + // likely be higher due to an 'atomic' big int modPow + var maxBlockTime = 10; + if('maxBlockTime' in options) { + maxBlockTime = options.maxBlockTime; + } + + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); +} + +function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { + var start = +new Date(); + do { + // overflow, regenerate random number + if(num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + // do primality test + if(num.isProbablePrime(mrTests)) { + return callback(null, num); + } + // get next potential prime + num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime)); + + // keep trying later + forge$l.util.setImmediate(function() { + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + }); +} + +// NOTE: This algorithm is indeterminate in nature because workers +// run in parallel looking at different segments of numbers. Even if this +// algorithm is run twice with the same input from a predictable RNG, it +// may produce different outputs. +function primeincFindPrimeWithWorkers(bits, rng, options, callback) { + // web workers unavailable + if(typeof Worker === 'undefined') { + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + } + + // initialize random number + var num = generateRandom(bits, rng); + + // use web workers to generate keys + var numWorkers = options.workers; + var workLoad = options.workLoad || 100; + var range = workLoad * 30 / 8; + var workerScript = options.workerScript || 'forge/prime.worker.js'; + if(numWorkers === -1) { + return forge$l.util.estimateCores(function(err, cores) { + if(err) { + // default to 2 + cores = 2; + } + numWorkers = cores - 1; + generate(); + }); + } + generate(); + + function generate() { + // require at least 1 worker + numWorkers = Math.max(1, numWorkers); + + // TODO: consider optimizing by starting workers outside getPrime() ... + // note that in order to clean up they will have to be made internally + // asynchronous which may actually be slower + + // start workers immediately + var workers = []; + for(var i = 0; i < numWorkers; ++i) { + // FIXME: fix path or use blob URLs + workers[i] = new Worker(workerScript); + } + + // listen for requests from workers and assign ranges to find prime + for(var i = 0; i < numWorkers; ++i) { + workers[i].addEventListener('message', workerMessage); + } + + /* Note: The distribution of random numbers is unknown. Therefore, each + web worker is continuously allocated a range of numbers to check for a + random number until one is found. + + Every 30 numbers will be checked just 8 times, because prime numbers + have the form: + + 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this) + + Therefore, if we want a web worker to run N checks before asking for + a new range of numbers, each range must contain N*30/8 numbers. + + For 100 checks (workLoad), this is a range of 375. */ + + var found = false; + function workerMessage(e) { + // ignore message, prime already found + if(found) { + return; + } + var data = e.data; + if(data.found) { + // terminate all workers + for(var i = 0; i < workers.length; ++i) { + workers[i].terminate(); + } + found = true; + return callback(null, new BigInteger(data.prime, 16)); + } + + // overflow, regenerate random number + if(num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + + // assign new range to check + var hex = num.toString(16); + + // start prime search + e.target.postMessage({ + hex: hex, + workLoad: workLoad + }); + + num.dAddOffset(range, 0); + } + } +} + +/** + * Generates a random number using the given number of bits and RNG. + * + * @param bits the number of bits for the number. + * @param rng the random number generator to use. + * + * @return the random number. + */ +function generateRandom(bits, rng) { + var num = new BigInteger(bits, rng); + // force MSB set + var bits1 = bits - 1; + if(!num.testBit(bits1)) { + num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); + } + // align number on 30k+1 boundary + num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); + return num; +} + +/** + * Returns the required number of Miller-Rabin tests to generate a + * prime with an error probability of (1/2)^80. + * + * See Handbook of Applied Cryptography Chapter 4, Table 4.4. + * + * @param bits the bit size. + * + * @return the required number of iterations. + */ +function getMillerRabinTests(bits) { + if(bits <= 100) return 27; + if(bits <= 150) return 18; + if(bits <= 200) return 15; + if(bits <= 250) return 12; + if(bits <= 300) return 9; + if(bits <= 350) return 8; + if(bits <= 400) return 7; + if(bits <= 500) return 6; + if(bits <= 600) return 5; + if(bits <= 800) return 4; + if(bits <= 1250) return 3; + return 2; +} + +})(); + +/** + * Javascript implementation of basic RSA algorithms. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * + * The only algorithm currently supported for PKI is RSA. + * + * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo + * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier + * and a subjectPublicKey of type bit string. + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of RSA, there aren't any. + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING + * } + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * For an RSA public key, the subjectPublicKey is: + * + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER -- e + * } + * + * PrivateKeyInfo ::= SEQUENCE { + * version Version, + * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, + * privateKey PrivateKey, + * attributes [0] IMPLICIT Attributes OPTIONAL + * } + * + * Version ::= INTEGER + * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier + * PrivateKey ::= OCTET STRING + * Attributes ::= SET OF Attribute + * + * An RSA private key as the following structure: + * + * RSAPrivateKey ::= SEQUENCE { + * version Version, + * modulus INTEGER, -- n + * publicExponent INTEGER, -- e + * privateExponent INTEGER, -- d + * prime1 INTEGER, -- p + * prime2 INTEGER, -- q + * exponent1 INTEGER, -- d mod (p-1) + * exponent2 INTEGER, -- d mod (q-1) + * coefficient INTEGER -- (inverse of q) mod p + * } + * + * Version ::= INTEGER + * + * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1 + */ + +var forge$k = forge$F; + + + + + + + + +if(typeof BigInteger$1 === 'undefined') { + var BigInteger$1 = forge$k.jsbn.BigInteger; +} + +var _crypto = forge$k.util.isNodejs ? require$$1__default : null; + +// shortcut for asn.1 API +var asn1$7 = forge$k.asn1; + +// shortcut for util API +var util = forge$k.util; + +/* + * RSA encryption and decryption, see RFC 2313. + */ +forge$k.pki = forge$k.pki || {}; +forge$k.pki.rsa = forge$k.rsa = forge$k.rsa || {}; +var pki$4 = forge$k.pki; + +// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 +var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + +// validator for a PrivateKeyInfo structure +var privateKeyValidator$1 = { + // PrivateKeyInfo + name: 'PrivateKeyInfo', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'PrivateKeyInfo.version', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // privateKeyAlgorithm + name: 'PrivateKeyInfo.privateKeyAlgorithm', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.OID, + constructed: false, + capture: 'privateKeyOid' + }] + }, { + // PrivateKey + name: 'PrivateKeyInfo', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.OCTETSTRING, + constructed: false, + capture: 'privateKey' + }] +}; + +// validator for an RSA private key +var rsaPrivateKeyValidator = { + // RSAPrivateKey + name: 'RSAPrivateKey', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'RSAPrivateKey.version', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // modulus (n) + name: 'RSAPrivateKey.modulus', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'privateKeyModulus' + }, { + // publicExponent (e) + name: 'RSAPrivateKey.publicExponent', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'privateKeyPublicExponent' + }, { + // privateExponent (d) + name: 'RSAPrivateKey.privateExponent', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrivateExponent' + }, { + // prime1 (p) + name: 'RSAPrivateKey.prime1', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrime1' + }, { + // prime2 (q) + name: 'RSAPrivateKey.prime2', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrime2' + }, { + // exponent1 (d mod (p-1)) + name: 'RSAPrivateKey.exponent1', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'privateKeyExponent1' + }, { + // exponent2 (d mod (q-1)) + name: 'RSAPrivateKey.exponent2', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'privateKeyExponent2' + }, { + // coefficient ((inverse of q) mod p) + name: 'RSAPrivateKey.coefficient', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'privateKeyCoefficient' + }] +}; + +// validator for an RSA public key +var rsaPublicKeyValidator = { + // RSAPublicKey + name: 'RSAPublicKey', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.SEQUENCE, + constructed: true, + value: [{ + // modulus (n) + name: 'RSAPublicKey.modulus', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'publicKeyModulus' + }, { + // publicExponent (e) + name: 'RSAPublicKey.exponent', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.INTEGER, + constructed: false, + capture: 'publicKeyExponent' + }] +}; + +// validator for an SubjectPublicKeyInfo structure +// Note: Currently only works with an RSA public key +var publicKeyValidator$2 = forge$k.pki.rsa.publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [{ + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.OID, + constructed: false, + capture: 'publicKeyOid' + }] + }, { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1$7.Class.UNIVERSAL, + type: asn1$7.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + }] +}; + +/** + * Wrap digest in DigestInfo object. + * + * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447. + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * Digest ::= OCTET STRING + * + * @param md the message digest object with the hash to sign. + * + * @return the encoded message (ready for RSA encrytion) + */ +var emsaPkcs1v15encode = function(md) { + // get the oid for the algorithm + var oid; + if(md.algorithm in pki$4.oids) { + oid = pki$4.oids[md.algorithm]; + } else { + var error = new Error('Unknown message digest algorithm.'); + error.algorithm = md.algorithm; + throw error; + } + var oidBytes = asn1$7.oidToDer(oid).getBytes(); + + // create the digest info + var digestInfo = asn1$7.create( + asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, []); + var digestAlgorithm = asn1$7.create( + asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, []); + digestAlgorithm.value.push(asn1$7.create( + asn1$7.Class.UNIVERSAL, asn1$7.Type.OID, false, oidBytes)); + digestAlgorithm.value.push(asn1$7.create( + asn1$7.Class.UNIVERSAL, asn1$7.Type.NULL, false, '')); + var digest = asn1$7.create( + asn1$7.Class.UNIVERSAL, asn1$7.Type.OCTETSTRING, + false, md.digest().getBytes()); + digestInfo.value.push(digestAlgorithm); + digestInfo.value.push(digest); + + // encode digest info + return asn1$7.toDer(digestInfo).getBytes(); +}; + +/** + * Performs x^c mod n (RSA encryption or decryption operation). + * + * @param x the number to raise and mod. + * @param key the key to use. + * @param pub true if the key is public, false if private. + * + * @return the result of x^c mod n. + */ +var _modPow = function(x, key, pub) { + if(pub) { + return x.modPow(key.e, key.n); + } + + if(!key.p || !key.q) { + // allow calculation without CRT params (slow) + return x.modPow(key.d, key.n); + } + + // pre-compute dP, dQ, and qInv if necessary + if(!key.dP) { + key.dP = key.d.mod(key.p.subtract(BigInteger$1.ONE)); + } + if(!key.dQ) { + key.dQ = key.d.mod(key.q.subtract(BigInteger$1.ONE)); + } + if(!key.qInv) { + key.qInv = key.q.modInverse(key.p); + } + + /* Chinese remainder theorem (CRT) states: + + Suppose n1, n2, ..., nk are positive integers which are pairwise + coprime (n1 and n2 have no common factors other than 1). For any + integers x1, x2, ..., xk there exists an integer x solving the + system of simultaneous congruences (where ~= means modularly + congruent so a ~= b mod n means a mod n = b mod n): + + x ~= x1 mod n1 + x ~= x2 mod n2 + ... + x ~= xk mod nk + + This system of congruences has a single simultaneous solution x + between 0 and n - 1. Furthermore, each xk solution and x itself + is congruent modulo the product n = n1*n2*...*nk. + So x1 mod n = x2 mod n = xk mod n = x mod n. + + The single simultaneous solution x can be solved with the following + equation: + + x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni. + + Where x is less than n, xi = x mod ni. + + For RSA we are only concerned with k = 2. The modulus n = pq, where + p and q are coprime. The RSA decryption algorithm is: + + y = x^d mod n + + Given the above: + + x1 = x^d mod p + r1 = n/p = q + s1 = q^-1 mod p + x2 = x^d mod q + r2 = n/q = p + s2 = p^-1 mod q + + So y = (x1r1s1 + x2r2s2) mod n + = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n + + According to Fermat's Little Theorem, if the modulus P is prime, + for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P. + Since A is not divisible by P it follows that if: + N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore: + + A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort + to calculate). In order to calculate x^d mod p more quickly the + exponent d mod (p - 1) is stored in the RSA private key (the same + is done for x^d mod q). These values are referred to as dP and dQ + respectively. Therefore we now have: + + y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n + + Since we'll be reducing x^dP by modulo p (same for q) we can also + reduce x by p (and q respectively) before hand. Therefore, let + + xp = ((x mod p)^dP mod p), and + xq = ((x mod q)^dQ mod q), yielding: + + y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n + + This can be further reduced to a simple algorithm that only + requires 1 inverse (the q inverse is used) to be used and stored. + The algorithm is called Garner's algorithm. If qInv is the + inverse of q, we simply calculate: + + y = (qInv*(xp - xq) mod p) * q + xq + + However, there are two further complications. First, we need to + ensure that xp > xq to prevent signed BigIntegers from being used + so we add p until this is true (since we will be mod'ing with + p anyway). Then, there is a known timing attack on algorithms + using the CRT. To mitigate this risk, "cryptographic blinding" + should be used. This requires simply generating a random number r + between 0 and n-1 and its inverse and multiplying x by r^e before + calculating y and then multiplying y by r^-1 afterwards. Note that + r must be coprime with n (gcd(r, n) === 1) in order to have an + inverse. + */ + + // cryptographic blinding + var r; + do { + r = new BigInteger$1( + forge$k.util.bytesToHex(forge$k.random.getBytes(key.n.bitLength() / 8)), + 16); + } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger$1.ONE)); + x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); + + // calculate xp and xq + var xp = x.mod(key.p).modPow(key.dP, key.p); + var xq = x.mod(key.q).modPow(key.dQ, key.q); + + // xp must be larger than xq to avoid signed bit usage + while(xp.compareTo(xq) < 0) { + xp = xp.add(key.p); + } + + // do last step + var y = xp.subtract(xq) + .multiply(key.qInv).mod(key.p) + .multiply(key.q).add(xq); + + // remove effect of random for cryptographic blinding + y = y.multiply(r.modInverse(key.n)).mod(key.n); + + return y; +}; + +/** + * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or + * 'encrypt' on a public key object instead. + * + * Performs RSA encryption. + * + * The parameter bt controls whether to put padding bytes before the + * message passed in. Set bt to either true or false to disable padding + * completely (in order to handle e.g. EMSA-PSS encoding seperately before), + * signaling whether the encryption operation is a public key operation + * (i.e. encrypting data) or not, i.e. private key operation (data signing). + * + * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01 + * (for signing) or 0x02 (for encryption). The key operation mode (private + * or public) is derived from this flag in that case). + * + * @param m the message to encrypt as a byte string. + * @param key the RSA key to use. + * @param bt for PKCS#1 v1.5 padding, the block type to use + * (0x01 for private key, 0x02 for public), + * to disable padding: true = public key, false = private key. + * + * @return the encrypted bytes as a string. + */ +pki$4.rsa.encrypt = function(m, key, bt) { + var pub = bt; + var eb; + + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + if(bt !== false && bt !== true) { + // legacy, default to PKCS#1 v1.5 padding + pub = (bt === 0x02); + eb = _encodePkcs1_v1_5(m, key, bt); + } else { + eb = forge$k.util.createBuffer(); + eb.putBytes(m); + } + + // load encryption block as big integer 'x' + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var x = new BigInteger$1(eb.toHex(), 16); + + // do RSA encryption + var y = _modPow(x, key, pub); + + // convert y into the encrypted data byte string, if y is shorter in + // bytes than k, then prepend zero bytes to fill up ed + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var yhex = y.toString(16); + var ed = forge$k.util.createBuffer(); + var zeros = k - Math.ceil(yhex.length / 2); + while(zeros > 0) { + ed.putByte(0x00); + --zeros; + } + ed.putBytes(forge$k.util.hexToBytes(yhex)); + return ed.getBytes(); +}; + +/** + * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or + * 'verify' on a public key object instead. + * + * Performs RSA decryption. + * + * The parameter ml controls whether to apply PKCS#1 v1.5 padding + * or not. Set ml = false to disable padding removal completely + * (in order to handle e.g. EMSA-PSS later on) and simply pass back + * the RSA encryption block. + * + * @param ed the encrypted data to decrypt in as a byte string. + * @param key the RSA key to use. + * @param pub true for a public key operation, false for private. + * @param ml the message length, if known, false to disable padding. + * + * @return the decrypted message as a byte string. + */ +pki$4.rsa.decrypt = function(ed, key, pub, ml) { + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + // error if the length of the encrypted data ED is not k + if(ed.length !== k) { + var error = new Error('Encrypted message length is invalid.'); + error.length = ed.length; + error.expected = k; + throw error; + } + + // convert encrypted data into a big integer + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var y = new BigInteger$1(forge$k.util.createBuffer(ed).toHex(), 16); + + // y must be less than the modulus or it wasn't the result of + // a previous mod operation (encryption) using that modulus + if(y.compareTo(key.n) >= 0) { + throw new Error('Encrypted message is invalid.'); + } + + // do RSA decryption + var x = _modPow(y, key, pub); + + // create the encryption block, if x is shorter in bytes than k, then + // prepend zero bytes to fill up eb + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var xhex = x.toString(16); + var eb = forge$k.util.createBuffer(); + var zeros = k - Math.ceil(xhex.length / 2); + while(zeros > 0) { + eb.putByte(0x00); + --zeros; + } + eb.putBytes(forge$k.util.hexToBytes(xhex)); + + if(ml !== false) { + // legacy, default to PKCS#1 v1.5 padding + return _decodePkcs1_v1_5(eb.getBytes(), key, pub); + } + + // return message + return eb.getBytes(); +}; + +/** + * Creates an RSA key-pair generation state object. It is used to allow + * key-generation to be performed in steps. It also allows for a UI to + * display progress updates. + * + * @param bits the size for the private key in bits, defaults to 2048. + * @param e the public exponent to use, defaults to 65537 (0x10001). + * @param [options] the options to use. + * prng a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + * algorithm the algorithm to use (default: 'PRIMEINC'). + * + * @return the state object to use to generate the key-pair. + */ +pki$4.rsa.createKeyPairGenerationState = function(bits, e, options) { + // TODO: migrate step-based prime generation code to forge.prime + + // set default bits + if(typeof(bits) === 'string') { + bits = parseInt(bits, 10); + } + bits = bits || 2048; + + // create prng with api that matches BigInteger secure random + options = options || {}; + var prng = options.prng || forge$k.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for(var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; + + var algorithm = options.algorithm || 'PRIMEINC'; + + // create PRIMEINC algorithm state + var rval; + if(algorithm === 'PRIMEINC') { + rval = { + algorithm: algorithm, + state: 0, + bits: bits, + rng: rng, + eInt: e || 65537, + e: new BigInteger$1(null), + p: null, + q: null, + qBits: bits >> 1, + pBits: bits - (bits >> 1), + pqState: 0, + num: null, + keys: null + }; + rval.e.fromInt(rval.eInt); + } else { + throw new Error('Invalid key generation algorithm: ' + algorithm); + } + + return rval; +}; + +/** + * Attempts to runs the key-generation algorithm for at most n seconds + * (approximately) using the given state. When key-generation has completed, + * the keys will be stored in state.keys. + * + * To use this function to update a UI while generating a key or to prevent + * causing browser lockups/warnings, set "n" to a value other than 0. A + * simple pattern for generating a key and showing a progress indicator is: + * + * var state = pki.rsa.createKeyPairGenerationState(2048); + * var step = function() { + * // step key-generation, run algorithm for 100 ms, repeat + * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) { + * setTimeout(step, 1); + * } else { + * // key-generation complete + * // TODO: turn off progress indicator here + * // TODO: use the generated key-pair in "state.keys" + * } + * }; + * // TODO: turn on progress indicator here + * setTimeout(step, 0); + * + * @param state the state to use. + * @param n the maximum number of milliseconds to run the algorithm for, 0 + * to run the algorithm to completion. + * + * @return true if the key-generation completed, false if not. + */ +pki$4.rsa.stepKeyPairGenerationState = function(state, n) { + // set default algorithm if not set + if(!('algorithm' in state)) { + state.algorithm = 'PRIMEINC'; + } + + // TODO: migrate step-based prime generation code to forge.prime + // TODO: abstract as PRIMEINC algorithm + + // do key generation (based on Tom Wu's rsa.js, see jsbn.js license) + // with some minor optimizations and designed to run in steps + + // local state vars + var THIRTY = new BigInteger$1(null); + THIRTY.fromInt(30); + var deltaIdx = 0; + var op_or = function(x, y) {return x | y;}; + + // keep stepping until time limit is reached or done + var t1 = +new Date(); + var t2; + var total = 0; + while(state.keys === null && (n <= 0 || total < n)) { + // generate p or q + if(state.state === 0) { + /* Note: All primes are of the form: + + 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i + + When we generate a random number, we always align it at 30k + 1. Each + time the number is determined not to be prime we add to get to the + next 'i', eg: if the number was at 30k + 1 we add 6. */ + var bits = (state.p === null) ? state.pBits : state.qBits; + var bits1 = bits - 1; + + // get a random number + if(state.pqState === 0) { + state.num = new BigInteger$1(bits, state.rng); + // force MSB set + if(!state.num.testBit(bits1)) { + state.num.bitwiseTo( + BigInteger$1.ONE.shiftLeft(bits1), op_or, state.num); + } + // align number on 30k+1 boundary + state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); + deltaIdx = 0; + + ++state.pqState; + } else if(state.pqState === 1) { + // try to make the number a prime + if(state.num.bitLength() > bits) { + // overflow, try again + state.pqState = 0; + // do primality test + } else if(state.num.isProbablePrime( + _getMillerRabinTests(state.num.bitLength()))) { + ++state.pqState; + } else { + // get next potential prime + state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } + } else if(state.pqState === 2) { + // ensure number is coprime with e + state.pqState = + (state.num.subtract(BigInteger$1.ONE).gcd(state.e) + .compareTo(BigInteger$1.ONE) === 0) ? 3 : 0; + } else if(state.pqState === 3) { + // store p or q + state.pqState = 0; + if(state.p === null) { + state.p = state.num; + } else { + state.q = state.num; + } + + // advance state if both p and q are ready + if(state.p !== null && state.q !== null) { + ++state.state; + } + state.num = null; + } + } else if(state.state === 1) { + // ensure p is larger than q (swap them if not) + if(state.p.compareTo(state.q) < 0) { + state.num = state.p; + state.p = state.q; + state.q = state.num; + } + ++state.state; + } else if(state.state === 2) { + // compute phi: (p - 1)(q - 1) (Euler's totient function) + state.p1 = state.p.subtract(BigInteger$1.ONE); + state.q1 = state.q.subtract(BigInteger$1.ONE); + state.phi = state.p1.multiply(state.q1); + ++state.state; + } else if(state.state === 3) { + // ensure e and phi are coprime + if(state.phi.gcd(state.e).compareTo(BigInteger$1.ONE) === 0) { + // phi and e are coprime, advance + ++state.state; + } else { + // phi and e aren't coprime, so generate a new p and q + state.p = null; + state.q = null; + state.state = 0; + } + } else if(state.state === 4) { + // create n, ensure n is has the right number of bits + state.n = state.p.multiply(state.q); + + // ensure n is right number of bits + if(state.n.bitLength() === state.bits) { + // success, advance + ++state.state; + } else { + // failed, get new q + state.q = null; + state.state = 0; + } + } else if(state.state === 5) { + // set keys + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki$4.rsa.setPrivateKey( + state.n, state.e, d, state.p, state.q, + d.mod(state.p1), d.mod(state.q1), + state.q.modInverse(state.p)), + publicKey: pki$4.rsa.setPublicKey(state.n, state.e) + }; + } + + // update timing + t2 = +new Date(); + total += t2 - t1; + t1 = t2; + } + + return state.keys !== null; +}; + +/** + * Generates an RSA public-private key pair in a single call. + * + * To generate a key-pair in steps (to allow for progress updates and to + * prevent blocking or warnings in slow browsers) then use the key-pair + * generation state functions. + * + * To generate a key-pair asynchronously (either through web-workers, if + * available, or by breaking up the work on the main thread), pass a + * callback function. + * + * @param [bits] the size for the private key in bits, defaults to 2048. + * @param [e] the public exponent to use, defaults to 65537. + * @param [options] options for key-pair generation, if given then 'bits' + * and 'e' must *not* be given: + * bits the size for the private key in bits, (default: 2048). + * e the public exponent to use, (default: 65537 (0x10001)). + * workerScript the worker script URL. + * workers the number of web workers (if supported) to use, + * (default: 2). + * workLoad the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * prng a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". Disables use of native APIs. + * algorithm the algorithm to use (default: 'PRIMEINC'). + * @param [callback(err, keypair)] called once the operation completes. + * + * @return an object with privateKey and publicKey properties. + */ +pki$4.rsa.generateKeyPair = function(bits, e, options, callback) { + // (bits), (options), (callback) + if(arguments.length === 1) { + if(typeof bits === 'object') { + options = bits; + bits = undefined; + } else if(typeof bits === 'function') { + callback = bits; + bits = undefined; + } + } else if(arguments.length === 2) { + // (bits, e), (bits, options), (bits, callback), (options, callback) + if(typeof bits === 'number') { + if(typeof e === 'function') { + callback = e; + e = undefined; + } else if(typeof e !== 'number') { + options = e; + e = undefined; + } + } else { + options = bits; + callback = e; + bits = undefined; + e = undefined; + } + } else if(arguments.length === 3) { + // (bits, e, options), (bits, e, callback), (bits, options, callback) + if(typeof e === 'number') { + if(typeof options === 'function') { + callback = options; + options = undefined; + } + } else { + callback = options; + options = e; + e = undefined; + } + } + options = options || {}; + if(bits === undefined) { + bits = options.bits || 2048; + } + if(e === undefined) { + e = options.e || 0x10001; + } + + // use native code if permitted, available, and parameters are acceptable + if(!options.prng && + bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) { + if(callback) { + // try native async + if(_detectNodeCrypto('generateKeyPair')) { + return _crypto.generateKeyPair('rsa', { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: 'spki', + format: 'pem' + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem' + } + }, function(err, pub, priv) { + if(err) { + return callback(err); + } + callback(null, { + privateKey: pki$4.privateKeyFromPem(priv), + publicKey: pki$4.publicKeyFromPem(pub) + }); + }); + } + if(_detectSubtleCrypto('generateKey') && + _detectSubtleCrypto('exportKey')) { + // use standard native generateKey + return util.globalScope.crypto.subtle.generateKey({ + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: {name: 'SHA-256'} + }, true /* key can be exported*/, ['sign', 'verify']) + .then(function(pair) { + return util.globalScope.crypto.subtle.exportKey( + 'pkcs8', pair.privateKey); + // avoiding catch(function(err) {...}) to support IE <= 8 + }).then(undefined, function(err) { + callback(err); + }).then(function(pkcs8) { + if(pkcs8) { + var privateKey = pki$4.privateKeyFromAsn1( + asn1$7.fromDer(forge$k.util.createBuffer(pkcs8))); + callback(null, { + privateKey: privateKey, + publicKey: pki$4.setRsaPublicKey(privateKey.n, privateKey.e) + }); + } + }); + } + if(_detectSubtleMsCrypto('generateKey') && + _detectSubtleMsCrypto('exportKey')) { + var genOp = util.globalScope.msCrypto.subtle.generateKey({ + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: {name: 'SHA-256'} + }, true /* key can be exported*/, ['sign', 'verify']); + genOp.oncomplete = function(e) { + var pair = e.target.result; + var exportOp = util.globalScope.msCrypto.subtle.exportKey( + 'pkcs8', pair.privateKey); + exportOp.oncomplete = function(e) { + var pkcs8 = e.target.result; + var privateKey = pki$4.privateKeyFromAsn1( + asn1$7.fromDer(forge$k.util.createBuffer(pkcs8))); + callback(null, { + privateKey: privateKey, + publicKey: pki$4.setRsaPublicKey(privateKey.n, privateKey.e) + }); + }; + exportOp.onerror = function(err) { + callback(err); + }; + }; + genOp.onerror = function(err) { + callback(err); + }; + return; + } + } else { + // try native sync + if(_detectNodeCrypto('generateKeyPairSync')) { + var keypair = _crypto.generateKeyPairSync('rsa', { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: 'spki', + format: 'pem' + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem' + } + }); + return { + privateKey: pki$4.privateKeyFromPem(keypair.privateKey), + publicKey: pki$4.publicKeyFromPem(keypair.publicKey) + }; + } + } + } + + // use JavaScript implementation + var state = pki$4.rsa.createKeyPairGenerationState(bits, e, options); + if(!callback) { + pki$4.rsa.stepKeyPairGenerationState(state, 0); + return state.keys; + } + _generateKeyPair(state, options, callback); +}; + +/** + * Sets an RSA public key from BigIntegers modulus and exponent. + * + * @param n the modulus. + * @param e the exponent. + * + * @return the public key. + */ +pki$4.setRsaPublicKey = pki$4.rsa.setPublicKey = function(n, e) { + var key = { + n: n, + e: e + }; + + /** + * Encrypts the given data with this public key. Newer applications + * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for + * legacy applications. + * + * @param data the byte string to encrypt. + * @param scheme the encryption scheme to use: + * 'RSAES-PKCS1-V1_5' (default), + * 'RSA-OAEP', + * 'RAW', 'NONE', or null to perform raw RSA encryption, + * an object with an 'encode' property set to a function + * with the signature 'function(data, key)' that returns + * a binary-encoded string representing the encoded data. + * @param schemeOptions any scheme-specific options. + * + * @return the encrypted byte string. + */ + key.encrypt = function(data, scheme, schemeOptions) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSAES-PKCS1-V1_5'; + } + + if(scheme === 'RSAES-PKCS1-V1_5') { + scheme = { + encode: function(m, key, pub) { + return _encodePkcs1_v1_5(m, key, 0x02).getBytes(); + } + }; + } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { + scheme = { + encode: function(m, key) { + return forge$k.pkcs1.encode_rsa_oaep(key, m, schemeOptions); + } + }; + } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { + scheme = {encode: function(e) {return e;}}; + } else if(typeof scheme === 'string') { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } + + // do scheme-based encoding then rsa encryption + var e = scheme.encode(data, key, true); + return pki$4.rsa.encrypt(e, key, true); + }; + + /** + * Verifies the given signature against the given digest. + * + * PKCS#1 supports multiple (currently two) signature schemes: + * RSASSA-PKCS1-V1_5 and RSASSA-PSS. + * + * By default this implementation uses the "old scheme", i.e. + * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the + * signature is an OCTET STRING that holds a DigestInfo. + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * Digest ::= OCTET STRING + * + * To perform PSS signature verification, provide an instance + * of Forge PSS object as the scheme parameter. + * + * @param digest the message digest hash to compare against the signature, + * as a binary-encoded string. + * @param signature the signature to verify, as a binary-encoded string. + * @param scheme signature verification scheme to use: + * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, + * a Forge PSS object for RSASSA-PSS, + * 'NONE' or null for none, DigestInfo will not be expected, but + * PKCS#1 v1.5 padding will still be used. + * + * @return true if the signature was verified, false if not. + */ + key.verify = function(digest, signature, scheme) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSASSA-PKCS1-V1_5'; + } + + if(scheme === 'RSASSA-PKCS1-V1_5') { + scheme = { + verify: function(digest, d) { + // remove padding + d = _decodePkcs1_v1_5(d, key, true); + // d is ASN.1 BER-encoded DigestInfo + var obj = asn1$7.fromDer(d); + // compare the given digest to the decrypted one + return digest === obj.value[1].value; + } + }; + } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { + scheme = { + verify: function(digest, d) { + // remove padding + d = _decodePkcs1_v1_5(d, key, true); + return digest === d; + } + }; + } + + // do rsa decryption w/o any decoding, then verify -- which does decoding + var d = pki$4.rsa.decrypt(signature, key, true, false); + return scheme.verify(digest, d, key.n.bitLength()); + }; + + return key; +}; + +/** + * Sets an RSA private key from BigIntegers modulus, exponent, primes, + * prime exponents, and modular multiplicative inverse. + * + * @param n the modulus. + * @param e the public exponent. + * @param d the private exponent ((inverse of e) mod n). + * @param p the first prime. + * @param q the second prime. + * @param dP exponent1 (d mod (p-1)). + * @param dQ exponent2 (d mod (q-1)). + * @param qInv ((inverse of q) mod p) + * + * @return the private key. + */ +pki$4.setRsaPrivateKey = pki$4.rsa.setPrivateKey = function( + n, e, d, p, q, dP, dQ, qInv) { + var key = { + n: n, + e: e, + d: d, + p: p, + q: q, + dP: dP, + dQ: dQ, + qInv: qInv + }; + + /** + * Decrypts the given data with this private key. The decryption scheme + * must match the one used to encrypt the data. + * + * @param data the byte string to decrypt. + * @param scheme the decryption scheme to use: + * 'RSAES-PKCS1-V1_5' (default), + * 'RSA-OAEP', + * 'RAW', 'NONE', or null to perform raw RSA decryption. + * @param schemeOptions any scheme-specific options. + * + * @return the decrypted byte string. + */ + key.decrypt = function(data, scheme, schemeOptions) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSAES-PKCS1-V1_5'; + } + + // do rsa decryption w/o any decoding + var d = pki$4.rsa.decrypt(data, key, false, false); + + if(scheme === 'RSAES-PKCS1-V1_5') { + scheme = {decode: _decodePkcs1_v1_5}; + } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { + scheme = { + decode: function(d, key) { + return forge$k.pkcs1.decode_rsa_oaep(key, d, schemeOptions); + } + }; + } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { + scheme = {decode: function(d) {return d;}}; + } else { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } + + // decode according to scheme + return scheme.decode(d, key, false); + }; + + /** + * Signs the given digest, producing a signature. + * + * PKCS#1 supports multiple (currently two) signature schemes: + * RSASSA-PKCS1-V1_5 and RSASSA-PSS. + * + * By default this implementation uses the "old scheme", i.e. + * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide + * an instance of Forge PSS object as the scheme parameter. + * + * @param md the message digest object with the hash to sign. + * @param scheme the signature scheme to use: + * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, + * a Forge PSS object for RSASSA-PSS, + * 'NONE' or null for none, DigestInfo will not be used but + * PKCS#1 v1.5 padding will still be used. + * + * @return the signature as a byte string. + */ + key.sign = function(md, scheme) { + /* Note: The internal implementation of RSA operations is being + transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy + code like the use of an encoding block identifier 'bt' will eventually + be removed. */ + + // private key operation + var bt = false; + + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } + + if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') { + scheme = {encode: emsaPkcs1v15encode}; + bt = 0x01; + } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { + scheme = {encode: function() {return md;}}; + bt = 0x01; + } + + // encode and then encrypt + var d = scheme.encode(md, key.n.bitLength()); + return pki$4.rsa.encrypt(d, key, bt); + }; + + return key; +}; + +/** + * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object. + * + * @param rsaKey the ASN.1 RSAPrivateKey. + * + * @return the ASN.1 PrivateKeyInfo. + */ +pki$4.wrapRsaPrivateKey = function(rsaKey) { + // PrivateKeyInfo + return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ + // version (0) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + asn1$7.integerToDer(0).getBytes()), + // privateKeyAlgorithm + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ + asn1$7.create( + asn1$7.Class.UNIVERSAL, asn1$7.Type.OID, false, + asn1$7.oidToDer(pki$4.oids.rsaEncryption).getBytes()), + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.NULL, false, '') + ]), + // PrivateKey + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.OCTETSTRING, false, + asn1$7.toDer(rsaKey).getBytes()) + ]); +}; + +/** + * Converts a private key from an ASN.1 object. + * + * @param obj the ASN.1 representation of a PrivateKeyInfo containing an + * RSAPrivateKey or an RSAPrivateKey. + * + * @return the private key. + */ +pki$4.privateKeyFromAsn1 = function(obj) { + // get PrivateKeyInfo + var capture = {}; + var errors = []; + if(asn1$7.validate(obj, privateKeyValidator$1, capture, errors)) { + obj = asn1$7.fromDer(forge$k.util.createBuffer(capture.privateKey)); + } + + // get RSAPrivateKey + capture = {}; + errors = []; + if(!asn1$7.validate(obj, rsaPrivateKeyValidator, capture, errors)) { + var error = new Error('Cannot read private key. ' + + 'ASN.1 object does not contain an RSAPrivateKey.'); + error.errors = errors; + throw error; + } + + // Note: Version is currently ignored. + // capture.privateKeyVersion + // FIXME: inefficient, get a BigInteger that uses byte strings + var n, e, d, p, q, dP, dQ, qInv; + n = forge$k.util.createBuffer(capture.privateKeyModulus).toHex(); + e = forge$k.util.createBuffer(capture.privateKeyPublicExponent).toHex(); + d = forge$k.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); + p = forge$k.util.createBuffer(capture.privateKeyPrime1).toHex(); + q = forge$k.util.createBuffer(capture.privateKeyPrime2).toHex(); + dP = forge$k.util.createBuffer(capture.privateKeyExponent1).toHex(); + dQ = forge$k.util.createBuffer(capture.privateKeyExponent2).toHex(); + qInv = forge$k.util.createBuffer(capture.privateKeyCoefficient).toHex(); + + // set private key + return pki$4.setRsaPrivateKey( + new BigInteger$1(n, 16), + new BigInteger$1(e, 16), + new BigInteger$1(d, 16), + new BigInteger$1(p, 16), + new BigInteger$1(q, 16), + new BigInteger$1(dP, 16), + new BigInteger$1(dQ, 16), + new BigInteger$1(qInv, 16)); +}; + +/** + * Converts a private key to an ASN.1 RSAPrivateKey. + * + * @param key the private key. + * + * @return the ASN.1 representation of an RSAPrivateKey. + */ +pki$4.privateKeyToAsn1 = pki$4.privateKeyToRSAPrivateKey = function(key) { + // RSAPrivateKey + return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ + // version (0 = only 2 primes, 1 multiple primes) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + asn1$7.integerToDer(0).getBytes()), + // modulus (n) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + _bnToBytes(key.n)), + // publicExponent (e) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + _bnToBytes(key.e)), + // privateExponent (d) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + _bnToBytes(key.d)), + // privateKeyPrime1 (p) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + _bnToBytes(key.p)), + // privateKeyPrime2 (q) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + _bnToBytes(key.q)), + // privateKeyExponent1 (dP) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + _bnToBytes(key.dP)), + // privateKeyExponent2 (dQ) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + _bnToBytes(key.dQ)), + // coefficient (qInv) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + _bnToBytes(key.qInv)) + ]); +}; + +/** + * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey. + * + * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey. + * + * @return the public key. + */ +pki$4.publicKeyFromAsn1 = function(obj) { + // get SubjectPublicKeyInfo + var capture = {}; + var errors = []; + if(asn1$7.validate(obj, publicKeyValidator$2, capture, errors)) { + // get oid + var oid = asn1$7.derToOid(capture.publicKeyOid); + if(oid !== pki$4.oids.rsaEncryption) { + var error = new Error('Cannot read public key. Unknown OID.'); + error.oid = oid; + throw error; + } + obj = capture.rsaPublicKey; + } + + // get RSA params + errors = []; + if(!asn1$7.validate(obj, rsaPublicKeyValidator, capture, errors)) { + var error = new Error('Cannot read public key. ' + + 'ASN.1 object does not contain an RSAPublicKey.'); + error.errors = errors; + throw error; + } + + // FIXME: inefficient, get a BigInteger that uses byte strings + var n = forge$k.util.createBuffer(capture.publicKeyModulus).toHex(); + var e = forge$k.util.createBuffer(capture.publicKeyExponent).toHex(); + + // set public key + return pki$4.setRsaPublicKey( + new BigInteger$1(n, 16), + new BigInteger$1(e, 16)); +}; + +/** + * Converts a public key to an ASN.1 SubjectPublicKeyInfo. + * + * @param key the public key. + * + * @return the asn1 representation of a SubjectPublicKeyInfo. + */ +pki$4.publicKeyToAsn1 = pki$4.publicKeyToSubjectPublicKeyInfo = function(key) { + // SubjectPublicKeyInfo + return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ + // AlgorithmIdentifier + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ + // algorithm + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.OID, false, + asn1$7.oidToDer(pki$4.oids.rsaEncryption).getBytes()), + // parameters (null) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.NULL, false, '') + ]), + // subjectPublicKey + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.BITSTRING, false, [ + pki$4.publicKeyToRSAPublicKey(key) + ]) + ]); +}; + +/** + * Converts a public key to an ASN.1 RSAPublicKey. + * + * @param key the public key. + * + * @return the asn1 representation of a RSAPublicKey. + */ +pki$4.publicKeyToRSAPublicKey = function(key) { + // RSAPublicKey + return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ + // modulus (n) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + _bnToBytes(key.n)), + // publicExponent (e) + asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, + _bnToBytes(key.e)) + ]); +}; + +/** + * Encodes a message using PKCS#1 v1.5 padding. + * + * @param m the message to encode. + * @param key the RSA key to use. + * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02 + * (for encryption). + * + * @return the padded byte buffer. + */ +function _encodePkcs1_v1_5(m, key, bt) { + var eb = forge$k.util.createBuffer(); + + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + /* use PKCS#1 v1.5 padding */ + if(m.length > (k - 11)) { + var error = new Error('Message is too long for PKCS#1 v1.5 padding.'); + error.length = m.length; + error.max = k - 11; + throw error; + } + + /* A block type BT, a padding string PS, and the data D shall be + formatted into an octet string EB, the encryption block: + + EB = 00 || BT || PS || 00 || D + + The block type BT shall be a single octet indicating the structure of + the encryption block. For this version of the document it shall have + value 00, 01, or 02. For a private-key operation, the block type + shall be 00 or 01. For a public-key operation, it shall be 02. + + The padding string PS shall consist of k-3-||D|| octets. For block + type 00, the octets shall have value 00; for block type 01, they + shall have value FF; and for block type 02, they shall be + pseudorandomly generated and nonzero. This makes the length of the + encryption block EB equal to k. */ + + // build the encryption block + eb.putByte(0x00); + eb.putByte(bt); + + // create the padding + var padNum = k - 3 - m.length; + var padByte; + // private key op + if(bt === 0x00 || bt === 0x01) { + padByte = (bt === 0x00) ? 0x00 : 0xFF; + for(var i = 0; i < padNum; ++i) { + eb.putByte(padByte); + } + } else { + // public key op + // pad with random non-zero values + while(padNum > 0) { + var numZeros = 0; + var padBytes = forge$k.random.getBytes(padNum); + for(var i = 0; i < padNum; ++i) { + padByte = padBytes.charCodeAt(i); + if(padByte === 0) { + ++numZeros; + } else { + eb.putByte(padByte); + } + } + padNum = numZeros; + } + } + + // zero followed by message + eb.putByte(0x00); + eb.putBytes(m); + + return eb; +} + +/** + * Decodes a message using PKCS#1 v1.5 padding. + * + * @param em the message to decode. + * @param key the RSA key to use. + * @param pub true if the key is a public key, false if it is private. + * @param ml the message length, if specified. + * + * @return the decoded bytes. + */ +function _decodePkcs1_v1_5(em, key, pub, ml) { + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + /* It is an error if any of the following conditions occurs: + + 1. The encryption block EB cannot be parsed unambiguously. + 2. The padding string PS consists of fewer than eight octets + or is inconsisent with the block type BT. + 3. The decryption process is a public-key operation and the block + type BT is not 00 or 01, or the decryption process is a + private-key operation and the block type is not 02. + */ + + // parse the encryption block + var eb = forge$k.util.createBuffer(em); + var first = eb.getByte(); + var bt = eb.getByte(); + if(first !== 0x00 || + (pub && bt !== 0x00 && bt !== 0x01) || + (!pub && bt != 0x02) || + (pub && bt === 0x00 && typeof(ml) === 'undefined')) { + throw new Error('Encryption block is invalid.'); + } + + var padNum = 0; + if(bt === 0x00) { + // check all padding bytes for 0x00 + padNum = k - 3 - ml; + for(var i = 0; i < padNum; ++i) { + if(eb.getByte() !== 0x00) { + throw new Error('Encryption block is invalid.'); + } + } + } else if(bt === 0x01) { + // find the first byte that isn't 0xFF, should be after all padding + padNum = 0; + while(eb.length() > 1) { + if(eb.getByte() !== 0xFF) { + --eb.read; + break; + } + ++padNum; + } + } else if(bt === 0x02) { + // look for 0x00 byte + padNum = 0; + while(eb.length() > 1) { + if(eb.getByte() === 0x00) { + --eb.read; + break; + } + ++padNum; + } + } + + // zero must be 0x00 and padNum must be (k - 3 - message length) + var zero = eb.getByte(); + if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) { + throw new Error('Encryption block is invalid.'); + } + + return eb.getBytes(); +} + +/** + * Runs the key-generation algorithm asynchronously, either in the background + * via Web Workers, or using the main thread and setImmediate. + * + * @param state the key-pair generation state. + * @param [options] options for key-pair generation: + * workerScript the worker script URL. + * workers the number of web workers (if supported) to use, + * (default: 2, -1 to use estimated cores minus one). + * workLoad the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * @param callback(err, keypair) called once the operation completes. + */ +function _generateKeyPair(state, options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + var opts = { + algorithm: { + name: options.algorithm || 'PRIMEINC', + options: { + workers: options.workers || 2, + workLoad: options.workLoad || 100, + workerScript: options.workerScript + } + } + }; + if('prng' in options) { + opts.prng = options.prng; + } + + generate(); + + function generate() { + // find p and then q (done in series to simplify) + getPrime(state.pBits, function(err, num) { + if(err) { + return callback(err); + } + state.p = num; + if(state.q !== null) { + return finish(err, state.q); + } + getPrime(state.qBits, finish); + }); + } + + function getPrime(bits, callback) { + forge$k.prime.generateProbablePrime(bits, opts, callback); + } + + function finish(err, num) { + if(err) { + return callback(err); + } + + // set q + state.q = num; + + // ensure p is larger than q (swap them if not) + if(state.p.compareTo(state.q) < 0) { + var tmp = state.p; + state.p = state.q; + state.q = tmp; + } + + // ensure p is coprime with e + if(state.p.subtract(BigInteger$1.ONE).gcd(state.e) + .compareTo(BigInteger$1.ONE) !== 0) { + state.p = null; + generate(); + return; + } + + // ensure q is coprime with e + if(state.q.subtract(BigInteger$1.ONE).gcd(state.e) + .compareTo(BigInteger$1.ONE) !== 0) { + state.q = null; + getPrime(state.qBits, finish); + return; + } + + // compute phi: (p - 1)(q - 1) (Euler's totient function) + state.p1 = state.p.subtract(BigInteger$1.ONE); + state.q1 = state.q.subtract(BigInteger$1.ONE); + state.phi = state.p1.multiply(state.q1); + + // ensure e and phi are coprime + if(state.phi.gcd(state.e).compareTo(BigInteger$1.ONE) !== 0) { + // phi and e aren't coprime, so generate a new p and q + state.p = state.q = null; + generate(); + return; + } + + // create n, ensure n is has the right number of bits + state.n = state.p.multiply(state.q); + if(state.n.bitLength() !== state.bits) { + // failed, get new q + state.q = null; + getPrime(state.qBits, finish); + return; + } + + // set keys + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki$4.rsa.setPrivateKey( + state.n, state.e, d, state.p, state.q, + d.mod(state.p1), d.mod(state.q1), + state.q.modInverse(state.p)), + publicKey: pki$4.rsa.setPublicKey(state.n, state.e) + }; + + callback(null, state.keys); + } +} + +/** + * Converts a positive BigInteger into 2's-complement big-endian bytes. + * + * @param b the big integer to convert. + * + * @return the bytes. + */ +function _bnToBytes(b) { + // prepend 0x00 if first byte >= 0x80 + var hex = b.toString(16); + if(hex[0] >= '8') { + hex = '00' + hex; + } + var bytes = forge$k.util.hexToBytes(hex); + + // ensure integer is minimally-encoded + if(bytes.length > 1 && + // leading 0x00 for positive integer + ((bytes.charCodeAt(0) === 0 && + (bytes.charCodeAt(1) & 0x80) === 0) || + // leading 0xFF for negative integer + (bytes.charCodeAt(0) === 0xFF && + (bytes.charCodeAt(1) & 0x80) === 0x80))) { + return bytes.substr(1); + } + return bytes; +} + +/** + * Returns the required number of Miller-Rabin tests to generate a + * prime with an error probability of (1/2)^80. + * + * See Handbook of Applied Cryptography Chapter 4, Table 4.4. + * + * @param bits the bit size. + * + * @return the required number of iterations. + */ +function _getMillerRabinTests(bits) { + if(bits <= 100) return 27; + if(bits <= 150) return 18; + if(bits <= 200) return 15; + if(bits <= 250) return 12; + if(bits <= 300) return 9; + if(bits <= 350) return 8; + if(bits <= 400) return 7; + if(bits <= 500) return 6; + if(bits <= 600) return 5; + if(bits <= 800) return 4; + if(bits <= 1250) return 3; + return 2; +} + +/** + * Performs feature detection on the Node crypto interface. + * + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. + */ +function _detectNodeCrypto(fn) { + return forge$k.util.isNodejs && typeof _crypto[fn] === 'function'; +} + +/** + * Performs feature detection on the SubtleCrypto interface. + * + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. + */ +function _detectSubtleCrypto(fn) { + return (typeof util.globalScope !== 'undefined' && + typeof util.globalScope.crypto === 'object' && + typeof util.globalScope.crypto.subtle === 'object' && + typeof util.globalScope.crypto.subtle[fn] === 'function'); +} + +/** + * Performs feature detection on the deprecated Microsoft Internet Explorer + * outdated SubtleCrypto interface. This function should only be used after + * checking for the modern, standard SubtleCrypto interface. + * + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. + */ +function _detectSubtleMsCrypto(fn) { + return (typeof util.globalScope !== 'undefined' && + typeof util.globalScope.msCrypto === 'object' && + typeof util.globalScope.msCrypto.subtle === 'object' && + typeof util.globalScope.msCrypto.subtle[fn] === 'function'); +} + +function _intToUint8Array(x) { + var bytes = forge$k.util.hexToBytes(x.toString(16)); + var buffer = new Uint8Array(bytes.length); + for(var i = 0; i < bytes.length; ++i) { + buffer[i] = bytes.charCodeAt(i); + } + return buffer; +} + +/** + * Password-based encryption functions. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * An EncryptedPrivateKeyInfo: + * + * EncryptedPrivateKeyInfo ::= SEQUENCE { + * encryptionAlgorithm EncryptionAlgorithmIdentifier, + * encryptedData EncryptedData } + * + * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * EncryptedData ::= OCTET STRING + */ + +var forge$j = forge$F; + +// shortcut for asn.1 API +var asn1$6 = forge$j.asn1; + +/* Password-based encryption implementation. */ +var pki$3 = forge$j.pki = forge$j.pki || {}; +pki$3.pbe = forge$j.pbe = forge$j.pbe || {}; +var oids$1 = pki$3.oids; + +// validator for an EncryptedPrivateKeyInfo structure +// Note: Currently only works w/algorithm params +var encryptedPrivateKeyValidator = { + name: 'EncryptedPrivateKeyInfo', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.OID, + constructed: false, + capture: 'encryptionOid' + }, { + name: 'AlgorithmIdentifier.parameters', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.SEQUENCE, + constructed: true, + captureAsn1: 'encryptionParams' + }] + }, { + // encryptedData + name: 'EncryptedPrivateKeyInfo.encryptedData', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.OCTETSTRING, + constructed: false, + capture: 'encryptedData' + }] +}; + +// validator for a PBES2Algorithms structure +// Note: Currently only works w/PBKDF2 + AES encryption schemes +var PBES2AlgorithmsValidator = { + name: 'PBES2Algorithms', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.keyDerivationFunc', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.keyDerivationFunc.oid', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.OID, + constructed: false, + capture: 'kdfOid' + }, { + name: 'PBES2Algorithms.params', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.params.salt', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.OCTETSTRING, + constructed: false, + capture: 'kdfSalt' + }, { + name: 'PBES2Algorithms.params.iterationCount', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.INTEGER, + constructed: false, + capture: 'kdfIterationCount' + }, { + name: 'PBES2Algorithms.params.keyLength', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.INTEGER, + constructed: false, + optional: true, + capture: 'keyLength' + }, { + // prf + name: 'PBES2Algorithms.params.prf', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'PBES2Algorithms.params.prf.algorithm', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.OID, + constructed: false, + capture: 'prfOid' + }] + }] + }] + }, { + name: 'PBES2Algorithms.encryptionScheme', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.encryptionScheme.oid', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.OID, + constructed: false, + capture: 'encOid' + }, { + name: 'PBES2Algorithms.encryptionScheme.iv', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.OCTETSTRING, + constructed: false, + capture: 'encIv' + }] + }] +}; + +var pkcs12PbeParamsValidator = { + name: 'pkcs-12PbeParams', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'pkcs-12PbeParams.salt', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.OCTETSTRING, + constructed: false, + capture: 'salt' + }, { + name: 'pkcs-12PbeParams.iterations', + tagClass: asn1$6.Class.UNIVERSAL, + type: asn1$6.Type.INTEGER, + constructed: false, + capture: 'iterations' + }] +}; + +/** + * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo. + * + * PBES2Algorithms ALGORITHM-IDENTIFIER ::= + * { {PBES2-params IDENTIFIED BY id-PBES2}, ...} + * + * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} + * + * PBES2-params ::= SEQUENCE { + * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}}, + * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} + * } + * + * PBES2-KDFs ALGORITHM-IDENTIFIER ::= + * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... } + * + * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... } + * + * PBKDF2-params ::= SEQUENCE { + * salt CHOICE { + * specified OCTET STRING, + * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}} + * }, + * iterationCount INTEGER (1..MAX), + * keyLength INTEGER (1..MAX) OPTIONAL, + * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 + * } + * + * @param obj the ASN.1 PrivateKeyInfo object. + * @param password the password to encrypt with. + * @param options: + * algorithm the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. + * count the iteration count to use. + * saltSize the salt size to use. + * prfAlgorithm the PRF message digest algorithm to use + * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512') + * + * @return the ASN.1 EncryptedPrivateKeyInfo. + */ +pki$3.encryptPrivateKeyInfo = function(obj, password, options) { + // set default options + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || 'aes128'; + options.prfAlgorithm = options.prfAlgorithm || 'sha1'; + + // generate PBE params + var salt = forge$j.random.getBytesSync(options.saltSize); + var count = options.count; + var countBytes = asn1$6.integerToDer(count); + var dkLen; + var encryptionAlgorithm; + var encryptedData; + if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') { + // do PBES2 + var ivLen, encOid, cipherFn; + switch(options.algorithm) { + case 'aes128': + dkLen = 16; + ivLen = 16; + encOid = oids$1['aes128-CBC']; + cipherFn = forge$j.aes.createEncryptionCipher; + break; + case 'aes192': + dkLen = 24; + ivLen = 16; + encOid = oids$1['aes192-CBC']; + cipherFn = forge$j.aes.createEncryptionCipher; + break; + case 'aes256': + dkLen = 32; + ivLen = 16; + encOid = oids$1['aes256-CBC']; + cipherFn = forge$j.aes.createEncryptionCipher; + break; + case 'des': + dkLen = 8; + ivLen = 8; + encOid = oids$1['desCBC']; + cipherFn = forge$j.des.createEncryptionCipher; + break; + default: + var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); + error.algorithm = options.algorithm; + throw error; + } + + // get PRF message digest + var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase(); + var md = prfAlgorithmToMessageDigest(prfAlgorithm); + + // encrypt private key using pbe SHA-1 and AES/DES + var dk = forge$j.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = forge$j.random.getBytesSync(ivLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1$6.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + + // get PBKDF2-params + var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); + + encryptionAlgorithm = asn1$6.create( + asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false, + asn1$6.oidToDer(oids$1['pkcs5PBES2']).getBytes()), + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ + // keyDerivationFunc + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false, + asn1$6.oidToDer(oids$1['pkcs5PBKDF2']).getBytes()), + // PBKDF2-params + params + ]), + // encryptionScheme + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false, + asn1$6.oidToDer(encOid).getBytes()), + // iv + asn1$6.create( + asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, iv) + ]) + ]) + ]); + } else if(options.algorithm === '3des') { + // Do PKCS12 PBE + dkLen = 24; + + var saltBytes = new forge$j.util.ByteBuffer(salt); + var dk = pki$3.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); + var iv = pki$3.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); + var cipher = forge$j.des.createEncryptionCipher(dk); + cipher.start(iv); + cipher.update(asn1$6.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + + encryptionAlgorithm = asn1$6.create( + asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false, + asn1$6.oidToDer(oids$1['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()), + // pkcs-12PbeParams + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ + // salt + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, salt), + // iteration count + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.INTEGER, false, + countBytes.getBytes()) + ]) + ]); + } else { + var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); + error.algorithm = options.algorithm; + throw error; + } + + // EncryptedPrivateKeyInfo + var rval = asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ + // encryptionAlgorithm + encryptionAlgorithm, + // encryptedData + asn1$6.create( + asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, encryptedData) + ]); + return rval; +}; + +/** + * Decrypts a ASN.1 PrivateKeyInfo object. + * + * @param obj the ASN.1 EncryptedPrivateKeyInfo object. + * @param password the password to decrypt with. + * + * @return the ASN.1 PrivateKeyInfo on success, null on failure. + */ +pki$3.decryptPrivateKeyInfo = function(obj, password) { + var rval = null; + + // get PBE params + var capture = {}; + var errors = []; + if(!asn1$6.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { + var error = new Error('Cannot read encrypted private key. ' + + 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + // get cipher + var oid = asn1$6.derToOid(capture.encryptionOid); + var cipher = pki$3.pbe.getCipher(oid, capture.encryptionParams, password); + + // get encrypted data + var encrypted = forge$j.util.createBuffer(capture.encryptedData); + + cipher.update(encrypted); + if(cipher.finish()) { + rval = asn1$6.fromDer(cipher.output); + } + + return rval; +}; + +/** + * Converts a EncryptedPrivateKeyInfo to PEM format. + * + * @param epki the EncryptedPrivateKeyInfo. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted encrypted private key. + */ +pki$3.encryptedPrivateKeyToPem = function(epki, maxline) { + // convert to DER, then PEM-encode + var msg = { + type: 'ENCRYPTED PRIVATE KEY', + body: asn1$6.toDer(epki).getBytes() + }; + return forge$j.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption + * is not performed. + * + * @param pem the EncryptedPrivateKeyInfo in PEM-format. + * + * @return the ASN.1 EncryptedPrivateKeyInfo. + */ +pki$3.encryptedPrivateKeyFromPem = function(pem) { + var msg = forge$j.pem.decode(pem)[0]; + + if(msg.type !== 'ENCRYPTED PRIVATE KEY') { + var error = new Error('Could not convert encrypted private key from PEM; ' + + 'PEM header type is "ENCRYPTED PRIVATE KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert encrypted private key from PEM; ' + + 'PEM is encrypted.'); + } + + // convert DER to ASN.1 object + return asn1$6.fromDer(msg.body); +}; + +/** + * Encrypts an RSA private key. By default, the key will be wrapped in + * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo. + * This is the standard, preferred way to encrypt a private key. + * + * To produce a non-standard PEM-encrypted private key that uses encapsulated + * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL + * private key encryption), set the 'legacy' option to true. Note: Using this + * option will cause the iteration count to be forced to 1. + * + * Note: The 'des' algorithm is supported, but it is not considered to be + * secure because it only uses a single 56-bit key. If possible, it is highly + * recommended that a different algorithm be used. + * + * @param rsaKey the RSA key to encrypt. + * @param password the password to use. + * @param options: + * algorithm: the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des', 'des'). + * count: the iteration count to use. + * saltSize: the salt size to use. + * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated + * headers (DEK-Info) private key. + * + * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo. + */ +pki$3.encryptRsaPrivateKey = function(rsaKey, password, options) { + // standard PKCS#8 + options = options || {}; + if(!options.legacy) { + // encrypt PrivateKeyInfo + var rval = pki$3.wrapRsaPrivateKey(pki$3.privateKeyToAsn1(rsaKey)); + rval = pki$3.encryptPrivateKeyInfo(rval, password, options); + return pki$3.encryptedPrivateKeyToPem(rval); + } + + // legacy non-PKCS#8 + var algorithm; + var iv; + var dkLen; + var cipherFn; + switch(options.algorithm) { + case 'aes128': + algorithm = 'AES-128-CBC'; + dkLen = 16; + iv = forge$j.random.getBytesSync(16); + cipherFn = forge$j.aes.createEncryptionCipher; + break; + case 'aes192': + algorithm = 'AES-192-CBC'; + dkLen = 24; + iv = forge$j.random.getBytesSync(16); + cipherFn = forge$j.aes.createEncryptionCipher; + break; + case 'aes256': + algorithm = 'AES-256-CBC'; + dkLen = 32; + iv = forge$j.random.getBytesSync(16); + cipherFn = forge$j.aes.createEncryptionCipher; + break; + case '3des': + algorithm = 'DES-EDE3-CBC'; + dkLen = 24; + iv = forge$j.random.getBytesSync(8); + cipherFn = forge$j.des.createEncryptionCipher; + break; + case 'des': + algorithm = 'DES-CBC'; + dkLen = 8; + iv = forge$j.random.getBytesSync(8); + cipherFn = forge$j.des.createEncryptionCipher; + break; + default: + var error = new Error('Could not encrypt RSA private key; unsupported ' + + 'encryption algorithm "' + options.algorithm + '".'); + error.algorithm = options.algorithm; + throw error; + } + + // encrypt private key using OpenSSL legacy key derivation + var dk = forge$j.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1$6.toDer(pki$3.privateKeyToAsn1(rsaKey))); + cipher.finish(); + + var msg = { + type: 'RSA PRIVATE KEY', + procType: { + version: '4', + type: 'ENCRYPTED' + }, + dekInfo: { + algorithm: algorithm, + parameters: forge$j.util.bytesToHex(iv).toUpperCase() + }, + body: cipher.output.getBytes() + }; + return forge$j.pem.encode(msg); +}; + +/** + * Decrypts an RSA private key. + * + * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt. + * @param password the password to use. + * + * @return the RSA key on success, null on failure. + */ +pki$3.decryptRsaPrivateKey = function(pem, password) { + var rval = null; + + var msg = forge$j.pem.decode(pem)[0]; + + if(msg.type !== 'ENCRYPTED PRIVATE KEY' && + msg.type !== 'PRIVATE KEY' && + msg.type !== 'RSA PRIVATE KEY') { + var error = new Error('Could not convert private key from PEM; PEM header type ' + + 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); + error.headerType = error; + throw error; + } + + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + var dkLen; + var cipherFn; + switch(msg.dekInfo.algorithm) { + case 'DES-CBC': + dkLen = 8; + cipherFn = forge$j.des.createDecryptionCipher; + break; + case 'DES-EDE3-CBC': + dkLen = 24; + cipherFn = forge$j.des.createDecryptionCipher; + break; + case 'AES-128-CBC': + dkLen = 16; + cipherFn = forge$j.aes.createDecryptionCipher; + break; + case 'AES-192-CBC': + dkLen = 24; + cipherFn = forge$j.aes.createDecryptionCipher; + break; + case 'AES-256-CBC': + dkLen = 32; + cipherFn = forge$j.aes.createDecryptionCipher; + break; + case 'RC2-40-CBC': + dkLen = 5; + cipherFn = function(key) { + return forge$j.rc2.createDecryptionCipher(key, 40); + }; + break; + case 'RC2-64-CBC': + dkLen = 8; + cipherFn = function(key) { + return forge$j.rc2.createDecryptionCipher(key, 64); + }; + break; + case 'RC2-128-CBC': + dkLen = 16; + cipherFn = function(key) { + return forge$j.rc2.createDecryptionCipher(key, 128); + }; + break; + default: + var error = new Error('Could not decrypt private key; unsupported ' + + 'encryption algorithm "' + msg.dekInfo.algorithm + '".'); + error.algorithm = msg.dekInfo.algorithm; + throw error; + } + + // use OpenSSL legacy key derivation + var iv = forge$j.util.hexToBytes(msg.dekInfo.parameters); + var dk = forge$j.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(forge$j.util.createBuffer(msg.body)); + if(cipher.finish()) { + rval = cipher.output.getBytes(); + } else { + return rval; + } + } else { + rval = msg.body; + } + + if(msg.type === 'ENCRYPTED PRIVATE KEY') { + rval = pki$3.decryptPrivateKeyInfo(asn1$6.fromDer(rval), password); + } else { + // decryption already performed above + rval = asn1$6.fromDer(rval); + } + + if(rval !== null) { + rval = pki$3.privateKeyFromAsn1(rval); + } + + return rval; +}; + +/** + * Derives a PKCS#12 key. + * + * @param password the password to derive the key material from, null or + * undefined for none. + * @param salt the salt, as a ByteBuffer, to use. + * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). + * @param iter the iteration count. + * @param n the number of bytes to derive from the password. + * @param md the message digest to use, defaults to SHA-1. + * + * @return a ByteBuffer with the bytes derived from the password. + */ +pki$3.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { + var j, l; + + if(typeof md === 'undefined' || md === null) { + if(!('sha1' in forge$j.md)) { + throw new Error('"sha1" hash algorithm unavailable.'); + } + md = forge$j.md.sha1.create(); + } + + var u = md.digestLength; + var v = md.blockLength; + var result = new forge$j.util.ByteBuffer(); + + /* Convert password to Unicode byte buffer + trailing 0-byte. */ + var passBuf = new forge$j.util.ByteBuffer(); + if(password !== null && password !== undefined) { + for(l = 0; l < password.length; l++) { + passBuf.putInt16(password.charCodeAt(l)); + } + passBuf.putInt16(0); + } + + /* Length of salt and password in BYTES. */ + var p = passBuf.length(); + var s = salt.length(); + + /* 1. Construct a string, D (the "diversifier"), by concatenating + v copies of ID. */ + var D = new forge$j.util.ByteBuffer(); + D.fillWithByte(id, v); + + /* 2. Concatenate copies of the salt together to create a string S of length + v * ceil(s / v) bytes (the final copy of the salt may be trunacted + to create S). + Note that if the salt is the empty string, then so is S. */ + var Slen = v * Math.ceil(s / v); + var S = new forge$j.util.ByteBuffer(); + for(l = 0; l < Slen; l++) { + S.putByte(salt.at(l % s)); + } + + /* 3. Concatenate copies of the password together to create a string P of + length v * ceil(p / v) bytes (the final copy of the password may be + truncated to create P). + Note that if the password is the empty string, then so is P. */ + var Plen = v * Math.ceil(p / v); + var P = new forge$j.util.ByteBuffer(); + for(l = 0; l < Plen; l++) { + P.putByte(passBuf.at(l % p)); + } + + /* 4. Set I=S||P to be the concatenation of S and P. */ + var I = S; + I.putBuffer(P); + + /* 5. Set c=ceil(n / u). */ + var c = Math.ceil(n / u); + + /* 6. For i=1, 2, ..., c, do the following: */ + for(var i = 1; i <= c; i++) { + /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */ + var buf = new forge$j.util.ByteBuffer(); + buf.putBytes(D.bytes()); + buf.putBytes(I.bytes()); + for(var round = 0; round < iter; round++) { + md.start(); + md.update(buf.getBytes()); + buf = md.digest(); + } + + /* b) Concatenate copies of Ai to create a string B of length v bytes (the + final copy of Ai may be truncated to create B). */ + var B = new forge$j.util.ByteBuffer(); + for(l = 0; l < v; l++) { + B.putByte(buf.at(l % u)); + } + + /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks, + where k=ceil(s / v) + ceil(p / v), modify I by setting + Ij=(Ij+B+1) mod 2v for each j. */ + var k = Math.ceil(s / v) + Math.ceil(p / v); + var Inew = new forge$j.util.ByteBuffer(); + for(j = 0; j < k; j++) { + var chunk = new forge$j.util.ByteBuffer(I.getBytes(v)); + var x = 0x1ff; + for(l = B.length() - 1; l >= 0; l--) { + x = x >> 8; + x += B.at(l) + chunk.at(l); + chunk.setAt(l, x & 0xff); + } + Inew.putBuffer(chunk); + } + I = Inew; + + /* Add Ai to A. */ + result.putBuffer(buf); + } + + result.truncate(result.length() - n); + return result; +}; + +/** + * Get new Forge cipher object instance. + * + * @param oid the OID (in string notation). + * @param params the ASN.1 params object. + * @param password the password to decrypt with. + * + * @return new cipher object instance. + */ +pki$3.pbe.getCipher = function(oid, params, password) { + switch(oid) { + case pki$3.oids['pkcs5PBES2']: + return pki$3.pbe.getCipherForPBES2(oid, params, password); + + case pki$3.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: + case pki$3.oids['pbewithSHAAnd40BitRC2-CBC']: + return pki$3.pbe.getCipherForPKCS12PBE(oid, params, password); + + default: + var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.'); + error.oid = oid; + error.supportedOids = [ + 'pkcs5PBES2', + 'pbeWithSHAAnd3-KeyTripleDES-CBC', + 'pbewithSHAAnd40BitRC2-CBC' + ]; + throw error; + } +}; + +/** + * Get new Forge cipher object instance according to PBES2 params block. + * + * The returned cipher instance is already started using the IV + * from PBES2 parameter block. + * + * @param oid the PKCS#5 PBKDF2 OID (in string notation). + * @param params the ASN.1 PBES2-params object. + * @param password the password to decrypt with. + * + * @return new cipher object instance. + */ +pki$3.pbe.getCipherForPBES2 = function(oid, params, password) { + // get PBE params + var capture = {}; + var errors = []; + if(!asn1$6.validate(params, PBES2AlgorithmsValidator, capture, errors)) { + var error = new Error('Cannot read password-based-encryption algorithm ' + + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + // check oids + oid = asn1$6.derToOid(capture.kdfOid); + if(oid !== pki$3.oids['pkcs5PBKDF2']) { + var error = new Error('Cannot read encrypted private key. ' + + 'Unsupported key derivation function OID.'); + error.oid = oid; + error.supportedOids = ['pkcs5PBKDF2']; + throw error; + } + oid = asn1$6.derToOid(capture.encOid); + if(oid !== pki$3.oids['aes128-CBC'] && + oid !== pki$3.oids['aes192-CBC'] && + oid !== pki$3.oids['aes256-CBC'] && + oid !== pki$3.oids['des-EDE3-CBC'] && + oid !== pki$3.oids['desCBC']) { + var error = new Error('Cannot read encrypted private key. ' + + 'Unsupported encryption scheme OID.'); + error.oid = oid; + error.supportedOids = [ + 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC']; + throw error; + } + + // set PBE params + var salt = capture.kdfSalt; + var count = forge$j.util.createBuffer(capture.kdfIterationCount); + count = count.getInt(count.length() << 3); + var dkLen; + var cipherFn; + switch(pki$3.oids[oid]) { + case 'aes128-CBC': + dkLen = 16; + cipherFn = forge$j.aes.createDecryptionCipher; + break; + case 'aes192-CBC': + dkLen = 24; + cipherFn = forge$j.aes.createDecryptionCipher; + break; + case 'aes256-CBC': + dkLen = 32; + cipherFn = forge$j.aes.createDecryptionCipher; + break; + case 'des-EDE3-CBC': + dkLen = 24; + cipherFn = forge$j.des.createDecryptionCipher; + break; + case 'desCBC': + dkLen = 8; + cipherFn = forge$j.des.createDecryptionCipher; + break; + } + + // get PRF message digest + var md = prfOidToMessageDigest(capture.prfOid); + + // decrypt private key using pbe with chosen PRF and AES/DES + var dk = forge$j.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = capture.encIv; + var cipher = cipherFn(dk); + cipher.start(iv); + + return cipher; +}; + +/** + * Get new Forge cipher object instance for PKCS#12 PBE. + * + * The returned cipher instance is already started using the key & IV + * derived from the provided password and PKCS#12 PBE salt. + * + * @param oid The PKCS#12 PBE OID (in string notation). + * @param params The ASN.1 PKCS#12 PBE-params object. + * @param password The password to decrypt with. + * + * @return the new cipher object instance. + */ +pki$3.pbe.getCipherForPKCS12PBE = function(oid, params, password) { + // get PBE params + var capture = {}; + var errors = []; + if(!asn1$6.validate(params, pkcs12PbeParamsValidator, capture, errors)) { + var error = new Error('Cannot read password-based-encryption algorithm ' + + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + var salt = forge$j.util.createBuffer(capture.salt); + var count = forge$j.util.createBuffer(capture.iterations); + count = count.getInt(count.length() << 3); + + var dkLen, dIvLen, cipherFn; + switch(oid) { + case pki$3.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: + dkLen = 24; + dIvLen = 8; + cipherFn = forge$j.des.startDecrypting; + break; + + case pki$3.oids['pbewithSHAAnd40BitRC2-CBC']: + dkLen = 5; + dIvLen = 8; + cipherFn = function(key, iv) { + var cipher = forge$j.rc2.createDecryptionCipher(key, 40); + cipher.start(iv, null); + return cipher; + }; + break; + + default: + var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.'); + error.oid = oid; + throw error; + } + + // get PRF message digest + var md = prfOidToMessageDigest(capture.prfOid); + var key = pki$3.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); + md.start(); + var iv = pki$3.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); + + return cipherFn(key, iv); +}; + +/** + * OpenSSL's legacy key derivation function. + * + * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html + * + * @param password the password to derive the key from. + * @param salt the salt to use, null for none. + * @param dkLen the number of bytes needed for the derived key. + * @param [options] the options to use: + * [md] an optional message digest object to use. + */ +pki$3.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { + if(typeof md === 'undefined' || md === null) { + if(!('md5' in forge$j.md)) { + throw new Error('"md5" hash algorithm unavailable.'); + } + md = forge$j.md.md5.create(); + } + if(salt === null) { + salt = ''; + } + var digests = [hash(md, password + salt)]; + for(var length = 16, i = 1; length < dkLen; ++i, length += 16) { + digests.push(hash(md, digests[i - 1] + password + salt)); + } + return digests.join('').substr(0, dkLen); +}; + +function hash(md, bytes) { + return md.start().update(bytes).digest().getBytes(); +} + +function prfOidToMessageDigest(prfOid) { + // get PRF algorithm, default to SHA-1 + var prfAlgorithm; + if(!prfOid) { + prfAlgorithm = 'hmacWithSHA1'; + } else { + prfAlgorithm = pki$3.oids[asn1$6.derToOid(prfOid)]; + if(!prfAlgorithm) { + var error = new Error('Unsupported PRF OID.'); + error.oid = prfOid; + error.supported = [ + 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', + 'hmacWithSHA512']; + throw error; + } + } + return prfAlgorithmToMessageDigest(prfAlgorithm); +} + +function prfAlgorithmToMessageDigest(prfAlgorithm) { + var factory = forge$j.md; + switch(prfAlgorithm) { + case 'hmacWithSHA224': + factory = forge$j.md.sha512; + case 'hmacWithSHA1': + case 'hmacWithSHA256': + case 'hmacWithSHA384': + case 'hmacWithSHA512': + prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); + break; + default: + var error = new Error('Unsupported PRF algorithm.'); + error.algorithm = prfAlgorithm; + error.supported = [ + 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', + 'hmacWithSHA512']; + throw error; + } + if(!factory || !(prfAlgorithm in factory)) { + throw new Error('Unknown hash algorithm: ' + prfAlgorithm); + } + return factory[prfAlgorithm].create(); +} + +function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { + var params = asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ + // salt + asn1$6.create( + asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, salt), + // iteration count + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.INTEGER, false, + countBytes.getBytes()) + ]); + // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm + if(prfAlgorithm !== 'hmacWithSHA1') { + params.value.push( + // key length + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.INTEGER, false, + forge$j.util.hexToBytes(dkLen.toString(16))), + // AlgorithmIdentifier + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ + // algorithm + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false, + asn1$6.oidToDer(pki$3.oids[prfAlgorithm]).getBytes()), + // parameters (null) + asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.NULL, false, '') + ])); + } + return params; +} + +/** + * Javascript implementation of ASN.1 validators for PKCS#7 v1.5. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2012-2015 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * The ASN.1 representation of PKCS#7 is as follows + * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt): + * + * A PKCS#7 message consists of a ContentInfo on root level, which may + * contain any number of further ContentInfo nested into it. + * + * ContentInfo ::= SEQUENCE { + * contentType ContentType, + * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL + * } + * + * ContentType ::= OBJECT IDENTIFIER + * + * EnvelopedData ::= SEQUENCE { + * version Version, + * recipientInfos RecipientInfos, + * encryptedContentInfo EncryptedContentInfo + * } + * + * EncryptedData ::= SEQUENCE { + * version Version, + * encryptedContentInfo EncryptedContentInfo + * } + * + * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2) + * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 } + * + * SignedData ::= SEQUENCE { + * version INTEGER, + * digestAlgorithms DigestAlgorithmIdentifiers, + * contentInfo ContentInfo, + * certificates [0] IMPLICIT Certificates OPTIONAL, + * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, + * signerInfos SignerInfos + * } + * + * SignerInfos ::= SET OF SignerInfo + * + * SignerInfo ::= SEQUENCE { + * version Version, + * issuerAndSerialNumber IssuerAndSerialNumber, + * digestAlgorithm DigestAlgorithmIdentifier, + * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, + * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, + * encryptedDigest EncryptedDigest, + * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL + * } + * + * EncryptedDigest ::= OCTET STRING + * + * Attributes ::= SET OF Attribute + * + * Attribute ::= SEQUENCE { + * attrType OBJECT IDENTIFIER, + * attrValues SET OF AttributeValue + * } + * + * AttributeValue ::= ANY + * + * Version ::= INTEGER + * + * RecipientInfos ::= SET OF RecipientInfo + * + * EncryptedContentInfo ::= SEQUENCE { + * contentType ContentType, + * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, + * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL + * } + * + * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of AES and DES3, there is only one, + * the IV. + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * EncryptedContent ::= OCTET STRING + * + * RecipientInfo ::= SEQUENCE { + * version Version, + * issuerAndSerialNumber IssuerAndSerialNumber, + * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier, + * encryptedKey EncryptedKey + * } + * + * IssuerAndSerialNumber ::= SEQUENCE { + * issuer Name, + * serialNumber CertificateSerialNumber + * } + * + * CertificateSerialNumber ::= INTEGER + * + * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * EncryptedKey ::= OCTET STRING + */ + +var forge$i = forge$F; + + + +// shortcut for ASN.1 API +var asn1$5 = forge$i.asn1; + +// shortcut for PKCS#7 API +var p7v = forge$i.pkcs7asn1 = forge$i.pkcs7asn1 || {}; +forge$i.pkcs7 = forge$i.pkcs7 || {}; +forge$i.pkcs7.asn1 = p7v; + +var contentInfoValidator$1 = { + name: 'ContentInfo', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'ContentInfo.ContentType', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'ContentInfo.content', + tagClass: asn1$5.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + captureAsn1: 'content' + }] +}; +p7v.contentInfoValidator = contentInfoValidator$1; + +var encryptedContentInfoValidator = { + name: 'EncryptedContentInfo', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedContentInfo.contentType', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.OID, + constructed: false, + capture: 'encAlgorithm' + }, { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter', + tagClass: asn1$5.Class.UNIVERSAL, + captureAsn1: 'encParameter' + }] + }, { + name: 'EncryptedContentInfo.encryptedContent', + tagClass: asn1$5.Class.CONTEXT_SPECIFIC, + type: 0, + /* The PKCS#7 structure output by OpenSSL somewhat differs from what + * other implementations do generate. + * + * OpenSSL generates a structure like this: + * SEQUENCE { + * ... + * [0] + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * + * Whereas other implementations (and this PKCS#7 module) generate: + * SEQUENCE { + * ... + * [0] { + * OCTET STRING + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * } + * + * In order to support both, we just capture the context specific + * field here. The OCTET STRING bit is removed below. + */ + capture: 'encryptedContent', + captureAsn1: 'encryptedContentAsn1' + }] +}; + +p7v.envelopedDataValidator = { + name: 'EnvelopedData', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EnvelopedData.Version', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'EnvelopedData.RecipientInfos', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SET, + constructed: true, + captureAsn1: 'recipientInfos' + }].concat(encryptedContentInfoValidator) +}; + +p7v.encryptedDataValidator = { + name: 'EncryptedData', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedData.Version', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.INTEGER, + constructed: false, + capture: 'version' + }].concat(encryptedContentInfoValidator) +}; + +var signerValidator = { + name: 'SignerInfo', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.version', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.INTEGER, + constructed: false + }, { + name: 'SignerInfo.issuerAndSerialNumber', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.issuerAndSerialNumber.issuer', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + captureAsn1: 'issuer' + }, { + name: 'SignerInfo.issuerAndSerialNumber.serialNumber', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.INTEGER, + constructed: false, + capture: 'serial' + }] + }, { + name: 'SignerInfo.digestAlgorithm', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.digestAlgorithm.algorithm', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.OID, + constructed: false, + capture: 'digestAlgorithm' + }, { + name: 'SignerInfo.digestAlgorithm.parameter', + tagClass: asn1$5.Class.UNIVERSAL, + constructed: false, + captureAsn1: 'digestParameter', + optional: true + }] + }, { + name: 'SignerInfo.authenticatedAttributes', + tagClass: asn1$5.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: 'authenticatedAttributes' + }, { + name: 'SignerInfo.digestEncryptionAlgorithm', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + capture: 'signatureAlgorithm' + }, { + name: 'SignerInfo.encryptedDigest', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.OCTETSTRING, + constructed: false, + capture: 'signature' + }, { + name: 'SignerInfo.unauthenticatedAttributes', + tagClass: asn1$5.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + capture: 'unauthenticatedAttributes' + }] +}; + +p7v.signedDataValidator = { + name: 'SignedData', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignedData.Version', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'SignedData.DigestAlgorithms', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SET, + constructed: true, + captureAsn1: 'digestAlgorithms' + }, + contentInfoValidator$1, + { + name: 'SignedData.Certificates', + tagClass: asn1$5.Class.CONTEXT_SPECIFIC, + type: 0, + optional: true, + captureAsn1: 'certificates' + }, { + name: 'SignedData.CertificateRevocationLists', + tagClass: asn1$5.Class.CONTEXT_SPECIFIC, + type: 1, + optional: true, + captureAsn1: 'crls' + }, { + name: 'SignedData.SignerInfos', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SET, + capture: 'signerInfos', + optional: true, + value: [signerValidator] + }] +}; + +p7v.recipientInfoValidator = { + name: 'RecipientInfo', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.version', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'RecipientInfo.issuerAndSerial', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.issuerAndSerial.issuer', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + captureAsn1: 'issuer' + }, { + name: 'RecipientInfo.issuerAndSerial.serialNumber', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.INTEGER, + constructed: false, + capture: 'serial' + }] + }, { + name: 'RecipientInfo.keyEncryptionAlgorithm', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.OID, + constructed: false, + capture: 'encAlgorithm' + }, { + name: 'RecipientInfo.keyEncryptionAlgorithm.parameter', + tagClass: asn1$5.Class.UNIVERSAL, + constructed: false, + captureAsn1: 'encParameter' + }] + }, { + name: 'RecipientInfo.encryptedKey', + tagClass: asn1$5.Class.UNIVERSAL, + type: asn1$5.Type.OCTETSTRING, + constructed: false, + capture: 'encKey' + }] +}; + +/** + * Javascript implementation of mask generation function MGF1. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2014 Digital Bazaar, Inc. + */ + +var forge$h = forge$F; + + +forge$h.mgf = forge$h.mgf || {}; +var mgf1 = forge$h.mgf.mgf1 = forge$h.mgf1 = forge$h.mgf1 || {}; + +/** + * Creates a MGF1 mask generation function object. + * + * @param md the message digest API to use (eg: forge.md.sha1.create()). + * + * @return a mask generation function object. + */ +mgf1.create = function(md) { + var mgf = { + /** + * Generate mask of specified length. + * + * @param {String} seed The seed for mask generation. + * @param maskLen Number of bytes to generate. + * @return {String} The generated mask. + */ + generate: function(seed, maskLen) { + /* 2. Let T be the empty octet string. */ + var t = new forge$h.util.ByteBuffer(); + + /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */ + var len = Math.ceil(maskLen / md.digestLength); + for(var i = 0; i < len; i++) { + /* a. Convert counter to an octet string C of length 4 octets */ + var c = new forge$h.util.ByteBuffer(); + c.putInt32(i); + + /* b. Concatenate the hash of the seed mgfSeed and C to the octet + * string T: */ + md.start(); + md.update(seed + c.getBytes()); + t.putBuffer(md.digest()); + } + + /* Output the leading maskLen octets of T as the octet string mask. */ + t.truncate(t.length() - maskLen); + return t.getBytes(); + } + }; + + return mgf; +}; + +/** + * Node.js module for Forge mask generation functions. + * + * @author Stefan Siegl + * + * Copyright 2012 Stefan Siegl + */ + +var forge$g = forge$F; + + +forge$g.mgf = forge$g.mgf || {}; +forge$g.mgf.mgf1 = forge$g.mgf1; + +/** + * Javascript implementation of PKCS#1 PSS signature padding. + * + * @author Stefan Siegl + * + * Copyright (c) 2012 Stefan Siegl + */ + +var forge$f = forge$F; + + + +// shortcut for PSS API +var pss = forge$f.pss = forge$f.pss || {}; + +/** + * Creates a PSS signature scheme object. + * + * There are several ways to provide a salt for encoding: + * + * 1. Specify the saltLength only and the built-in PRNG will generate it. + * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that + * will be used. + * 3. Specify the salt itself as a forge.util.ByteBuffer. + * + * @param options the options to use: + * md the message digest object to use, a forge md instance. + * mgf the mask generation function to use, a forge mgf instance. + * [saltLength] the length of the salt in octets. + * [prng] the pseudo-random number generator to use to produce a salt. + * [salt] the salt to use when encoding. + * + * @return a signature scheme object. + */ +pss.create = function(options) { + // backwards compatibility w/legacy args: hash, mgf, sLen + if(arguments.length === 3) { + options = { + md: arguments[0], + mgf: arguments[1], + saltLength: arguments[2] + }; + } + + var hash = options.md; + var mgf = options.mgf; + var hLen = hash.digestLength; + + var salt_ = options.salt || null; + if(typeof salt_ === 'string') { + // assume binary-encoded string + salt_ = forge$f.util.createBuffer(salt_); + } + + var sLen; + if('saltLength' in options) { + sLen = options.saltLength; + } else if(salt_ !== null) { + sLen = salt_.length(); + } else { + throw new Error('Salt length not specified or specific salt not given.'); + } + + if(salt_ !== null && salt_.length() !== sLen) { + throw new Error('Given salt length does not match length of given salt.'); + } + + var prng = options.prng || forge$f.random; + + var pssobj = {}; + + /** + * Encodes a PSS signature. + * + * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1. + * + * @param md the message digest object with the hash to sign. + * @param modsBits the length of the RSA modulus in bits. + * + * @return the encoded message as a binary-encoded string of length + * ceil((modBits - 1) / 8). + */ + pssobj.encode = function(md, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + + /* 2. Let mHash = Hash(M), an octet string of length hLen. */ + var mHash = md.digest().getBytes(); + + /* 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. */ + if(emLen < hLen + sLen + 2) { + throw new Error('Message is too long to encrypt.'); + } + + /* 4. Generate a random octet string salt of length sLen; if sLen = 0, + * then salt is the empty string. */ + var salt; + if(salt_ === null) { + salt = prng.getBytesSync(sLen); + } else { + salt = salt_.bytes(); + } + + /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */ + var m_ = new forge$f.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + + /* 6. Let H = Hash(M'), an octet string of length hLen. */ + hash.start(); + hash.update(m_.getBytes()); + var h = hash.digest().getBytes(); + + /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2 + * zero octets. The length of PS may be 0. */ + var ps = new forge$f.util.ByteBuffer(); + ps.fillWithByte(0, emLen - sLen - hLen - 2); + + /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length + * emLen - hLen - 1. */ + ps.putByte(0x01); + ps.putBytes(salt); + var db = ps.getBytes(); + + /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */ + var maskLen = emLen - hLen - 1; + var dbMask = mgf.generate(h, maskLen); + + /* 10. Let maskedDB = DB \xor dbMask. */ + var maskedDB = ''; + for(i = 0; i < maskLen; i++) { + maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + + /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in + * maskedDB to zero. */ + var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; + maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + + maskedDB.substr(1); + + /* 12. Let EM = maskedDB || H || 0xbc. + * 13. Output EM. */ + return maskedDB + h + String.fromCharCode(0xbc); + }; + + /** + * Verifies a PSS signature. + * + * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2. + * + * @param mHash the message digest hash, as a binary-encoded string, to + * compare against the signature. + * @param em the encoded message, as a binary-encoded string + * (RSA decryption result). + * @param modsBits the length of the RSA modulus in bits. + * + * @return true if the signature was verified, false if not. + */ + pssobj.verify = function(mHash, em, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + + /* c. Convert the message representative m to an encoded message EM + * of length emLen = ceil((modBits - 1) / 8) octets, where modBits + * is the length in bits of the RSA modulus n */ + em = em.substr(-emLen); + + /* 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. */ + if(emLen < hLen + sLen + 2) { + throw new Error('Inconsistent parameters to PSS signature verification.'); + } + + /* 4. If the rightmost octet of EM does not have hexadecimal value + * 0xbc, output "inconsistent" and stop. */ + if(em.charCodeAt(emLen - 1) !== 0xbc) { + throw new Error('Encoded message does not end in 0xBC.'); + } + + /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and + * let H be the next hLen octets. */ + var maskLen = emLen - hLen - 1; + var maskedDB = em.substr(0, maskLen); + var h = em.substr(maskLen, hLen); + + /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in + * maskedDB are not all equal to zero, output "inconsistent" and stop. */ + var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; + if((maskedDB.charCodeAt(0) & mask) !== 0) { + throw new Error('Bits beyond keysize not zero as expected.'); + } + + /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */ + var dbMask = mgf.generate(h, maskLen); + + /* 8. Let DB = maskedDB \xor dbMask. */ + var db = ''; + for(i = 0; i < maskLen; i++) { + db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + + /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet + * in DB to zero. */ + db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); + + /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero + * or if the octet at position emLen - hLen - sLen - 1 (the leftmost + * position is "position 1") does not have hexadecimal value 0x01, + * output "inconsistent" and stop. */ + var checkLen = emLen - hLen - sLen - 2; + for(i = 0; i < checkLen; i++) { + if(db.charCodeAt(i) !== 0x00) { + throw new Error('Leftmost octets not zero as expected'); + } + } + + if(db.charCodeAt(checkLen) !== 0x01) { + throw new Error('Inconsistent PSS signature, 0x01 marker not found'); + } + + /* 11. Let salt be the last sLen octets of DB. */ + var salt = db.substr(-sLen); + + /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */ + var m_ = new forge$f.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + + /* 13. Let H' = Hash(M'), an octet string of length hLen. */ + hash.start(); + hash.update(m_.getBytes()); + var h_ = hash.digest().getBytes(); + + /* 14. If H = H', output "consistent." Otherwise, output "inconsistent." */ + return h === h_; + }; + + return pssobj; +}; + +/** + * Javascript implementation of X.509 and related components (such as + * Certification Signing Requests) of a Public Key Infrastructure. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * + * The ASN.1 representation of an X.509v3 certificate is as follows + * (see RFC 2459): + * + * Certificate ::= SEQUENCE { + * tbsCertificate TBSCertificate, + * signatureAlgorithm AlgorithmIdentifier, + * signatureValue BIT STRING + * } + * + * TBSCertificate ::= SEQUENCE { + * version [0] EXPLICIT Version DEFAULT v1, + * serialNumber CertificateSerialNumber, + * signature AlgorithmIdentifier, + * issuer Name, + * validity Validity, + * subject Name, + * subjectPublicKeyInfo SubjectPublicKeyInfo, + * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, + * -- If present, version shall be v2 or v3 + * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, + * -- If present, version shall be v2 or v3 + * extensions [3] EXPLICIT Extensions OPTIONAL + * -- If present, version shall be v3 + * } + * + * Version ::= INTEGER { v1(0), v2(1), v3(2) } + * + * CertificateSerialNumber ::= INTEGER + * + * Name ::= CHOICE { + * // only one possible choice for now + * RDNSequence + * } + * + * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName + * + * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue + * + * AttributeTypeAndValue ::= SEQUENCE { + * type AttributeType, + * value AttributeValue + * } + * AttributeType ::= OBJECT IDENTIFIER + * AttributeValue ::= ANY DEFINED BY AttributeType + * + * Validity ::= SEQUENCE { + * notBefore Time, + * notAfter Time + * } + * + * Time ::= CHOICE { + * utcTime UTCTime, + * generalTime GeneralizedTime + * } + * + * UniqueIdentifier ::= BIT STRING + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING + * } + * + * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension + * + * Extension ::= SEQUENCE { + * extnID OBJECT IDENTIFIER, + * critical BOOLEAN DEFAULT FALSE, + * extnValue OCTET STRING + * } + * + * The only key algorithm currently supported for PKI is RSA. + * + * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055. + * + * PKCS#10 v1.7 describes certificate signing requests: + * + * CertificationRequestInfo: + * + * CertificationRequestInfo ::= SEQUENCE { + * version INTEGER { v1(0) } (v1,...), + * subject Name, + * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, + * attributes [0] Attributes{{ CRIAttributes }} + * } + * + * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }} + * + * CRIAttributes ATTRIBUTE ::= { + * ... -- add any locally defined attributes here -- } + * + * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE { + * type ATTRIBUTE.&id({IOSet}), + * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type}) + * } + * + * CertificationRequest ::= SEQUENCE { + * certificationRequestInfo CertificationRequestInfo, + * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, + * signature BIT STRING + * } + */ + +var forge$e = forge$F; + + + + + + + + + + + +// shortcut for asn.1 API +var asn1$4 = forge$e.asn1; + +/* Public Key Infrastructure (PKI) implementation. */ +var pki$2 = forge$e.pki = forge$e.pki || {}; +var oids = pki$2.oids; + +// short name OID mappings +var _shortNames = {}; +_shortNames['CN'] = oids['commonName']; +_shortNames['commonName'] = 'CN'; +_shortNames['C'] = oids['countryName']; +_shortNames['countryName'] = 'C'; +_shortNames['L'] = oids['localityName']; +_shortNames['localityName'] = 'L'; +_shortNames['ST'] = oids['stateOrProvinceName']; +_shortNames['stateOrProvinceName'] = 'ST'; +_shortNames['O'] = oids['organizationName']; +_shortNames['organizationName'] = 'O'; +_shortNames['OU'] = oids['organizationalUnitName']; +_shortNames['organizationalUnitName'] = 'OU'; +_shortNames['E'] = oids['emailAddress']; +_shortNames['emailAddress'] = 'E'; + +// validator for an SubjectPublicKeyInfo structure +// Note: Currently only works with an RSA public key +var publicKeyValidator$1 = forge$e.pki.rsa.publicKeyValidator; + +// validator for an X.509v3 certificate +var x509CertificateValidator = { + name: 'Certificate', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Certificate.TBSCertificate', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + captureAsn1: 'tbsCertificate', + value: [{ + name: 'Certificate.TBSCertificate.version', + tagClass: asn1$4.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.version.integer', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.INTEGER, + constructed: false, + capture: 'certVersion' + }] + }, { + name: 'Certificate.TBSCertificate.serialNumber', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.INTEGER, + constructed: false, + capture: 'certSerialNumber' + }, { + name: 'Certificate.TBSCertificate.signature', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Certificate.TBSCertificate.signature.algorithm', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.OID, + constructed: false, + capture: 'certinfoSignatureOid' + }, { + name: 'Certificate.TBSCertificate.signature.parameters', + tagClass: asn1$4.Class.UNIVERSAL, + optional: true, + captureAsn1: 'certinfoSignatureParams' + }] + }, { + name: 'Certificate.TBSCertificate.issuer', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certIssuer' + }, { + name: 'Certificate.TBSCertificate.validity', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + // Note: UTC and generalized times may both appear so the capture + // names are based on their detected order, the names used below + // are only for the common case, which validity time really means + // "notBefore" and which means "notAfter" will be determined by order + value: [{ + // notBefore (Time) (UTC time case) + name: 'Certificate.TBSCertificate.validity.notBefore (utc)', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.UTCTIME, + constructed: false, + optional: true, + capture: 'certValidity1UTCTime' + }, { + // notBefore (Time) (generalized time case) + name: 'Certificate.TBSCertificate.validity.notBefore (generalized)', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: 'certValidity2GeneralizedTime' + }, { + // notAfter (Time) (only UTC time is supported) + name: 'Certificate.TBSCertificate.validity.notAfter (utc)', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.UTCTIME, + constructed: false, + optional: true, + capture: 'certValidity3UTCTime' + }, { + // notAfter (Time) (only UTC time is supported) + name: 'Certificate.TBSCertificate.validity.notAfter (generalized)', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: 'certValidity4GeneralizedTime' + }] + }, { + // Name (subject) (RDNSequence) + name: 'Certificate.TBSCertificate.subject', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certSubject' + }, + // SubjectPublicKeyInfo + publicKeyValidator$1, + { + // issuerUniqueID (optional) + name: 'Certificate.TBSCertificate.issuerUniqueID', + tagClass: asn1$4.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.issuerUniqueID.id', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: 'certIssuerUniqueId' + }] + }, { + // subjectUniqueID (optional) + name: 'Certificate.TBSCertificate.subjectUniqueID', + tagClass: asn1$4.Class.CONTEXT_SPECIFIC, + type: 2, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.subjectUniqueID.id', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: 'certSubjectUniqueId' + }] + }, { + // Extensions (optional) + name: 'Certificate.TBSCertificate.extensions', + tagClass: asn1$4.Class.CONTEXT_SPECIFIC, + type: 3, + constructed: true, + captureAsn1: 'certExtensions', + optional: true + }] + }, { + // AlgorithmIdentifier (signature algorithm) + name: 'Certificate.signatureAlgorithm', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: 'Certificate.signatureAlgorithm.algorithm', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.OID, + constructed: false, + capture: 'certSignatureOid' + }, { + name: 'Certificate.TBSCertificate.signature.parameters', + tagClass: asn1$4.Class.UNIVERSAL, + optional: true, + captureAsn1: 'certSignatureParams' + }] + }, { + // SignatureValue + name: 'Certificate.signatureValue', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'certSignature' + }] +}; + +var rsassaPssParameterValidator = { + name: 'rsapss', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'rsapss.hashAlgorithm', + tagClass: asn1$4.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + value: [{ + name: 'rsapss.hashAlgorithm.AlgorithmIdentifier', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.OID, + constructed: false, + capture: 'hashOid' + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }, { + name: 'rsapss.maskGenAlgorithm', + tagClass: asn1$4.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.OID, + constructed: false, + capture: 'maskGenOid' + }, { + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.OID, + constructed: false, + capture: 'maskGenHashOid' + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }] + }, { + name: 'rsapss.saltLength', + tagClass: asn1$4.Class.CONTEXT_SPECIFIC, + type: 2, + optional: true, + value: [{ + name: 'rsapss.saltLength.saltLength', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Class.INTEGER, + constructed: false, + capture: 'saltLength' + }] + }, { + name: 'rsapss.trailerField', + tagClass: asn1$4.Class.CONTEXT_SPECIFIC, + type: 3, + optional: true, + value: [{ + name: 'rsapss.trailer.trailer', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Class.INTEGER, + constructed: false, + capture: 'trailer' + }] + }] +}; + +// validator for a CertificationRequestInfo structure +var certificationRequestInfoValidator = { + name: 'CertificationRequestInfo', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certificationRequestInfo', + value: [{ + name: 'CertificationRequestInfo.integer', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.INTEGER, + constructed: false, + capture: 'certificationRequestInfoVersion' + }, { + // Name (subject) (RDNSequence) + name: 'CertificationRequestInfo.subject', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certificationRequestInfoSubject' + }, + // SubjectPublicKeyInfo + publicKeyValidator$1, + { + name: 'CertificationRequestInfo.attributes', + tagClass: asn1$4.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: 'certificationRequestInfoAttributes', + value: [{ + name: 'CertificationRequestInfo.attributes', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'CertificationRequestInfo.attributes.type', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.OID, + constructed: false + }, { + name: 'CertificationRequestInfo.attributes.value', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SET, + constructed: true + }] + }] + }] +}; + +// validator for a CertificationRequest structure +var certificationRequestValidator = { + name: 'CertificationRequest', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + captureAsn1: 'csr', + value: [ + certificationRequestInfoValidator, { + // AlgorithmIdentifier (signature algorithm) + name: 'CertificationRequest.signatureAlgorithm', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: 'CertificationRequest.signatureAlgorithm.algorithm', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.OID, + constructed: false, + capture: 'csrSignatureOid' + }, { + name: 'CertificationRequest.signatureAlgorithm.parameters', + tagClass: asn1$4.Class.UNIVERSAL, + optional: true, + captureAsn1: 'csrSignatureParams' + }] + }, { + // signature + name: 'CertificationRequest.signature', + tagClass: asn1$4.Class.UNIVERSAL, + type: asn1$4.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'csrSignature' + } + ] +}; + +/** + * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName + * sets into an array with objects that have type and value properties. + * + * @param rdn the RDNSequence to convert. + * @param md a message digest to append type and value to if provided. + */ +pki$2.RDNAttributesAsArray = function(rdn, md) { + var rval = []; + + // each value in 'rdn' in is a SET of RelativeDistinguishedName + var set, attr, obj; + for(var si = 0; si < rdn.value.length; ++si) { + // get the RelativeDistinguishedName set + set = rdn.value[si]; + + // each value in the SET is an AttributeTypeAndValue sequence + // containing first a type (an OID) and second a value (defined by + // the OID) + for(var i = 0; i < set.value.length; ++i) { + obj = {}; + attr = set.value[i]; + obj.type = asn1$4.derToOid(attr.value[0].value); + obj.value = attr.value[1].value; + obj.valueTagClass = attr.value[1].type; + // if the OID is known, get its name and short name + if(obj.type in oids) { + obj.name = oids[obj.type]; + if(obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + if(md) { + md.update(obj.type); + md.update(obj.value); + } + rval.push(obj); + } + } + + return rval; +}; + +/** + * Converts ASN.1 CRIAttributes into an array with objects that have type and + * value properties. + * + * @param attributes the CRIAttributes to convert. + */ +pki$2.CRIAttributesAsArray = function(attributes) { + var rval = []; + + // each value in 'attributes' in is a SEQUENCE with an OID and a SET + for(var si = 0; si < attributes.length; ++si) { + // get the attribute sequence + var seq = attributes[si]; + + // each value in the SEQUENCE containing first a type (an OID) and + // second a set of values (defined by the OID) + var type = asn1$4.derToOid(seq.value[0].value); + var values = seq.value[1].value; + for(var vi = 0; vi < values.length; ++vi) { + var obj = {}; + obj.type = type; + obj.value = values[vi].value; + obj.valueTagClass = values[vi].type; + // if the OID is known, get its name and short name + if(obj.type in oids) { + obj.name = oids[obj.type]; + if(obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + // parse extensions + if(obj.type === oids.extensionRequest) { + obj.extensions = []; + for(var ei = 0; ei < obj.value.length; ++ei) { + obj.extensions.push(pki$2.certificateExtensionFromAsn1(obj.value[ei])); + } + } + rval.push(obj); + } + } + + return rval; +}; + +/** + * Gets an issuer or subject attribute from its name, type, or short name. + * + * @param obj the issuer or subject object. + * @param options a short name string or an object with: + * shortName the short name for the attribute. + * name the name for the attribute. + * type the type for the attribute. + * + * @return the attribute. + */ +function _getAttribute(obj, options) { + if(typeof options === 'string') { + options = {shortName: options}; + } + + var rval = null; + var attr; + for(var i = 0; rval === null && i < obj.attributes.length; ++i) { + attr = obj.attributes[i]; + if(options.type && options.type === attr.type) { + rval = attr; + } else if(options.name && options.name === attr.name) { + rval = attr; + } else if(options.shortName && options.shortName === attr.shortName) { + rval = attr; + } + } + return rval; +} + +/** + * Converts signature parameters from ASN.1 structure. + * + * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had + * no parameters. + * + * RSASSA-PSS-params ::= SEQUENCE { + * hashAlgorithm [0] HashAlgorithm DEFAULT + * sha1Identifier, + * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT + * mgf1SHA1Identifier, + * saltLength [2] INTEGER DEFAULT 20, + * trailerField [3] INTEGER DEFAULT 1 + * } + * + * HashAlgorithm ::= AlgorithmIdentifier + * + * MaskGenAlgorithm ::= AlgorithmIdentifier + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * @param oid The OID specifying the signature algorithm + * @param obj The ASN.1 structure holding the parameters + * @param fillDefaults Whether to use return default values where omitted + * @return signature parameter object + */ +var _readSignatureParameters = function(oid, obj, fillDefaults) { + var params = {}; + + if(oid !== oids['RSASSA-PSS']) { + return params; + } + + if(fillDefaults) { + params = { + hash: { + algorithmOid: oids['sha1'] + }, + mgf: { + algorithmOid: oids['mgf1'], + hash: { + algorithmOid: oids['sha1'] + } + }, + saltLength: 20 + }; + } + + var capture = {}; + var errors = []; + if(!asn1$4.validate(obj, rsassaPssParameterValidator, capture, errors)) { + var error = new Error('Cannot read RSASSA-PSS parameter block.'); + error.errors = errors; + throw error; + } + + if(capture.hashOid !== undefined) { + params.hash = params.hash || {}; + params.hash.algorithmOid = asn1$4.derToOid(capture.hashOid); + } + + if(capture.maskGenOid !== undefined) { + params.mgf = params.mgf || {}; + params.mgf.algorithmOid = asn1$4.derToOid(capture.maskGenOid); + params.mgf.hash = params.mgf.hash || {}; + params.mgf.hash.algorithmOid = asn1$4.derToOid(capture.maskGenHashOid); + } + + if(capture.saltLength !== undefined) { + params.saltLength = capture.saltLength.charCodeAt(0); + } + + return params; +}; + +/** + * Converts an X.509 certificate from PEM format. + * + * Note: If the certificate is to be verified then compute hash should + * be set to true. This will scan the TBSCertificate part of the ASN.1 + * object while it is converted so it doesn't need to be converted back + * to ASN.1-DER-encoding later. + * + * @param pem the PEM-formatted certificate. + * @param computeHash true to compute the hash for verification. + * @param strict true to be strict when checking ASN.1 value lengths, false to + * allow truncated values (default: true). + * + * @return the certificate. + */ +pki$2.certificateFromPem = function(pem, computeHash, strict) { + var msg = forge$e.pem.decode(pem)[0]; + + if(msg.type !== 'CERTIFICATE' && + msg.type !== 'X509 CERTIFICATE' && + msg.type !== 'TRUSTED CERTIFICATE') { + var error = new Error( + 'Could not convert certificate from PEM; PEM header type ' + + 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error( + 'Could not convert certificate from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1$4.fromDer(msg.body, strict); + + return pki$2.certificateFromAsn1(obj, computeHash); +}; + +/** + * Converts an X.509 certificate to PEM format. + * + * @param cert the certificate. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted certificate. + */ +pki$2.certificateToPem = function(cert, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'CERTIFICATE', + body: asn1$4.toDer(pki$2.certificateToAsn1(cert)).getBytes() + }; + return forge$e.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts an RSA public key from PEM format. + * + * @param pem the PEM-formatted public key. + * + * @return the public key. + */ +pki$2.publicKeyFromPem = function(pem) { + var msg = forge$e.pem.decode(pem)[0]; + + if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') { + var error = new Error('Could not convert public key from PEM; PEM header ' + + 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert public key from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1$4.fromDer(msg.body); + + return pki$2.publicKeyFromAsn1(obj); +}; + +/** + * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo). + * + * @param key the public key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted public key. + */ +pki$2.publicKeyToPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'PUBLIC KEY', + body: asn1$4.toDer(pki$2.publicKeyToAsn1(key)).getBytes() + }; + return forge$e.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts an RSA public key to PEM format (using an RSAPublicKey). + * + * @param key the public key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted public key. + */ +pki$2.publicKeyToRSAPublicKeyPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'RSA PUBLIC KEY', + body: asn1$4.toDer(pki$2.publicKeyToRSAPublicKey(key)).getBytes() + }; + return forge$e.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Gets a fingerprint for the given public key. + * + * @param options the options to use. + * [md] the message digest object to use (defaults to forge.md.sha1). + * [type] the type of fingerprint, such as 'RSAPublicKey', + * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey'). + * [encoding] an alternative output encoding, such as 'hex' + * (defaults to none, outputs a byte buffer). + * [delimiter] the delimiter to use between bytes for 'hex' encoded + * output, eg: ':' (defaults to none). + * + * @return the fingerprint as a byte buffer or other encoding based on options. + */ +pki$2.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md = options.md || forge$e.md.sha1.create(); + var type = options.type || 'RSAPublicKey'; + + var bytes; + switch(type) { + case 'RSAPublicKey': + bytes = asn1$4.toDer(pki$2.publicKeyToRSAPublicKey(key)).getBytes(); + break; + case 'SubjectPublicKeyInfo': + bytes = asn1$4.toDer(pki$2.publicKeyToAsn1(key)).getBytes(); + break; + default: + throw new Error('Unknown fingerprint type "' + options.type + '".'); + } + + // hash public key bytes + md.start(); + md.update(bytes); + var digest = md.digest(); + if(options.encoding === 'hex') { + var hex = digest.toHex(); + if(options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if(options.encoding === 'binary') { + return digest.getBytes(); + } else if(options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; +}; + +/** + * Converts a PKCS#10 certification request (CSR) from PEM format. + * + * Note: If the certification request is to be verified then compute hash + * should be set to true. This will scan the CertificationRequestInfo part of + * the ASN.1 object while it is converted so it doesn't need to be converted + * back to ASN.1-DER-encoding later. + * + * @param pem the PEM-formatted certificate. + * @param computeHash true to compute the hash for verification. + * @param strict true to be strict when checking ASN.1 value lengths, false to + * allow truncated values (default: true). + * + * @return the certification request (CSR). + */ +pki$2.certificationRequestFromPem = function(pem, computeHash, strict) { + var msg = forge$e.pem.decode(pem)[0]; + + if(msg.type !== 'CERTIFICATE REQUEST') { + var error = new Error('Could not convert certification request from PEM; ' + + 'PEM header type is not "CERTIFICATE REQUEST".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certification request from PEM; ' + + 'PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1$4.fromDer(msg.body, strict); + + return pki$2.certificationRequestFromAsn1(obj, computeHash); +}; + +/** + * Converts a PKCS#10 certification request (CSR) to PEM format. + * + * @param csr the certification request. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted certification request. + */ +pki$2.certificationRequestToPem = function(csr, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'CERTIFICATE REQUEST', + body: asn1$4.toDer(pki$2.certificationRequestToAsn1(csr)).getBytes() + }; + return forge$e.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Creates an empty X.509v3 RSA certificate. + * + * @return the certificate. + */ +pki$2.createCertificate = function() { + var cert = {}; + cert.version = 0x02; + cert.serialNumber = '00'; + cert.signatureOid = null; + cert.signature = null; + cert.siginfo = {}; + cert.siginfo.algorithmOid = null; + cert.validity = {}; + cert.validity.notBefore = new Date(); + cert.validity.notAfter = new Date(); + + cert.issuer = {}; + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); + }; + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = []; + cert.issuer.hash = null; + + cert.subject = {}; + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = []; + cert.subject.hash = null; + + cert.extensions = []; + cert.publicKey = null; + cert.md = null; + + /** + * Sets the subject of this certificate. + * + * @param attrs the array of subject attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + cert.setSubject = function(attrs, uniqueId) { + // set new attributes, clear hash + _fillMissingFields(attrs); + cert.subject.attributes = attrs; + delete cert.subject.uniqueId; + if(uniqueId) { + // TODO: support arbitrary bit length ids + cert.subject.uniqueId = uniqueId; + } + cert.subject.hash = null; + }; + + /** + * Sets the issuer of this certificate. + * + * @param attrs the array of issuer attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + cert.setIssuer = function(attrs, uniqueId) { + // set new attributes, clear hash + _fillMissingFields(attrs); + cert.issuer.attributes = attrs; + delete cert.issuer.uniqueId; + if(uniqueId) { + // TODO: support arbitrary bit length ids + cert.issuer.uniqueId = uniqueId; + } + cert.issuer.hash = null; + }; + + /** + * Sets the extensions of this certificate. + * + * @param exts the array of extensions to use. + */ + cert.setExtensions = function(exts) { + for(var i = 0; i < exts.length; ++i) { + _fillMissingExtensionFields(exts[i], {cert: cert}); + } + // set new extensions + cert.extensions = exts; + }; + + /** + * Gets an extension by its name or id. + * + * @param options the name to use or an object with: + * name the name to use. + * id the id to use. + * + * @return the extension or null if not found. + */ + cert.getExtension = function(options) { + if(typeof options === 'string') { + options = {name: options}; + } + + var rval = null; + var ext; + for(var i = 0; rval === null && i < cert.extensions.length; ++i) { + ext = cert.extensions[i]; + if(options.id && ext.id === options.id) { + rval = ext; + } else if(options.name && ext.name === options.name) { + rval = ext; + } + } + return rval; + }; + + /** + * Signs this certificate using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + cert.sign = function(key, md) { + // TODO: get signature OID from private key + cert.md = md || forge$e.md.sha1.create(); + var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption']; + if(!algorithmOid) { + var error = new Error('Could not compute certificate digest. ' + + 'Unknown message digest algorithm OID.'); + error.algorithm = cert.md.algorithm; + throw error; + } + cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; + + // get TBSCertificate, convert to DER + cert.tbsCertificate = pki$2.getTBSCertificate(cert); + var bytes = asn1$4.toDer(cert.tbsCertificate); + + // digest and sign + cert.md.update(bytes.getBytes()); + cert.signature = key.sign(cert.md); + }; + + /** + * Attempts verify the signature on the passed certificate using this + * certificate's public key. + * + * @param child the certificate to verify. + * + * @return true if verified, false if not. + */ + cert.verify = function(child) { + var rval = false; + + if(!cert.issued(child)) { + var issuer = child.issuer; + var subject = cert.subject; + var error = new Error( + 'The parent certificate did not issue the given child ' + + 'certificate; the child certificate\'s issuer does not match the ' + + 'parent\'s subject.'); + error.expectedIssuer = issuer.attributes; + error.actualIssuer = subject.attributes; + throw error; + } + + var md = child.md; + if(md === null) { + // check signature OID for supported signature types + if(child.signatureOid in oids) { + var oid = oids[child.signatureOid]; + switch(oid) { + case 'sha1WithRSAEncryption': + md = forge$e.md.sha1.create(); + break; + case 'md5WithRSAEncryption': + md = forge$e.md.md5.create(); + break; + case 'sha256WithRSAEncryption': + md = forge$e.md.sha256.create(); + break; + case 'sha384WithRSAEncryption': + md = forge$e.md.sha384.create(); + break; + case 'sha512WithRSAEncryption': + md = forge$e.md.sha512.create(); + break; + case 'RSASSA-PSS': + md = forge$e.md.sha256.create(); + break; + } + } + if(md === null) { + var error = new Error('Could not compute certificate digest. ' + + 'Unknown signature OID.'); + error.signatureOid = child.signatureOid; + throw error; + } + + // produce DER formatted TBSCertificate and digest it + var tbsCertificate = child.tbsCertificate || pki$2.getTBSCertificate(child); + var bytes = asn1$4.toDer(tbsCertificate); + md.update(bytes.getBytes()); + } + + if(md !== null) { + var scheme; + + switch(child.signatureOid) { + case oids.sha1WithRSAEncryption: + scheme = undefined; /* use PKCS#1 v1.5 padding scheme */ + break; + case oids['RSASSA-PSS']: + var hash, mgf; + + /* initialize mgf */ + hash = oids[child.signatureParameters.mgf.hash.algorithmOid]; + if(hash === undefined || forge$e.md[hash] === undefined) { + var error = new Error('Unsupported MGF hash function.'); + error.oid = child.signatureParameters.mgf.hash.algorithmOid; + error.name = hash; + throw error; + } + + mgf = oids[child.signatureParameters.mgf.algorithmOid]; + if(mgf === undefined || forge$e.mgf[mgf] === undefined) { + var error = new Error('Unsupported MGF function.'); + error.oid = child.signatureParameters.mgf.algorithmOid; + error.name = mgf; + throw error; + } + + mgf = forge$e.mgf[mgf].create(forge$e.md[hash].create()); + + /* initialize hash function */ + hash = oids[child.signatureParameters.hash.algorithmOid]; + if(hash === undefined || forge$e.md[hash] === undefined) { + throw { + message: 'Unsupported RSASSA-PSS hash function.', + oid: child.signatureParameters.hash.algorithmOid, + name: hash + }; + } + + scheme = forge$e.pss.create(forge$e.md[hash].create(), mgf, + child.signatureParameters.saltLength); + break; + } + + // verify signature on cert using public key + rval = cert.publicKey.verify( + md.digest().getBytes(), child.signature, scheme); + } + + return rval; + }; + + /** + * Returns true if this certificate's issuer matches the passed + * certificate's subject. Note that no signature check is performed. + * + * @param parent the certificate to check. + * + * @return true if this certificate's issuer matches the passed certificate's + * subject. + */ + cert.isIssuer = function(parent) { + var rval = false; + + var i = cert.issuer; + var s = parent.subject; + + // compare hashes if present + if(i.hash && s.hash) { + rval = (i.hash === s.hash); + } else if(i.attributes.length === s.attributes.length) { + // all attributes are the same so issuer matches subject + rval = true; + var iattr, sattr; + for(var n = 0; rval && n < i.attributes.length; ++n) { + iattr = i.attributes[n]; + sattr = s.attributes[n]; + if(iattr.type !== sattr.type || iattr.value !== sattr.value) { + // attribute mismatch + rval = false; + } + } + } + + return rval; + }; + + /** + * Returns true if this certificate's subject matches the issuer of the + * given certificate). Note that not signature check is performed. + * + * @param child the certificate to check. + * + * @return true if this certificate's subject matches the passed + * certificate's issuer. + */ + cert.issued = function(child) { + return child.isIssuer(cert); + }; + + /** + * Generates the subjectKeyIdentifier for this certificate as byte buffer. + * + * @return the subjectKeyIdentifier for this certificate as byte buffer. + */ + cert.generateSubjectKeyIdentifier = function() { + /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either: + + (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the + value of the BIT STRING subjectPublicKey (excluding the tag, + length, and number of unused bits). + + (2) The keyIdentifier is composed of a four bit type field with + the value 0100 followed by the least significant 60 bits of the + SHA-1 hash of the value of the BIT STRING subjectPublicKey + (excluding the tag, length, and number of unused bit string bits). + */ + + // skipping the tag, length, and number of unused bits is the same + // as just using the RSAPublicKey (for RSA keys, which are the + // only ones supported) + return pki$2.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'}); + }; + + /** + * Verifies the subjectKeyIdentifier extension value for this certificate + * against its public key. If no extension is found, false will be + * returned. + * + * @return true if verified, false if not. + */ + cert.verifySubjectKeyIdentifier = function() { + var oid = oids['subjectKeyIdentifier']; + for(var i = 0; i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if(ext.id === oid) { + var ski = cert.generateSubjectKeyIdentifier().getBytes(); + return (forge$e.util.hexToBytes(ext.subjectKeyIdentifier) === ski); + } + } + return false; + }; + + return cert; +}; + +/** + * Converts an X.509v3 RSA certificate from an ASN.1 object. + * + * Note: If the certificate is to be verified then compute hash should + * be set to true. There is currently no implementation for converting + * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1 + * object needs to be scanned before the cert object is created. + * + * @param obj the asn1 representation of an X.509v3 RSA certificate. + * @param computeHash true to compute the hash for verification. + * + * @return the certificate. + */ +pki$2.certificateFromAsn1 = function(obj, computeHash) { + // validate certificate and capture data + var capture = {}; + var errors = []; + if(!asn1$4.validate(obj, x509CertificateValidator, capture, errors)) { + var error = new Error('Cannot read X.509 certificate. ' + + 'ASN.1 object is not an X509v3 Certificate.'); + error.errors = errors; + throw error; + } + + // get oid + var oid = asn1$4.derToOid(capture.publicKeyOid); + if(oid !== pki$2.oids.rsaEncryption) { + throw new Error('Cannot read public key. OID is not RSA.'); + } + + // create certificate + var cert = pki$2.createCertificate(); + cert.version = capture.certVersion ? + capture.certVersion.charCodeAt(0) : 0; + var serial = forge$e.util.createBuffer(capture.certSerialNumber); + cert.serialNumber = serial.toHex(); + cert.signatureOid = forge$e.asn1.derToOid(capture.certSignatureOid); + cert.signatureParameters = _readSignatureParameters( + cert.signatureOid, capture.certSignatureParams, true); + cert.siginfo.algorithmOid = forge$e.asn1.derToOid(capture.certinfoSignatureOid); + cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid, + capture.certinfoSignatureParams, false); + cert.signature = capture.certSignature; + + var validity = []; + if(capture.certValidity1UTCTime !== undefined) { + validity.push(asn1$4.utcTimeToDate(capture.certValidity1UTCTime)); + } + if(capture.certValidity2GeneralizedTime !== undefined) { + validity.push(asn1$4.generalizedTimeToDate( + capture.certValidity2GeneralizedTime)); + } + if(capture.certValidity3UTCTime !== undefined) { + validity.push(asn1$4.utcTimeToDate(capture.certValidity3UTCTime)); + } + if(capture.certValidity4GeneralizedTime !== undefined) { + validity.push(asn1$4.generalizedTimeToDate( + capture.certValidity4GeneralizedTime)); + } + if(validity.length > 2) { + throw new Error('Cannot read notBefore/notAfter validity times; more ' + + 'than two times were provided in the certificate.'); + } + if(validity.length < 2) { + throw new Error('Cannot read notBefore/notAfter validity times; they ' + + 'were not provided as either UTCTime or GeneralizedTime.'); + } + cert.validity.notBefore = validity[0]; + cert.validity.notAfter = validity[1]; + + // keep TBSCertificate to preserve signature when exporting + cert.tbsCertificate = capture.tbsCertificate; + + if(computeHash) { + // check signature OID for supported signature types + cert.md = null; + if(cert.signatureOid in oids) { + var oid = oids[cert.signatureOid]; + switch(oid) { + case 'sha1WithRSAEncryption': + cert.md = forge$e.md.sha1.create(); + break; + case 'md5WithRSAEncryption': + cert.md = forge$e.md.md5.create(); + break; + case 'sha256WithRSAEncryption': + cert.md = forge$e.md.sha256.create(); + break; + case 'sha384WithRSAEncryption': + cert.md = forge$e.md.sha384.create(); + break; + case 'sha512WithRSAEncryption': + cert.md = forge$e.md.sha512.create(); + break; + case 'RSASSA-PSS': + cert.md = forge$e.md.sha256.create(); + break; + } + } + if(cert.md === null) { + var error = new Error('Could not compute certificate digest. ' + + 'Unknown signature OID.'); + error.signatureOid = cert.signatureOid; + throw error; + } + + // produce DER formatted TBSCertificate and digest it + var bytes = asn1$4.toDer(cert.tbsCertificate); + cert.md.update(bytes.getBytes()); + } + + // handle issuer, build issuer message digest + var imd = forge$e.md.sha1.create(); + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); + }; + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = pki$2.RDNAttributesAsArray(capture.certIssuer, imd); + if(capture.certIssuerUniqueId) { + cert.issuer.uniqueId = capture.certIssuerUniqueId; + } + cert.issuer.hash = imd.digest().toHex(); + + // handle subject, build subject message digest + var smd = forge$e.md.sha1.create(); + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = pki$2.RDNAttributesAsArray(capture.certSubject, smd); + if(capture.certSubjectUniqueId) { + cert.subject.uniqueId = capture.certSubjectUniqueId; + } + cert.subject.hash = smd.digest().toHex(); + + // handle extensions + if(capture.certExtensions) { + cert.extensions = pki$2.certificateExtensionsFromAsn1(capture.certExtensions); + } else { + cert.extensions = []; + } + + // convert RSA public key from ASN.1 + cert.publicKey = pki$2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + + return cert; +}; + +/** + * Converts an ASN.1 extensions object (with extension sequences as its + * values) into an array of extension objects with types and values. + * + * Supported extensions: + * + * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } + * KeyUsage ::= BIT STRING { + * digitalSignature (0), + * nonRepudiation (1), + * keyEncipherment (2), + * dataEncipherment (3), + * keyAgreement (4), + * keyCertSign (5), + * cRLSign (6), + * encipherOnly (7), + * decipherOnly (8) + * } + * + * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } + * BasicConstraints ::= SEQUENCE { + * cA BOOLEAN DEFAULT FALSE, + * pathLenConstraint INTEGER (0..MAX) OPTIONAL + * } + * + * subjectAltName EXTENSION ::= { + * SYNTAX GeneralNames + * IDENTIFIED BY id-ce-subjectAltName + * } + * + * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName + * + * GeneralName ::= CHOICE { + * otherName [0] INSTANCE OF OTHER-NAME, + * rfc822Name [1] IA5String, + * dNSName [2] IA5String, + * x400Address [3] ORAddress, + * directoryName [4] Name, + * ediPartyName [5] EDIPartyName, + * uniformResourceIdentifier [6] IA5String, + * IPAddress [7] OCTET STRING, + * registeredID [8] OBJECT IDENTIFIER + * } + * + * OTHER-NAME ::= TYPE-IDENTIFIER + * + * EDIPartyName ::= SEQUENCE { + * nameAssigner [0] DirectoryString {ub-name} OPTIONAL, + * partyName [1] DirectoryString {ub-name} + * } + * + * @param exts the extensions ASN.1 with extension sequences to parse. + * + * @return the array. + */ +pki$2.certificateExtensionsFromAsn1 = function(exts) { + var rval = []; + for(var i = 0; i < exts.value.length; ++i) { + // get extension sequence + var extseq = exts.value[i]; + for(var ei = 0; ei < extseq.value.length; ++ei) { + rval.push(pki$2.certificateExtensionFromAsn1(extseq.value[ei])); + } + } + + return rval; +}; + +/** + * Parses a single certificate extension from ASN.1. + * + * @param ext the extension in ASN.1 format. + * + * @return the parsed extension as an object. + */ +pki$2.certificateExtensionFromAsn1 = function(ext) { + // an extension has: + // [0] extnID OBJECT IDENTIFIER + // [1] critical BOOLEAN DEFAULT FALSE + // [2] extnValue OCTET STRING + var e = {}; + e.id = asn1$4.derToOid(ext.value[0].value); + e.critical = false; + if(ext.value[1].type === asn1$4.Type.BOOLEAN) { + e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00); + e.value = ext.value[2].value; + } else { + e.value = ext.value[1].value; + } + // if the oid is known, get its name + if(e.id in oids) { + e.name = oids[e.id]; + + // handle key usage + if(e.name === 'keyUsage') { + // get value as BIT STRING + var ev = asn1$4.fromDer(e.value); + var b2 = 0x00; + var b3 = 0x00; + if(ev.value.length > 1) { + // skip first byte, just indicates unused bits which + // will be padded with 0s anyway + // get bytes with flag bits + b2 = ev.value.charCodeAt(1); + b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; + } + // set flags + e.digitalSignature = (b2 & 0x80) === 0x80; + e.nonRepudiation = (b2 & 0x40) === 0x40; + e.keyEncipherment = (b2 & 0x20) === 0x20; + e.dataEncipherment = (b2 & 0x10) === 0x10; + e.keyAgreement = (b2 & 0x08) === 0x08; + e.keyCertSign = (b2 & 0x04) === 0x04; + e.cRLSign = (b2 & 0x02) === 0x02; + e.encipherOnly = (b2 & 0x01) === 0x01; + e.decipherOnly = (b3 & 0x80) === 0x80; + } else if(e.name === 'basicConstraints') { + // handle basic constraints + // get value as SEQUENCE + var ev = asn1$4.fromDer(e.value); + // get cA BOOLEAN flag (defaults to false) + if(ev.value.length > 0 && ev.value[0].type === asn1$4.Type.BOOLEAN) { + e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00); + } else { + e.cA = false; + } + // get path length constraint + var value = null; + if(ev.value.length > 0 && ev.value[0].type === asn1$4.Type.INTEGER) { + value = ev.value[0].value; + } else if(ev.value.length > 1) { + value = ev.value[1].value; + } + if(value !== null) { + e.pathLenConstraint = asn1$4.derToInteger(value); + } + } else if(e.name === 'extKeyUsage') { + // handle extKeyUsage + // value is a SEQUENCE of OIDs + var ev = asn1$4.fromDer(e.value); + for(var vi = 0; vi < ev.value.length; ++vi) { + var oid = asn1$4.derToOid(ev.value[vi].value); + if(oid in oids) { + e[oids[oid]] = true; + } else { + e[oid] = true; + } + } + } else if(e.name === 'nsCertType') { + // handle nsCertType + // get value as BIT STRING + var ev = asn1$4.fromDer(e.value); + var b2 = 0x00; + if(ev.value.length > 1) { + // skip first byte, just indicates unused bits which + // will be padded with 0s anyway + // get bytes with flag bits + b2 = ev.value.charCodeAt(1); + } + // set flags + e.client = (b2 & 0x80) === 0x80; + e.server = (b2 & 0x40) === 0x40; + e.email = (b2 & 0x20) === 0x20; + e.objsign = (b2 & 0x10) === 0x10; + e.reserved = (b2 & 0x08) === 0x08; + e.sslCA = (b2 & 0x04) === 0x04; + e.emailCA = (b2 & 0x02) === 0x02; + e.objCA = (b2 & 0x01) === 0x01; + } else if( + e.name === 'subjectAltName' || + e.name === 'issuerAltName') { + // handle subjectAltName/issuerAltName + e.altNames = []; + + // ev is a SYNTAX SEQUENCE + var gn; + var ev = asn1$4.fromDer(e.value); + for(var n = 0; n < ev.value.length; ++n) { + // get GeneralName + gn = ev.value[n]; + + var altName = { + type: gn.type, + value: gn.value + }; + e.altNames.push(altName); + + // Note: Support for types 1,2,6,7,8 + switch(gn.type) { + // rfc822Name + case 1: + // dNSName + case 2: + // uniformResourceIdentifier (URI) + case 6: + break; + // IPAddress + case 7: + // convert to IPv4/IPv6 string representation + altName.ip = forge$e.util.bytesToIP(gn.value); + break; + // registeredID + case 8: + altName.oid = asn1$4.derToOid(gn.value); + break; + // unsupported + } + } + } else if(e.name === 'subjectKeyIdentifier') { + // value is an OCTETSTRING w/the hash of the key-type specific + // public key structure (eg: RSAPublicKey) + var ev = asn1$4.fromDer(e.value); + e.subjectKeyIdentifier = forge$e.util.bytesToHex(ev.value); + } + } + return e; +}; + +/** + * Converts a PKCS#10 certification request (CSR) from an ASN.1 object. + * + * Note: If the certification request is to be verified then compute hash + * should be set to true. There is currently no implementation for converting + * a certificate back to ASN.1 so the CertificationRequestInfo part of the + * ASN.1 object needs to be scanned before the csr object is created. + * + * @param obj the asn1 representation of a PKCS#10 certification request (CSR). + * @param computeHash true to compute the hash for verification. + * + * @return the certification request (CSR). + */ +pki$2.certificationRequestFromAsn1 = function(obj, computeHash) { + // validate certification request and capture data + var capture = {}; + var errors = []; + if(!asn1$4.validate(obj, certificationRequestValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#10 certificate request. ' + + 'ASN.1 object is not a PKCS#10 CertificationRequest.'); + error.errors = errors; + throw error; + } + + // get oid + var oid = asn1$4.derToOid(capture.publicKeyOid); + if(oid !== pki$2.oids.rsaEncryption) { + throw new Error('Cannot read public key. OID is not RSA.'); + } + + // create certification request + var csr = pki$2.createCertificationRequest(); + csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; + csr.signatureOid = forge$e.asn1.derToOid(capture.csrSignatureOid); + csr.signatureParameters = _readSignatureParameters( + csr.signatureOid, capture.csrSignatureParams, true); + csr.siginfo.algorithmOid = forge$e.asn1.derToOid(capture.csrSignatureOid); + csr.siginfo.parameters = _readSignatureParameters( + csr.siginfo.algorithmOid, capture.csrSignatureParams, false); + csr.signature = capture.csrSignature; + + // keep CertificationRequestInfo to preserve signature when exporting + csr.certificationRequestInfo = capture.certificationRequestInfo; + + if(computeHash) { + // check signature OID for supported signature types + csr.md = null; + if(csr.signatureOid in oids) { + var oid = oids[csr.signatureOid]; + switch(oid) { + case 'sha1WithRSAEncryption': + csr.md = forge$e.md.sha1.create(); + break; + case 'md5WithRSAEncryption': + csr.md = forge$e.md.md5.create(); + break; + case 'sha256WithRSAEncryption': + csr.md = forge$e.md.sha256.create(); + break; + case 'sha384WithRSAEncryption': + csr.md = forge$e.md.sha384.create(); + break; + case 'sha512WithRSAEncryption': + csr.md = forge$e.md.sha512.create(); + break; + case 'RSASSA-PSS': + csr.md = forge$e.md.sha256.create(); + break; + } + } + if(csr.md === null) { + var error = new Error('Could not compute certification request digest. ' + + 'Unknown signature OID.'); + error.signatureOid = csr.signatureOid; + throw error; + } + + // produce DER formatted CertificationRequestInfo and digest it + var bytes = asn1$4.toDer(csr.certificationRequestInfo); + csr.md.update(bytes.getBytes()); + } + + // handle subject, build subject message digest + var smd = forge$e.md.sha1.create(); + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); + }; + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = pki$2.RDNAttributesAsArray( + capture.certificationRequestInfoSubject, smd); + csr.subject.hash = smd.digest().toHex(); + + // convert RSA public key from ASN.1 + csr.publicKey = pki$2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + + // convert attributes from ASN.1 + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.attributes = pki$2.CRIAttributesAsArray( + capture.certificationRequestInfoAttributes || []); + + return csr; +}; + +/** + * Creates an empty certification request (a CSR or certificate signing + * request). Once created, its public key and attributes can be set and then + * it can be signed. + * + * @return the empty certification request. + */ +pki$2.createCertificationRequest = function() { + var csr = {}; + csr.version = 0x00; + csr.signatureOid = null; + csr.signature = null; + csr.siginfo = {}; + csr.siginfo.algorithmOid = null; + + csr.subject = {}; + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); + }; + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = []; + csr.subject.hash = null; + + csr.publicKey = null; + csr.attributes = []; + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.md = null; + + /** + * Sets the subject of this certification request. + * + * @param attrs the array of subject attributes to use. + */ + csr.setSubject = function(attrs) { + // set new attributes + _fillMissingFields(attrs); + csr.subject.attributes = attrs; + csr.subject.hash = null; + }; + + /** + * Sets the attributes of this certification request. + * + * @param attrs the array of attributes to use. + */ + csr.setAttributes = function(attrs) { + // set new attributes + _fillMissingFields(attrs); + csr.attributes = attrs; + }; + + /** + * Signs this certification request using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + csr.sign = function(key, md) { + // TODO: get signature OID from private key + csr.md = md || forge$e.md.sha1.create(); + var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption']; + if(!algorithmOid) { + var error = new Error('Could not compute certification request digest. ' + + 'Unknown message digest algorithm OID.'); + error.algorithm = csr.md.algorithm; + throw error; + } + csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; + + // get CertificationRequestInfo, convert to DER + csr.certificationRequestInfo = pki$2.getCertificationRequestInfo(csr); + var bytes = asn1$4.toDer(csr.certificationRequestInfo); + + // digest and sign + csr.md.update(bytes.getBytes()); + csr.signature = key.sign(csr.md); + }; + + /** + * Attempts verify the signature on the passed certification request using + * its public key. + * + * A CSR that has been exported to a file in PEM format can be verified using + * OpenSSL using this command: + * + * openssl req -in -verify -noout -text + * + * @return true if verified, false if not. + */ + csr.verify = function() { + var rval = false; + + var md = csr.md; + if(md === null) { + // check signature OID for supported signature types + if(csr.signatureOid in oids) { + // TODO: create DRY `OID to md` function + var oid = oids[csr.signatureOid]; + switch(oid) { + case 'sha1WithRSAEncryption': + md = forge$e.md.sha1.create(); + break; + case 'md5WithRSAEncryption': + md = forge$e.md.md5.create(); + break; + case 'sha256WithRSAEncryption': + md = forge$e.md.sha256.create(); + break; + case 'sha384WithRSAEncryption': + md = forge$e.md.sha384.create(); + break; + case 'sha512WithRSAEncryption': + md = forge$e.md.sha512.create(); + break; + case 'RSASSA-PSS': + md = forge$e.md.sha256.create(); + break; + } + } + if(md === null) { + var error = new Error( + 'Could not compute certification request digest. ' + + 'Unknown signature OID.'); + error.signatureOid = csr.signatureOid; + throw error; + } + + // produce DER formatted CertificationRequestInfo and digest it + var cri = csr.certificationRequestInfo || + pki$2.getCertificationRequestInfo(csr); + var bytes = asn1$4.toDer(cri); + md.update(bytes.getBytes()); + } + + if(md !== null) { + var scheme; + + switch(csr.signatureOid) { + case oids.sha1WithRSAEncryption: + /* use PKCS#1 v1.5 padding scheme */ + break; + case oids['RSASSA-PSS']: + var hash, mgf; + + /* initialize mgf */ + hash = oids[csr.signatureParameters.mgf.hash.algorithmOid]; + if(hash === undefined || forge$e.md[hash] === undefined) { + var error = new Error('Unsupported MGF hash function.'); + error.oid = csr.signatureParameters.mgf.hash.algorithmOid; + error.name = hash; + throw error; + } + + mgf = oids[csr.signatureParameters.mgf.algorithmOid]; + if(mgf === undefined || forge$e.mgf[mgf] === undefined) { + var error = new Error('Unsupported MGF function.'); + error.oid = csr.signatureParameters.mgf.algorithmOid; + error.name = mgf; + throw error; + } + + mgf = forge$e.mgf[mgf].create(forge$e.md[hash].create()); + + /* initialize hash function */ + hash = oids[csr.signatureParameters.hash.algorithmOid]; + if(hash === undefined || forge$e.md[hash] === undefined) { + var error = new Error('Unsupported RSASSA-PSS hash function.'); + error.oid = csr.signatureParameters.hash.algorithmOid; + error.name = hash; + throw error; + } + + scheme = forge$e.pss.create(forge$e.md[hash].create(), mgf, + csr.signatureParameters.saltLength); + break; + } + + // verify signature on csr using its public key + rval = csr.publicKey.verify( + md.digest().getBytes(), csr.signature, scheme); + } + + return rval; + }; + + return csr; +}; + +/** + * Converts an X.509 subject or issuer to an ASN.1 RDNSequence. + * + * @param obj the subject or issuer (distinguished name). + * + * @return the ASN.1 RDNSequence. + */ +function _dnToAsn1(obj) { + // create an empty RDNSequence + var rval = asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); + + // iterate over attributes + var attr, set; + var attrs = obj.attributes; + for(var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + var value = attr.value; + + // reuse tag class for attribute value if available + var valueTagClass = asn1$4.Type.PRINTABLESTRING; + if('valueTagClass' in attr) { + valueTagClass = attr.valueTagClass; + + if(valueTagClass === asn1$4.Type.UTF8) { + value = forge$e.util.encodeUtf8(value); + } + // FIXME: handle more encodings + } + + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + set = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SET, true, [ + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + // AttributeType + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, + asn1$4.oidToDer(attr.type).getBytes()), + // AttributeValue + asn1$4.create(asn1$4.Class.UNIVERSAL, valueTagClass, false, value) + ]) + ]); + rval.value.push(set); + } + + return rval; +} + +/** + * Fills in missing fields in attributes. + * + * @param attrs the attributes to fill missing fields in. + */ +function _fillMissingFields(attrs) { + var attr; + for(var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + + // populate missing name + if(typeof attr.name === 'undefined') { + if(attr.type && attr.type in pki$2.oids) { + attr.name = pki$2.oids[attr.type]; + } else if(attr.shortName && attr.shortName in _shortNames) { + attr.name = pki$2.oids[_shortNames[attr.shortName]]; + } + } + + // populate missing type (OID) + if(typeof attr.type === 'undefined') { + if(attr.name && attr.name in pki$2.oids) { + attr.type = pki$2.oids[attr.name]; + } else { + var error = new Error('Attribute type not specified.'); + error.attribute = attr; + throw error; + } + } + + // populate missing shortname + if(typeof attr.shortName === 'undefined') { + if(attr.name && attr.name in _shortNames) { + attr.shortName = _shortNames[attr.name]; + } + } + + // convert extensions to value + if(attr.type === oids.extensionRequest) { + attr.valueConstructed = true; + attr.valueTagClass = asn1$4.Type.SEQUENCE; + if(!attr.value && attr.extensions) { + attr.value = []; + for(var ei = 0; ei < attr.extensions.length; ++ei) { + attr.value.push(pki$2.certificateExtensionToAsn1( + _fillMissingExtensionFields(attr.extensions[ei]))); + } + } + } + + if(typeof attr.value === 'undefined') { + var error = new Error('Attribute value not specified.'); + error.attribute = attr; + throw error; + } + } +} + +/** + * Fills in missing fields in certificate extensions. + * + * @param e the extension. + * @param [options] the options to use. + * [cert] the certificate the extensions are for. + * + * @return the extension. + */ +function _fillMissingExtensionFields(e, options) { + options = options || {}; + + // populate missing name + if(typeof e.name === 'undefined') { + if(e.id && e.id in pki$2.oids) { + e.name = pki$2.oids[e.id]; + } + } + + // populate missing id + if(typeof e.id === 'undefined') { + if(e.name && e.name in pki$2.oids) { + e.id = pki$2.oids[e.name]; + } else { + var error = new Error('Extension ID not specified.'); + error.extension = e; + throw error; + } + } + + if(typeof e.value !== 'undefined') { + return e; + } + + // handle missing value: + + // value is a BIT STRING + if(e.name === 'keyUsage') { + // build flags + var unused = 0; + var b2 = 0x00; + var b3 = 0x00; + if(e.digitalSignature) { + b2 |= 0x80; + unused = 7; + } + if(e.nonRepudiation) { + b2 |= 0x40; + unused = 6; + } + if(e.keyEncipherment) { + b2 |= 0x20; + unused = 5; + } + if(e.dataEncipherment) { + b2 |= 0x10; + unused = 4; + } + if(e.keyAgreement) { + b2 |= 0x08; + unused = 3; + } + if(e.keyCertSign) { + b2 |= 0x04; + unused = 2; + } + if(e.cRLSign) { + b2 |= 0x02; + unused = 1; + } + if(e.encipherOnly) { + b2 |= 0x01; + unused = 0; + } + if(e.decipherOnly) { + b3 |= 0x80; + unused = 7; + } + + // create bit string + var value = String.fromCharCode(unused); + if(b3 !== 0) { + value += String.fromCharCode(b2) + String.fromCharCode(b3); + } else if(b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, value); + } else if(e.name === 'basicConstraints') { + // basicConstraints is a SEQUENCE + e.value = asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); + // cA BOOLEAN flag defaults to false + if(e.cA) { + e.value.value.push(asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.BOOLEAN, false, + String.fromCharCode(0xFF))); + } + if('pathLenConstraint' in e) { + e.value.value.push(asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false, + asn1$4.integerToDer(e.pathLenConstraint).getBytes())); + } + } else if(e.name === 'extKeyUsage') { + // extKeyUsage is a SEQUENCE of OIDs + e.value = asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); + var seq = e.value.value; + for(var key in e) { + if(e[key] !== true) { + continue; + } + // key is name in OID map + if(key in oids) { + seq.push(asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, + false, asn1$4.oidToDer(oids[key]).getBytes())); + } else if(key.indexOf('.') !== -1) { + // assume key is an OID + seq.push(asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, + false, asn1$4.oidToDer(key).getBytes())); + } + } + } else if(e.name === 'nsCertType') { + // nsCertType is a BIT STRING + // build flags + var unused = 0; + var b2 = 0x00; + + if(e.client) { + b2 |= 0x80; + unused = 7; + } + if(e.server) { + b2 |= 0x40; + unused = 6; + } + if(e.email) { + b2 |= 0x20; + unused = 5; + } + if(e.objsign) { + b2 |= 0x10; + unused = 4; + } + if(e.reserved) { + b2 |= 0x08; + unused = 3; + } + if(e.sslCA) { + b2 |= 0x04; + unused = 2; + } + if(e.emailCA) { + b2 |= 0x02; + unused = 1; + } + if(e.objCA) { + b2 |= 0x01; + unused = 0; + } + + // create bit string + var value = String.fromCharCode(unused); + if(b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, value); + } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') { + // SYNTAX SEQUENCE + e.value = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); + + var altName; + for(var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + // handle IP + if(altName.type === 7 && altName.ip) { + value = forge$e.util.bytesFromIP(altName.ip); + if(value === null) { + var error = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); + error.extension = e; + throw error; + } + } else if(altName.type === 8) { + // handle OID + if(altName.oid) { + value = asn1$4.oidToDer(asn1$4.oidToDer(altName.oid)); + } else { + // deprecated ... convert value to OID + value = asn1$4.oidToDer(value); + } + } + e.value.value.push(asn1$4.create( + asn1$4.Class.CONTEXT_SPECIFIC, altName.type, false, + value)); + } + } else if(e.name === 'nsComment' && options.cert) { + // sanity check value is ASCII (req'd) and not too big + if(!(/^[\x00-\x7F]*$/.test(e.comment)) || + (e.comment.length < 1) || (e.comment.length > 128)) { + throw new Error('Invalid "nsComment" content.'); + } + // IA5STRING opaque comment + e.value = asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.IA5STRING, false, e.comment); + } else if(e.name === 'subjectKeyIdentifier' && options.cert) { + var ski = options.cert.generateSubjectKeyIdentifier(); + e.subjectKeyIdentifier = ski.toHex(); + // OCTETSTRING w/digest + e.value = asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.OCTETSTRING, false, ski.getBytes()); + } else if(e.name === 'authorityKeyIdentifier' && options.cert) { + // SYNTAX SEQUENCE + e.value = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); + var seq = e.value.value; + + if(e.keyIdentifier) { + var keyIdentifier = (e.keyIdentifier === true ? + options.cert.generateSubjectKeyIdentifier().getBytes() : + e.keyIdentifier); + seq.push( + asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier)); + } + + if(e.authorityCertIssuer) { + var authorityCertIssuer = [ + asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 4, true, [ + _dnToAsn1(e.authorityCertIssuer === true ? + options.cert.issuer : e.authorityCertIssuer) + ]) + ]; + seq.push( + asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer)); + } + + if(e.serialNumber) { + var serialNumber = forge$e.util.hexToBytes(e.serialNumber === true ? + options.cert.serialNumber : e.serialNumber); + seq.push( + asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 2, false, serialNumber)); + } + } else if(e.name === 'cRLDistributionPoints') { + e.value = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); + var seq = e.value.value; + + // Create sub SEQUENCE of DistributionPointName + var subSeq = asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); + + // Create fullName CHOICE + var fullNameGeneralNames = asn1$4.create( + asn1$4.Class.CONTEXT_SPECIFIC, 0, true, []); + var altName; + for(var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + // handle IP + if(altName.type === 7 && altName.ip) { + value = forge$e.util.bytesFromIP(altName.ip); + if(value === null) { + var error = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); + error.extension = e; + throw error; + } + } else if(altName.type === 8) { + // handle OID + if(altName.oid) { + value = asn1$4.oidToDer(asn1$4.oidToDer(altName.oid)); + } else { + // deprecated ... convert value to OID + value = asn1$4.oidToDer(value); + } + } + fullNameGeneralNames.value.push(asn1$4.create( + asn1$4.Class.CONTEXT_SPECIFIC, altName.type, false, + value)); + } + + // Add to the parent SEQUENCE + subSeq.value.push(asn1$4.create( + asn1$4.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames])); + seq.push(subSeq); + } + + // ensure value has been defined by now + if(typeof e.value === 'undefined') { + var error = new Error('Extension value not specified.'); + error.extension = e; + throw error; + } + + return e; +} + +/** + * Convert signature parameters object to ASN.1 + * + * @param {String} oid Signature algorithm OID + * @param params The signature parametrs object + * @return ASN.1 object representing signature parameters + */ +function _signatureParametersToAsn1(oid, params) { + switch(oid) { + case oids['RSASSA-PSS']: + var parts = []; + + if(params.hash.algorithmOid !== undefined) { + parts.push(asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, + asn1$4.oidToDer(params.hash.algorithmOid).getBytes()), + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.NULL, false, '') + ]) + ])); + } + + if(params.mgf.algorithmOid !== undefined) { + parts.push(asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, + asn1$4.oidToDer(params.mgf.algorithmOid).getBytes()), + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, + asn1$4.oidToDer(params.mgf.hash.algorithmOid).getBytes()), + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.NULL, false, '') + ]) + ]) + ])); + } + + if(params.saltLength !== undefined) { + parts.push(asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false, + asn1$4.integerToDer(params.saltLength).getBytes()) + ])); + } + + return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, parts); + + default: + return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.NULL, false, ''); + } +} + +/** + * Converts a certification request's attributes to an ASN.1 set of + * CRIAttributes. + * + * @param csr certification request. + * + * @return the ASN.1 set of CRIAttributes. + */ +function _CRIAttributesToAsn1(csr) { + // create an empty context-specific container + var rval = asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, true, []); + + // no attributes, return empty container + if(csr.attributes.length === 0) { + return rval; + } + + // each attribute has a sequence with a type and a set of values + var attrs = csr.attributes; + for(var i = 0; i < attrs.length; ++i) { + var attr = attrs[i]; + var value = attr.value; + + // reuse tag class for attribute value if available + var valueTagClass = asn1$4.Type.UTF8; + if('valueTagClass' in attr) { + valueTagClass = attr.valueTagClass; + } + if(valueTagClass === asn1$4.Type.UTF8) { + value = forge$e.util.encodeUtf8(value); + } + var valueConstructed = false; + if('valueConstructed' in attr) { + valueConstructed = attr.valueConstructed; + } + // FIXME: handle more encodings + + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + var seq = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + // AttributeType + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, + asn1$4.oidToDer(attr.type).getBytes()), + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SET, true, [ + // AttributeValue + asn1$4.create( + asn1$4.Class.UNIVERSAL, valueTagClass, valueConstructed, value) + ]) + ]); + rval.value.push(seq); + } + + return rval; +} + +var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); +var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); + +/** + * Converts a Date object to ASN.1 + * Handles the different format before and after 1st January 2050 + * + * @param date date object. + * + * @return the ASN.1 object representing the date. + */ +function _dateToAsn1(date) { + if(date >= jan_1_1950 && date < jan_1_2050) { + return asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.UTCTIME, false, + asn1$4.dateToUtcTime(date)); + } else { + return asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.GENERALIZEDTIME, false, + asn1$4.dateToGeneralizedTime(date)); + } +} + +/** + * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate. + * + * @param cert the certificate. + * + * @return the asn1 TBSCertificate. + */ +pki$2.getTBSCertificate = function(cert) { + // TBSCertificate + var notBefore = _dateToAsn1(cert.validity.notBefore); + var notAfter = _dateToAsn1(cert.validity.notAfter); + var tbs = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + // version + asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, true, [ + // integer + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false, + asn1$4.integerToDer(cert.version).getBytes()) + ]), + // serialNumber + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false, + forge$e.util.hexToBytes(cert.serialNumber)), + // signature + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + // algorithm + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, + asn1$4.oidToDer(cert.siginfo.algorithmOid).getBytes()), + // parameters + _signatureParametersToAsn1( + cert.siginfo.algorithmOid, cert.siginfo.parameters) + ]), + // issuer + _dnToAsn1(cert.issuer), + // validity + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + notBefore, + notAfter + ]), + // subject + _dnToAsn1(cert.subject), + // SubjectPublicKeyInfo + pki$2.publicKeyToAsn1(cert.publicKey) + ]); + + if(cert.issuer.uniqueId) { + // issuerUniqueID (optional) + tbs.value.push( + asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0x00) + + cert.issuer.uniqueId + ) + ]) + ); + } + if(cert.subject.uniqueId) { + // subjectUniqueID (optional) + tbs.value.push( + asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0x00) + + cert.subject.uniqueId + ) + ]) + ); + } + + if(cert.extensions.length > 0) { + // extensions (optional) + tbs.value.push(pki$2.certificateExtensionsToAsn1(cert.extensions)); + } + + return tbs; +}; + +/** + * Gets the ASN.1 CertificationRequestInfo part of a + * PKCS#10 CertificationRequest. + * + * @param csr the certification request. + * + * @return the asn1 CertificationRequestInfo. + */ +pki$2.getCertificationRequestInfo = function(csr) { + // CertificationRequestInfo + var cri = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + // version + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false, + asn1$4.integerToDer(csr.version).getBytes()), + // subject + _dnToAsn1(csr.subject), + // SubjectPublicKeyInfo + pki$2.publicKeyToAsn1(csr.publicKey), + // attributes + _CRIAttributesToAsn1(csr) + ]); + + return cri; +}; + +/** + * Converts a DistinguishedName (subject or issuer) to an ASN.1 object. + * + * @param dn the DistinguishedName. + * + * @return the asn1 representation of a DistinguishedName. + */ +pki$2.distinguishedNameToAsn1 = function(dn) { + return _dnToAsn1(dn); +}; + +/** + * Converts an X.509v3 RSA certificate to an ASN.1 object. + * + * @param cert the certificate. + * + * @return the asn1 representation of an X.509v3 RSA certificate. + */ +pki$2.certificateToAsn1 = function(cert) { + // prefer cached TBSCertificate over generating one + var tbsCertificate = cert.tbsCertificate || pki$2.getTBSCertificate(cert); + + // Certificate + return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + // TBSCertificate + tbsCertificate, + // AlgorithmIdentifier (signature algorithm) + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + // algorithm + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, + asn1$4.oidToDer(cert.signatureOid).getBytes()), + // parameters + _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) + ]), + // SignatureValue + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, + String.fromCharCode(0x00) + cert.signature) + ]); +}; + +/** + * Converts X.509v3 certificate extensions to ASN.1. + * + * @param exts the extensions to convert. + * + * @return the extensions in ASN.1 format. + */ +pki$2.certificateExtensionsToAsn1 = function(exts) { + // create top-level extension container + var rval = asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 3, true, []); + + // create extension sequence (stores a sequence for each extension) + var seq = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); + rval.value.push(seq); + + for(var i = 0; i < exts.length; ++i) { + seq.value.push(pki$2.certificateExtensionToAsn1(exts[i])); + } + + return rval; +}; + +/** + * Converts a single certificate extension to ASN.1. + * + * @param ext the extension to convert. + * + * @return the extension in ASN.1 format. + */ +pki$2.certificateExtensionToAsn1 = function(ext) { + // create a sequence for each extension + var extseq = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); + + // extnID (OID) + extseq.value.push(asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, + asn1$4.oidToDer(ext.id).getBytes())); + + // critical defaults to false + if(ext.critical) { + // critical BOOLEAN DEFAULT FALSE + extseq.value.push(asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.BOOLEAN, false, + String.fromCharCode(0xFF))); + } + + var value = ext.value; + if(typeof ext.value !== 'string') { + // value is asn.1 + value = asn1$4.toDer(value).getBytes(); + } + + // extnValue (OCTET STRING) + extseq.value.push(asn1$4.create( + asn1$4.Class.UNIVERSAL, asn1$4.Type.OCTETSTRING, false, value)); + + return extseq; +}; + +/** + * Converts a PKCS#10 certification request to an ASN.1 object. + * + * @param csr the certification request. + * + * @return the asn1 representation of a certification request. + */ +pki$2.certificationRequestToAsn1 = function(csr) { + // prefer cached CertificationRequestInfo over generating one + var cri = csr.certificationRequestInfo || + pki$2.getCertificationRequestInfo(csr); + + // Certificate + return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + // CertificationRequestInfo + cri, + // AlgorithmIdentifier (signature algorithm) + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ + // algorithm + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, + asn1$4.oidToDer(csr.signatureOid).getBytes()), + // parameters + _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) + ]), + // signature + asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, + String.fromCharCode(0x00) + csr.signature) + ]); +}; + +/** + * Creates a CA store. + * + * @param certs an optional array of certificate objects or PEM-formatted + * certificate strings to add to the CA store. + * + * @return the CA store. + */ +pki$2.createCaStore = function(certs) { + // create CA store + var caStore = { + // stored certificates + certs: {} + }; + + /** + * Gets the certificate that issued the passed certificate or its + * 'parent'. + * + * @param cert the certificate to get the parent for. + * + * @return the parent certificate or null if none was found. + */ + caStore.getIssuer = function(cert) { + var rval = getBySubject(cert.issuer); + + // see if there are multiple matches + /*if(forge.util.isArray(rval)) { + // TODO: resolve multiple matches by checking + // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc. + // FIXME: or alternatively do authority key mapping + // if possible (X.509v1 certs can't work?) + throw new Error('Resolving multiple issuer matches not implemented yet.'); + }*/ + + return rval; + }; + + /** + * Adds a trusted certificate to the store. + * + * @param cert the certificate to add as a trusted certificate (either a + * pki.certificate object or a PEM-formatted certificate). + */ + caStore.addCertificate = function(cert) { + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge$e.pki.certificateFromPem(cert); + } + + ensureSubjectHasHash(cert.subject); + + if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store + if(cert.subject.hash in caStore.certs) { + // subject hash already exists, append to array + var tmp = caStore.certs[cert.subject.hash]; + if(!forge$e.util.isArray(tmp)) { + tmp = [tmp]; + } + tmp.push(cert); + caStore.certs[cert.subject.hash] = tmp; + } else { + caStore.certs[cert.subject.hash] = cert; + } + } + }; + + /** + * Checks to see if the given certificate is in the store. + * + * @param cert the certificate to check (either a pki.certificate or a + * PEM-formatted certificate). + * + * @return true if the certificate is in the store, false if not. + */ + caStore.hasCertificate = function(cert) { + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge$e.pki.certificateFromPem(cert); + } + + var match = getBySubject(cert.subject); + if(!match) { + return false; + } + if(!forge$e.util.isArray(match)) { + match = [match]; + } + // compare DER-encoding of certificates + var der1 = asn1$4.toDer(pki$2.certificateToAsn1(cert)).getBytes(); + for(var i = 0; i < match.length; ++i) { + var der2 = asn1$4.toDer(pki$2.certificateToAsn1(match[i])).getBytes(); + if(der1 === der2) { + return true; + } + } + return false; + }; + + /** + * Lists all of the certificates kept in the store. + * + * @return an array of all of the pki.certificate objects in the store. + */ + caStore.listAllCertificates = function() { + var certList = []; + + for(var hash in caStore.certs) { + if(caStore.certs.hasOwnProperty(hash)) { + var value = caStore.certs[hash]; + if(!forge$e.util.isArray(value)) { + certList.push(value); + } else { + for(var i = 0; i < value.length; ++i) { + certList.push(value[i]); + } + } + } + } + + return certList; + }; + + /** + * Removes a certificate from the store. + * + * @param cert the certificate to remove (either a pki.certificate or a + * PEM-formatted certificate). + * + * @return the certificate that was removed or null if the certificate + * wasn't in store. + */ + caStore.removeCertificate = function(cert) { + var result; + + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge$e.pki.certificateFromPem(cert); + } + ensureSubjectHasHash(cert.subject); + if(!caStore.hasCertificate(cert)) { + return null; + } + + var match = getBySubject(cert.subject); + + if(!forge$e.util.isArray(match)) { + result = caStore.certs[cert.subject.hash]; + delete caStore.certs[cert.subject.hash]; + return result; + } + + // compare DER-encoding of certificates + var der1 = asn1$4.toDer(pki$2.certificateToAsn1(cert)).getBytes(); + for(var i = 0; i < match.length; ++i) { + var der2 = asn1$4.toDer(pki$2.certificateToAsn1(match[i])).getBytes(); + if(der1 === der2) { + result = match[i]; + match.splice(i, 1); + } + } + if(match.length === 0) { + delete caStore.certs[cert.subject.hash]; + } + + return result; + }; + + function getBySubject(subject) { + ensureSubjectHasHash(subject); + return caStore.certs[subject.hash] || null; + } + + function ensureSubjectHasHash(subject) { + // produce subject hash if it doesn't exist + if(!subject.hash) { + var md = forge$e.md.sha1.create(); + subject.attributes = pki$2.RDNAttributesAsArray(_dnToAsn1(subject), md); + subject.hash = md.digest().toHex(); + } + } + + // auto-add passed in certs + if(certs) { + // parse PEM-formatted certificates as necessary + for(var i = 0; i < certs.length; ++i) { + var cert = certs[i]; + caStore.addCertificate(cert); + } + } + + return caStore; +}; + +/** + * Certificate verification errors, based on TLS. + */ +pki$2.certificateError = { + bad_certificate: 'forge.pki.BadCertificate', + unsupported_certificate: 'forge.pki.UnsupportedCertificate', + certificate_revoked: 'forge.pki.CertificateRevoked', + certificate_expired: 'forge.pki.CertificateExpired', + certificate_unknown: 'forge.pki.CertificateUnknown', + unknown_ca: 'forge.pki.UnknownCertificateAuthority' +}; + +/** + * Verifies a certificate chain against the given Certificate Authority store + * with an optional custom verify callback. + * + * @param caStore a certificate store to verify against. + * @param chain the certificate chain to verify, with the root or highest + * authority at the end (an array of certificates). + * @param options a callback to be called for every certificate in the chain or + * an object with: + * verify a callback to be called for every certificate in the + * chain + * validityCheckDate the date against which the certificate + * validity period should be checked. Pass null to not check + * the validity period. By default, the current date is used. + * + * The verify callback has the following signature: + * + * verified - Set to true if certificate was verified, otherwise the + * pki.certificateError for why the certificate failed. + * depth - The current index in the chain, where 0 is the end point's cert. + * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous + * end point. + * + * The function returns true on success and on failure either the appropriate + * pki.certificateError or an object with 'error' set to the appropriate + * pki.certificateError and 'message' set to a custom error message. + * + * @return true if successful, error thrown if not. + */ +pki$2.verifyCertificateChain = function(caStore, chain, options) { + /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate + Section 6: Certification Path Validation + See inline parentheticals related to this particular implementation. + + The primary goal of path validation is to verify the binding between + a subject distinguished name or a subject alternative name and subject + public key, as represented in the end entity certificate, based on the + public key of the trust anchor. This requires obtaining a sequence of + certificates that support that binding. That sequence should be provided + in the passed 'chain'. The trust anchor should be in the given CA + store. The 'end entity' certificate is the certificate provided by the + end point (typically a server) and is the first in the chain. + + To meet this goal, the path validation process verifies, among other + things, that a prospective certification path (a sequence of n + certificates or a 'chain') satisfies the following conditions: + + (a) for all x in {1, ..., n-1}, the subject of certificate x is + the issuer of certificate x+1; + + (b) certificate 1 is issued by the trust anchor; + + (c) certificate n is the certificate to be validated; and + + (d) for all x in {1, ..., n}, the certificate was valid at the + time in question. + + Note that here 'n' is index 0 in the chain and 1 is the last certificate + in the chain and it must be signed by a certificate in the connection's + CA store. + + The path validation process also determines the set of certificate + policies that are valid for this path, based on the certificate policies + extension, policy mapping extension, policy constraints extension, and + inhibit any-policy extension. + + Note: Policy mapping extension not supported (Not Required). + + Note: If the certificate has an unsupported critical extension, then it + must be rejected. + + Note: A certificate is self-issued if the DNs that appear in the subject + and issuer fields are identical and are not empty. + + The path validation algorithm assumes the following seven inputs are + provided to the path processing logic. What this specific implementation + will use is provided parenthetically: + + (a) a prospective certification path of length n (the 'chain') + (b) the current date/time: ('now'). + (c) user-initial-policy-set: A set of certificate policy identifiers + naming the policies that are acceptable to the certificate user. + The user-initial-policy-set contains the special value any-policy + if the user is not concerned about certificate policy + (Not implemented. Any policy is accepted). + (d) trust anchor information, describing a CA that serves as a trust + anchor for the certification path. The trust anchor information + includes: + + (1) the trusted issuer name, + (2) the trusted public key algorithm, + (3) the trusted public key, and + (4) optionally, the trusted public key parameters associated + with the public key. + + (Trust anchors are provided via certificates in the CA store). + + The trust anchor information may be provided to the path processing + procedure in the form of a self-signed certificate. The trusted anchor + information is trusted because it was delivered to the path processing + procedure by some trustworthy out-of-band procedure. If the trusted + public key algorithm requires parameters, then the parameters are + provided along with the trusted public key (No parameters used in this + implementation). + + (e) initial-policy-mapping-inhibit, which indicates if policy mapping is + allowed in the certification path. + (Not implemented, no policy checking) + + (f) initial-explicit-policy, which indicates if the path must be valid + for at least one of the certificate policies in the user-initial- + policy-set. + (Not implemented, no policy checking) + + (g) initial-any-policy-inhibit, which indicates whether the + anyPolicy OID should be processed if it is included in a + certificate. + (Not implemented, so any policy is valid provided that it is + not marked as critical) */ + + /* Basic Path Processing: + + For each certificate in the 'chain', the following is checked: + + 1. The certificate validity period includes the current time. + 2. The certificate was signed by its parent (where the parent is either + the next in the chain or from the CA store). Allow processing to + continue to the next step if no parent is found but the certificate is + in the CA store. + 3. TODO: The certificate has not been revoked. + 4. The certificate issuer name matches the parent's subject name. + 5. TODO: If the certificate is self-issued and not the final certificate + in the chain, skip this step, otherwise verify that the subject name + is within one of the permitted subtrees of X.500 distinguished names + and that each of the alternative names in the subjectAltName extension + (critical or non-critical) is within one of the permitted subtrees for + that name type. + 6. TODO: If the certificate is self-issued and not the final certificate + in the chain, skip this step, otherwise verify that the subject name + is not within one of the excluded subtrees for X.500 distinguished + names and none of the subjectAltName extension names are excluded for + that name type. + 7. The other steps in the algorithm for basic path processing involve + handling the policy extension which is not presently supported in this + implementation. Instead, if a critical policy extension is found, the + certificate is rejected as not supported. + 8. If the certificate is not the first or if its the only certificate in + the chain (having no parent from the CA store or is self-signed) and it + has a critical key usage extension, verify that the keyCertSign bit is + set. If the key usage extension exists, verify that the basic + constraints extension exists. If the basic constraints extension exists, + verify that the cA flag is set. If pathLenConstraint is set, ensure that + the number of certificates that precede in the chain (come earlier + in the chain as implemented below), excluding the very first in the + chain (typically the end-entity one), isn't greater than the + pathLenConstraint. This constraint limits the number of intermediate + CAs that may appear below a CA before only end-entity certificates + may be issued. */ + + // if a verify callback is passed as the third parameter, package it within + // the options object. This is to support a legacy function signature that + // expected the verify callback as the third parameter. + if(typeof options === 'function') { + options = {verify: options}; + } + options = options || {}; + + // copy cert chain references to another array to protect against changes + // in verify callback + chain = chain.slice(0); + var certs = chain.slice(0); + + var validityCheckDate = options.validityCheckDate; + // if no validityCheckDate is specified, default to the current date. Make + // sure to maintain the value null because it indicates that the validity + // period should not be checked. + if(typeof validityCheckDate === 'undefined') { + validityCheckDate = new Date(); + } + + // verify each cert in the chain using its parent, where the parent + // is either the next in the chain or from the CA store + var first = true; + var error = null; + var depth = 0; + do { + var cert = chain.shift(); + var parent = null; + var selfSigned = false; + + if(validityCheckDate) { + // 1. check valid time + if(validityCheckDate < cert.validity.notBefore || + validityCheckDate > cert.validity.notAfter) { + error = { + message: 'Certificate is not valid yet or has expired.', + error: pki$2.certificateError.certificate_expired, + notBefore: cert.validity.notBefore, + notAfter: cert.validity.notAfter, + // TODO: we might want to reconsider renaming 'now' to + // 'validityCheckDate' should this API be changed in the future. + now: validityCheckDate + }; + } + } + + // 2. verify with parent from chain or CA store + if(error === null) { + parent = chain[0] || caStore.getIssuer(cert); + if(parent === null) { + // check for self-signed cert + if(cert.isIssuer(cert)) { + selfSigned = true; + parent = cert; + } + } + + if(parent) { + // FIXME: current CA store implementation might have multiple + // certificates where the issuer can't be determined from the + // certificate (happens rarely with, eg: old certificates) so normalize + // by always putting parents into an array + // TODO: there's may be an extreme degenerate case currently uncovered + // where an old intermediate certificate seems to have a matching parent + // but none of the parents actually verify ... but the intermediate + // is in the CA and it should pass this check; needs investigation + var parents = parent; + if(!forge$e.util.isArray(parents)) { + parents = [parents]; + } + + // try to verify with each possible parent (typically only one) + var verified = false; + while(!verified && parents.length > 0) { + parent = parents.shift(); + try { + verified = parent.verify(cert); + } catch(ex) { + // failure to verify, don't care why, try next one + } + } + + if(!verified) { + error = { + message: 'Certificate signature is invalid.', + error: pki$2.certificateError.bad_certificate + }; + } + } + + if(error === null && (!parent || selfSigned) && + !caStore.hasCertificate(cert)) { + // no parent issuer and certificate itself is not trusted + error = { + message: 'Certificate is not trusted.', + error: pki$2.certificateError.unknown_ca + }; + } + } + + // TODO: 3. check revoked + + // 4. check for matching issuer/subject + if(error === null && parent && !cert.isIssuer(parent)) { + // parent is not issuer + error = { + message: 'Certificate issuer is invalid.', + error: pki$2.certificateError.bad_certificate + }; + } + + // 5. TODO: check names with permitted names tree + + // 6. TODO: check names against excluded names tree + + // 7. check for unsupported critical extensions + if(error === null) { + // supported extensions + var se = { + keyUsage: true, + basicConstraints: true + }; + for(var i = 0; error === null && i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if(ext.critical && !(ext.name in se)) { + error = { + message: + 'Certificate has an unsupported critical extension.', + error: pki$2.certificateError.unsupported_certificate + }; + } + } + } + + // 8. check for CA if cert is not first or is the only certificate + // remaining in chain with no parent or is self-signed + if(error === null && + (!first || (chain.length === 0 && (!parent || selfSigned)))) { + // first check keyUsage extension and then basic constraints + var bcExt = cert.getExtension('basicConstraints'); + var keyUsageExt = cert.getExtension('keyUsage'); + if(keyUsageExt !== null) { + // keyCertSign must be true and there must be a basic + // constraints extension + if(!keyUsageExt.keyCertSign || bcExt === null) { + // bad certificate + error = { + message: + 'Certificate keyUsage or basicConstraints conflict ' + + 'or indicate that the certificate is not a CA. ' + + 'If the certificate is the only one in the chain or ' + + 'isn\'t the first then the certificate must be a ' + + 'valid CA.', + error: pki$2.certificateError.bad_certificate + }; + } + } + // basic constraints cA flag must be set + if(error === null && bcExt !== null && !bcExt.cA) { + // bad certificate + error = { + message: + 'Certificate basicConstraints indicates the certificate ' + + 'is not a CA.', + error: pki$2.certificateError.bad_certificate + }; + } + // if error is not null and keyUsage is available, then we know it + // has keyCertSign and there is a basic constraints extension too, + // which means we can check pathLenConstraint (if it exists) + if(error === null && keyUsageExt !== null && + 'pathLenConstraint' in bcExt) { + // pathLen is the maximum # of intermediate CA certs that can be + // found between the current certificate and the end-entity (depth 0) + // certificate; this number does not include the end-entity (depth 0, + // last in the chain) even if it happens to be a CA certificate itself + var pathLen = depth - 1; + if(pathLen > bcExt.pathLenConstraint) { + // pathLenConstraint violated, bad certificate + error = { + message: + 'Certificate basicConstraints pathLenConstraint violated.', + error: pki$2.certificateError.bad_certificate + }; + } + } + } + + // call application callback + var vfd = (error === null) ? true : error.error; + var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; + if(ret === true) { + // clear any set error + error = null; + } else { + // if passed basic tests, set default message and alert + if(vfd === true) { + error = { + message: 'The application rejected the certificate.', + error: pki$2.certificateError.bad_certificate + }; + } + + // check for custom error info + if(ret || ret === 0) { + // set custom message and error + if(typeof ret === 'object' && !forge$e.util.isArray(ret)) { + if(ret.message) { + error.message = ret.message; + } + if(ret.error) { + error.error = ret.error; + } + } else if(typeof ret === 'string') { + // set custom error + error.error = ret; + } + } + + // throw error + throw error; + } + + // no longer first cert in chain + first = false; + ++depth; + } while(chain.length > 0); + + return true; +}; + +/** + * Javascript implementation of PKCS#12. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * The ASN.1 representation of PKCS#12 is as follows + * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details) + * + * PFX ::= SEQUENCE { + * version INTEGER {v3(3)}(v3,...), + * authSafe ContentInfo, + * macData MacData OPTIONAL + * } + * + * MacData ::= SEQUENCE { + * mac DigestInfo, + * macSalt OCTET STRING, + * iterations INTEGER DEFAULT 1 + * } + * Note: The iterations default is for historical reasons and its use is + * deprecated. A higher value, like 1024, is recommended. + * + * DigestInfo is defined in PKCS#7 as follows: + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of SHA1 there is none. + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * Digest ::= OCTET STRING + * + * + * ContentInfo ::= SEQUENCE { + * contentType ContentType, + * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL + * } + * + * ContentType ::= OBJECT IDENTIFIER + * + * AuthenticatedSafe ::= SEQUENCE OF ContentInfo + * -- Data if unencrypted + * -- EncryptedData if password-encrypted + * -- EnvelopedData if public key-encrypted + * + * + * SafeContents ::= SEQUENCE OF SafeBag + * + * SafeBag ::= SEQUENCE { + * bagId BAG-TYPE.&id ({PKCS12BagSet}) + * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}), + * bagAttributes SET OF PKCS12Attribute OPTIONAL + * } + * + * PKCS12Attribute ::= SEQUENCE { + * attrId ATTRIBUTE.&id ({PKCS12AttrSet}), + * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId}) + * } -- This type is compatible with the X.500 type 'Attribute' + * + * PKCS12AttrSet ATTRIBUTE ::= { + * friendlyName | -- from PKCS #9 + * localKeyId, -- from PKCS #9 + * ... -- Other attributes are allowed + * } + * + * CertBag ::= SEQUENCE { + * certId BAG-TYPE.&id ({CertTypes}), + * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId}) + * } + * + * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}} + * -- DER-encoded X.509 certificate stored in OCTET STRING + * + * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}} + * -- Base64-encoded SDSI certificate stored in IA5String + * + * CertTypes BAG-TYPE ::= { + * x509Certificate | + * sdsiCertificate, + * ... -- For future extensions + * } + */ + +var forge$d = forge$F; + + + + + + + + + + + +// shortcut for asn.1 & PKI API +var asn1$3 = forge$d.asn1; +var pki$1 = forge$d.pki; + +// shortcut for PKCS#12 API +var p12 = forge$d.pkcs12 = forge$d.pkcs12 || {}; + +var contentInfoValidator = { + name: 'ContentInfo', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.SEQUENCE, // a ContentInfo + constructed: true, + value: [{ + name: 'ContentInfo.contentType', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'ContentInfo.content', + tagClass: asn1$3.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: 'content' + }] +}; + +var pfxValidator = { + name: 'PFX', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PFX.version', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.INTEGER, + constructed: false, + capture: 'version' + }, + contentInfoValidator, { + name: 'PFX.macData', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'mac', + value: [{ + name: 'PFX.macData.mac', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.SEQUENCE, // DigestInfo + constructed: true, + value: [{ + name: 'PFX.macData.mac.digestAlgorithm', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.SEQUENCE, // DigestAlgorithmIdentifier + constructed: true, + value: [{ + name: 'PFX.macData.mac.digestAlgorithm.algorithm', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.OID, + constructed: false, + capture: 'macAlgorithm' + }, { + name: 'PFX.macData.mac.digestAlgorithm.parameters', + tagClass: asn1$3.Class.UNIVERSAL, + captureAsn1: 'macAlgorithmParameters' + }] + }, { + name: 'PFX.macData.mac.digest', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.OCTETSTRING, + constructed: false, + capture: 'macDigest' + }] + }, { + name: 'PFX.macData.macSalt', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.OCTETSTRING, + constructed: false, + capture: 'macSalt' + }, { + name: 'PFX.macData.iterations', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.INTEGER, + constructed: false, + optional: true, + capture: 'macIterations' + }] + }] +}; + +var safeBagValidator = { + name: 'SafeBag', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SafeBag.bagId', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.OID, + constructed: false, + capture: 'bagId' + }, { + name: 'SafeBag.bagValue', + tagClass: asn1$3.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: 'bagValue' + }, { + name: 'SafeBag.bagAttributes', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.SET, + constructed: true, + optional: true, + capture: 'bagAttributes' + }] +}; + +var attributeValidator = { + name: 'Attribute', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Attribute.attrId', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.OID, + constructed: false, + capture: 'oid' + }, { + name: 'Attribute.attrValues', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.SET, + constructed: true, + capture: 'values' + }] +}; + +var certBagValidator = { + name: 'CertBag', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'CertBag.certId', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Type.OID, + constructed: false, + capture: 'certId' + }, { + name: 'CertBag.certValue', + tagClass: asn1$3.Class.CONTEXT_SPECIFIC, + constructed: true, + /* So far we only support X.509 certificates (which are wrapped in + an OCTET STRING, hence hard code that here). */ + value: [{ + name: 'CertBag.certValue[0]', + tagClass: asn1$3.Class.UNIVERSAL, + type: asn1$3.Class.OCTETSTRING, + constructed: false, + capture: 'cert' + }] + }] +}; + +/** + * Search SafeContents structure for bags with matching attributes. + * + * The search can optionally be narrowed by a certain bag type. + * + * @param safeContents the SafeContents structure to search in. + * @param attrName the name of the attribute to compare against. + * @param attrValue the attribute value to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of matching bags. + */ +function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { + var result = []; + + for(var i = 0; i < safeContents.length; i++) { + for(var j = 0; j < safeContents[i].safeBags.length; j++) { + var bag = safeContents[i].safeBags[j]; + if(bagType !== undefined && bag.type !== bagType) { + continue; + } + // only filter by bag type, no attribute specified + if(attrName === null) { + result.push(bag); + continue; + } + if(bag.attributes[attrName] !== undefined && + bag.attributes[attrName].indexOf(attrValue) >= 0) { + result.push(bag); + } + } + } + + return result; +} + +/** + * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object. + * + * @param obj The PKCS#12 PFX in ASN.1 notation. + * @param strict true to use strict DER decoding, false not to (default: true). + * @param {String} password Password to decrypt with (optional). + * + * @return PKCS#12 PFX object. + */ +p12.pkcs12FromAsn1 = function(obj, strict, password) { + // handle args + if(typeof strict === 'string') { + password = strict; + strict = true; + } else if(strict === undefined) { + strict = true; + } + + // validate PFX and capture data + var capture = {}; + var errors = []; + if(!asn1$3.validate(obj, pfxValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 PFX. ' + + 'ASN.1 object is not an PKCS#12 PFX.'); + error.errors = error; + throw error; + } + + var pfx = { + version: capture.version.charCodeAt(0), + safeContents: [], + + /** + * Gets bags with matching attributes. + * + * @param filter the attributes to filter by: + * [localKeyId] the localKeyId to search for. + * [localKeyIdHex] the localKeyId in hex to search for. + * [friendlyName] the friendly name to search for. + * [bagType] bag type to narrow each attribute search by. + * + * @return a map of attribute type to an array of matching bags or, if no + * attribute was given but a bag type, the map key will be the + * bag type. + */ + getBags: function(filter) { + var rval = {}; + + var localKeyId; + if('localKeyId' in filter) { + localKeyId = filter.localKeyId; + } else if('localKeyIdHex' in filter) { + localKeyId = forge$d.util.hexToBytes(filter.localKeyIdHex); + } + + // filter on bagType only + if(localKeyId === undefined && !('friendlyName' in filter) && + 'bagType' in filter) { + rval[filter.bagType] = _getBagsByAttribute( + pfx.safeContents, null, null, filter.bagType); + } + + if(localKeyId !== undefined) { + rval.localKeyId = _getBagsByAttribute( + pfx.safeContents, 'localKeyId', + localKeyId, filter.bagType); + } + if('friendlyName' in filter) { + rval.friendlyName = _getBagsByAttribute( + pfx.safeContents, 'friendlyName', + filter.friendlyName, filter.bagType); + } + + return rval; + }, + + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching friendlyName attribute. + * + * @param friendlyName the friendly name to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching friendlyName attribute. + */ + getBagsByFriendlyName: function(friendlyName, bagType) { + return _getBagsByAttribute( + pfx.safeContents, 'friendlyName', friendlyName, bagType); + }, + + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching localKeyId attribute. + * + * @param localKeyId the localKeyId to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching localKeyId attribute. + */ + getBagsByLocalKeyId: function(localKeyId, bagType) { + return _getBagsByAttribute( + pfx.safeContents, 'localKeyId', localKeyId, bagType); + } + }; + + if(capture.version.charCodeAt(0) !== 3) { + var error = new Error('PKCS#12 PFX of version other than 3 not supported.'); + error.version = capture.version.charCodeAt(0); + throw error; + } + + if(asn1$3.derToOid(capture.contentType) !== pki$1.oids.data) { + var error = new Error('Only PKCS#12 PFX in password integrity mode supported.'); + error.oid = asn1$3.derToOid(capture.contentType); + throw error; + } + + var data = capture.content.value[0]; + if(data.tagClass !== asn1$3.Class.UNIVERSAL || + data.type !== asn1$3.Type.OCTETSTRING) { + throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.'); + } + data = _decodePkcs7Data(data); + + // check for MAC + if(capture.mac) { + var md = null; + var macKeyBytes = 0; + var macAlgorithm = asn1$3.derToOid(capture.macAlgorithm); + switch(macAlgorithm) { + case pki$1.oids.sha1: + md = forge$d.md.sha1.create(); + macKeyBytes = 20; + break; + case pki$1.oids.sha256: + md = forge$d.md.sha256.create(); + macKeyBytes = 32; + break; + case pki$1.oids.sha384: + md = forge$d.md.sha384.create(); + macKeyBytes = 48; + break; + case pki$1.oids.sha512: + md = forge$d.md.sha512.create(); + macKeyBytes = 64; + break; + case pki$1.oids.md5: + md = forge$d.md.md5.create(); + macKeyBytes = 16; + break; + } + if(md === null) { + throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm); + } + + // verify MAC (iterations default to 1) + var macSalt = new forge$d.util.ByteBuffer(capture.macSalt); + var macIterations = (('macIterations' in capture) ? + parseInt(forge$d.util.bytesToHex(capture.macIterations), 16) : 1); + var macKey = p12.generateKey( + password, macSalt, 3, macIterations, macKeyBytes, md); + var mac = forge$d.hmac.create(); + mac.start(md, macKey); + mac.update(data.value); + var macValue = mac.getMac(); + if(macValue.getBytes() !== capture.macDigest) { + throw new Error('PKCS#12 MAC could not be verified. Invalid password?'); + } + } + + _decodeAuthenticatedSafe(pfx, data.value, strict, password); + return pfx; +}; + +/** + * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines "Data" as an OCTET STRING, + * but it is sometimes an OCTET STRING that is composed/constructed of chunks, + * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This + * function transforms this corner-case into the usual simple, + * non-composed/constructed OCTET STRING. + * + * This function may be moved to ASN.1 at some point to better deal with + * more BER-encoding issues, should they arise. + * + * @param data the ASN.1 Data object to transform. + */ +function _decodePkcs7Data(data) { + // handle special case of "chunked" data content: an octet string composed + // of other octet strings + if(data.composed || data.constructed) { + var value = forge$d.util.createBuffer(); + for(var i = 0; i < data.value.length; ++i) { + value.putBytes(data.value[i].value); + } + data.composed = data.constructed = false; + data.value = value.getBytes(); + } + return data; +} + +/** + * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object. + * + * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo. + * + * @param pfx The PKCS#12 PFX object to fill. + * @param {String} authSafe BER-encoded AuthenticatedSafe. + * @param strict true to use strict DER decoding, false not to. + * @param {String} password Password to decrypt with (optional). + */ +function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { + authSafe = asn1$3.fromDer(authSafe, strict); /* actually it's BER encoded */ + + if(authSafe.tagClass !== asn1$3.Class.UNIVERSAL || + authSafe.type !== asn1$3.Type.SEQUENCE || + authSafe.constructed !== true) { + throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' + + 'SEQUENCE OF ContentInfo'); + } + + for(var i = 0; i < authSafe.value.length; i++) { + var contentInfo = authSafe.value[i]; + + // validate contentInfo and capture data + var capture = {}; + var errors = []; + if(!asn1$3.validate(contentInfo, contentInfoValidator, capture, errors)) { + var error = new Error('Cannot read ContentInfo.'); + error.errors = errors; + throw error; + } + + var obj = { + encrypted: false + }; + var safeContents = null; + var data = capture.content.value[0]; + switch(asn1$3.derToOid(capture.contentType)) { + case pki$1.oids.data: + if(data.tagClass !== asn1$3.Class.UNIVERSAL || + data.type !== asn1$3.Type.OCTETSTRING) { + throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.'); + } + safeContents = _decodePkcs7Data(data).value; + break; + case pki$1.oids.encryptedData: + safeContents = _decryptSafeContents(data, password); + obj.encrypted = true; + break; + default: + var error = new Error('Unsupported PKCS#12 contentType.'); + error.contentType = asn1$3.derToOid(capture.contentType); + throw error; + } + + obj.safeBags = _decodeSafeContents(safeContents, strict, password); + pfx.safeContents.push(obj); + } +} + +/** + * Decrypt PKCS#7 EncryptedData structure. + * + * @param data ASN.1 encoded EncryptedContentInfo object. + * @param password The user-provided password. + * + * @return The decrypted SafeContents (ASN.1 object). + */ +function _decryptSafeContents(data, password) { + var capture = {}; + var errors = []; + if(!asn1$3.validate( + data, forge$d.pkcs7.asn1.encryptedDataValidator, capture, errors)) { + var error = new Error('Cannot read EncryptedContentInfo.'); + error.errors = errors; + throw error; + } + + var oid = asn1$3.derToOid(capture.contentType); + if(oid !== pki$1.oids.data) { + var error = new Error( + 'PKCS#12 EncryptedContentInfo ContentType is not Data.'); + error.oid = oid; + throw error; + } + + // get cipher + oid = asn1$3.derToOid(capture.encAlgorithm); + var cipher = pki$1.pbe.getCipher(oid, capture.encParameter, password); + + // get encrypted data + var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); + var encrypted = forge$d.util.createBuffer(encryptedContentAsn1.value); + + cipher.update(encrypted); + if(!cipher.finish()) { + throw new Error('Failed to decrypt PKCS#12 SafeContents.'); + } + + return cipher.output.getBytes(); +} + +/** + * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects. + * + * The safeContents is a BER-encoded SEQUENCE OF SafeBag. + * + * @param {String} safeContents BER-encoded safeContents. + * @param strict true to use strict DER decoding, false not to. + * @param {String} password Password to decrypt with (optional). + * + * @return {Array} Array of Bag objects. + */ +function _decodeSafeContents(safeContents, strict, password) { + // if strict and no safe contents, return empty safes + if(!strict && safeContents.length === 0) { + return []; + } + + // actually it's BER-encoded + safeContents = asn1$3.fromDer(safeContents, strict); + + if(safeContents.tagClass !== asn1$3.Class.UNIVERSAL || + safeContents.type !== asn1$3.Type.SEQUENCE || + safeContents.constructed !== true) { + throw new Error( + 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.'); + } + + var res = []; + for(var i = 0; i < safeContents.value.length; i++) { + var safeBag = safeContents.value[i]; + + // validate SafeBag and capture data + var capture = {}; + var errors = []; + if(!asn1$3.validate(safeBag, safeBagValidator, capture, errors)) { + var error = new Error('Cannot read SafeBag.'); + error.errors = errors; + throw error; + } + + /* Create bag object and push to result array. */ + var bag = { + type: asn1$3.derToOid(capture.bagId), + attributes: _decodeBagAttributes(capture.bagAttributes) + }; + res.push(bag); + + var validator, decoder; + var bagAsn1 = capture.bagValue.value[0]; + switch(bag.type) { + case pki$1.oids.pkcs8ShroudedKeyBag: + /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt. + Afterwards we can handle it like a keyBag, + which is a PrivateKeyInfo. */ + bagAsn1 = pki$1.decryptPrivateKeyInfo(bagAsn1, password); + if(bagAsn1 === null) { + throw new Error( + 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?'); + } + + /* fall through */ + case pki$1.oids.keyBag: + /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our + PKI module, hence we don't have to do validation/capturing here, + just pass what we already got. */ + try { + bag.key = pki$1.privateKeyFromAsn1(bagAsn1); + } catch(e) { + // ignore unknown key type, pass asn1 value + bag.key = null; + bag.asn1 = bagAsn1; + } + continue; /* Nothing more to do. */ + + case pki$1.oids.certBag: + /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates. + Therefore put the SafeBag content through another validator to + capture the fields. Afterwards check & store the results. */ + validator = certBagValidator; + decoder = function() { + if(asn1$3.derToOid(capture.certId) !== pki$1.oids.x509Certificate) { + var error = new Error( + 'Unsupported certificate type, only X.509 supported.'); + error.oid = asn1$3.derToOid(capture.certId); + throw error; + } + + // true=produce cert hash + var certAsn1 = asn1$3.fromDer(capture.cert, strict); + try { + bag.cert = pki$1.certificateFromAsn1(certAsn1, true); + } catch(e) { + // ignore unknown cert type, pass asn1 value + bag.cert = null; + bag.asn1 = certAsn1; + } + }; + break; + + default: + var error = new Error('Unsupported PKCS#12 SafeBag type.'); + error.oid = bag.type; + throw error; + } + + /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */ + if(validator !== undefined && + !asn1$3.validate(bagAsn1, validator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 ' + validator.name); + error.errors = errors; + throw error; + } + + /* Call decoder function from above to store the results. */ + decoder(); + } + + return res; +} + +/** + * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object. + * + * @param attributes SET OF PKCS12Attribute (ASN.1 object). + * + * @return the decoded attributes. + */ +function _decodeBagAttributes(attributes) { + var decodedAttrs = {}; + + if(attributes !== undefined) { + for(var i = 0; i < attributes.length; ++i) { + var capture = {}; + var errors = []; + if(!asn1$3.validate(attributes[i], attributeValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 BagAttribute.'); + error.errors = errors; + throw error; + } + + var oid = asn1$3.derToOid(capture.oid); + if(pki$1.oids[oid] === undefined) { + // unsupported attribute type, ignore. + continue; + } + + decodedAttrs[pki$1.oids[oid]] = []; + for(var j = 0; j < capture.values.length; ++j) { + decodedAttrs[pki$1.oids[oid]].push(capture.values[j].value); + } + } + } + + return decodedAttrs; +} + +/** + * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a + * password is provided then the private key will be encrypted. + * + * An entire certificate chain may also be included. To do this, pass + * an array for the "cert" parameter where the first certificate is + * the one that is paired with the private key and each subsequent one + * verifies the previous one. The certificates may be in PEM format or + * have been already parsed by Forge. + * + * @todo implement password-based-encryption for the whole package + * + * @param key the private key. + * @param cert the certificate (may be an array of certificates in order + * to specify a certificate chain). + * @param password the password to use, null for none. + * @param options: + * algorithm the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. + * count the iteration count to use. + * saltSize the salt size to use. + * useMac true to include a MAC, false not to, defaults to true. + * localKeyId the local key ID to use, in hex. + * friendlyName the friendly name to use. + * generateLocalKeyId true to generate a random local key ID, + * false not to, defaults to true. + * + * @return the PKCS#12 PFX ASN.1 object. + */ +p12.toPkcs12Asn1 = function(key, cert, password, options) { + // set default options + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || options.encAlgorithm || 'aes128'; + if(!('useMac' in options)) { + options.useMac = true; + } + if(!('localKeyId' in options)) { + options.localKeyId = null; + } + if(!('generateLocalKeyId' in options)) { + options.generateLocalKeyId = true; + } + + var localKeyId = options.localKeyId; + var bagAttrs; + if(localKeyId !== null) { + localKeyId = forge$d.util.hexToBytes(localKeyId); + } else if(options.generateLocalKeyId) { + // use SHA-1 of paired cert, if available + if(cert) { + var pairedCert = forge$d.util.isArray(cert) ? cert[0] : cert; + if(typeof pairedCert === 'string') { + pairedCert = pki$1.certificateFromPem(pairedCert); + } + var sha1 = forge$d.md.sha1.create(); + sha1.update(asn1$3.toDer(pki$1.certificateToAsn1(pairedCert)).getBytes()); + localKeyId = sha1.digest().getBytes(); + } else { + // FIXME: consider using SHA-1 of public key (which can be generated + // from private key components), see: cert.generateSubjectKeyIdentifier + // generate random bytes + localKeyId = forge$d.random.getBytes(20); + } + } + + var attrs = []; + if(localKeyId !== null) { + attrs.push( + // localKeyID + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // attrId + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, + asn1$3.oidToDer(pki$1.oids.localKeyId).getBytes()), + // attrValues + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SET, true, [ + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, + localKeyId) + ]) + ])); + } + if('friendlyName' in options) { + attrs.push( + // friendlyName + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // attrId + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, + asn1$3.oidToDer(pki$1.oids.friendlyName).getBytes()), + // attrValues + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SET, true, [ + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.BMPSTRING, false, + options.friendlyName) + ]) + ])); + } + + if(attrs.length > 0) { + bagAttrs = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SET, true, attrs); + } + + // collect contents for AuthenticatedSafe + var contents = []; + + // create safe bag(s) for certificate chain + var chain = []; + if(cert !== null) { + if(forge$d.util.isArray(cert)) { + chain = cert; + } else { + chain = [cert]; + } + } + + var certSafeBags = []; + for(var i = 0; i < chain.length; ++i) { + // convert cert from PEM as necessary + cert = chain[i]; + if(typeof cert === 'string') { + cert = pki$1.certificateFromPem(cert); + } + + // SafeBag + var certBagAttrs = (i === 0) ? bagAttrs : undefined; + var certAsn1 = pki$1.certificateToAsn1(cert); + var certSafeBag = + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // bagId + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, + asn1$3.oidToDer(pki$1.oids.certBag).getBytes()), + // bagValue + asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ + // CertBag + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // certId + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, + asn1$3.oidToDer(pki$1.oids.x509Certificate).getBytes()), + // certValue (x509Certificate) + asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1$3.create( + asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, + asn1$3.toDer(certAsn1).getBytes()) + ])])]), + // bagAttributes (OPTIONAL) + certBagAttrs + ]); + certSafeBags.push(certSafeBag); + } + + if(certSafeBags.length > 0) { + // SafeContents + var certSafeContents = asn1$3.create( + asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, certSafeBags); + + // ContentInfo + var certCI = + // PKCS#7 ContentInfo + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // contentType + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, + // OID for the content type is 'data' + asn1$3.oidToDer(pki$1.oids.data).getBytes()), + // content + asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1$3.create( + asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, + asn1$3.toDer(certSafeContents).getBytes()) + ]) + ]); + contents.push(certCI); + } + + // create safe contents for private key + var keyBag = null; + if(key !== null) { + // SafeBag + var pkAsn1 = pki$1.wrapRsaPrivateKey(pki$1.privateKeyToAsn1(key)); + if(password === null) { + // no encryption + keyBag = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // bagId + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, + asn1$3.oidToDer(pki$1.oids.keyBag).getBytes()), + // bagValue + asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ + // PrivateKeyInfo + pkAsn1 + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } else { + // encrypted PrivateKeyInfo + keyBag = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // bagId + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, + asn1$3.oidToDer(pki$1.oids.pkcs8ShroudedKeyBag).getBytes()), + // bagValue + asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ + // EncryptedPrivateKeyInfo + pki$1.encryptPrivateKeyInfo(pkAsn1, password, options) + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } + + // SafeContents + var keySafeContents = + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [keyBag]); + + // ContentInfo + var keyCI = + // PKCS#7 ContentInfo + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // contentType + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, + // OID for the content type is 'data' + asn1$3.oidToDer(pki$1.oids.data).getBytes()), + // content + asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1$3.create( + asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, + asn1$3.toDer(keySafeContents).getBytes()) + ]) + ]); + contents.push(keyCI); + } + + // create AuthenticatedSafe by stringing together the contents + var safe = asn1$3.create( + asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, contents); + + var macData; + if(options.useMac) { + // MacData + var sha1 = forge$d.md.sha1.create(); + var macSalt = new forge$d.util.ByteBuffer( + forge$d.random.getBytes(options.saltSize)); + var count = options.count; + // 160-bit key + var key = p12.generateKey(password, macSalt, 3, count, 20); + var mac = forge$d.hmac.create(); + mac.start(sha1, key); + mac.update(asn1$3.toDer(safe).getBytes()); + var macValue = mac.getMac(); + macData = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // mac DigestInfo + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // digestAlgorithm + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // algorithm = SHA-1 + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, + asn1$3.oidToDer(pki$1.oids.sha1).getBytes()), + // parameters = Null + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.NULL, false, '') + ]), + // digest + asn1$3.create( + asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, + false, macValue.getBytes()) + ]), + // macSalt OCTET STRING + asn1$3.create( + asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, macSalt.getBytes()), + // iterations INTEGER (XXX: Only support count < 65536) + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.INTEGER, false, + asn1$3.integerToDer(count).getBytes() + ) + ]); + } + + // PFX + return asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // version (3) + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.INTEGER, false, + asn1$3.integerToDer(3).getBytes()), + // PKCS#7 ContentInfo + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ + // contentType + asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, + // OID for the content type is 'data' + asn1$3.oidToDer(pki$1.oids.data).getBytes()), + // content + asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1$3.create( + asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, + asn1$3.toDer(safe).getBytes()) + ]) + ]), + macData + ]); +}; + +/** + * Derives a PKCS#12 key. + * + * @param password the password to derive the key material from, null or + * undefined for none. + * @param salt the salt, as a ByteBuffer, to use. + * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). + * @param iter the iteration count. + * @param n the number of bytes to derive from the password. + * @param md the message digest to use, defaults to SHA-1. + * + * @return a ByteBuffer with the bytes derived from the password. + */ +p12.generateKey = forge$d.pbe.generatePkcs12Key; + +/** + * Javascript implementation of a basic Public Key Infrastructure, including + * support for RSA public and private keys. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ + +var forge$c = forge$F; + + + + + + + + + + + +// shortcut for asn.1 API +var asn1$2 = forge$c.asn1; + +/* Public Key Infrastructure (PKI) implementation. */ +var pki = forge$c.pki = forge$c.pki || {}; + +/** + * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead. + * + * Converts PEM-formatted data to DER. + * + * @param pem the PEM-formatted data. + * + * @return the DER-formatted data. + */ +pki.pemToDer = function(pem) { + var msg = forge$c.pem.decode(pem)[0]; + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert PEM to DER; PEM is encrypted.'); + } + return forge$c.util.createBuffer(msg.body); +}; + +/** + * Converts an RSA private key from PEM format. + * + * @param pem the PEM-formatted private key. + * + * @return the private key. + */ +pki.privateKeyFromPem = function(pem) { + var msg = forge$c.pem.decode(pem)[0]; + + if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') { + var error = new Error('Could not convert private key from PEM; PEM ' + + 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert private key from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1$2.fromDer(msg.body); + + return pki.privateKeyFromAsn1(obj); +}; + +/** + * Converts an RSA private key to PEM format. + * + * @param key the private key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted private key. + */ +pki.privateKeyToPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'RSA PRIVATE KEY', + body: asn1$2.toDer(pki.privateKeyToAsn1(key)).getBytes() + }; + return forge$c.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts a PrivateKeyInfo to PEM format. + * + * @param pki the PrivateKeyInfo. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted private key. + */ +pki.privateKeyInfoToPem = function(pki, maxline) { + // convert to DER, then PEM-encode + var msg = { + type: 'PRIVATE KEY', + body: asn1$2.toDer(pki).getBytes() + }; + return forge$c.pem.encode(msg, {maxline: maxline}); +}; + +/** + * A Javascript implementation of Transport Layer Security (TLS). + * + * @author Dave Longley + * + * Copyright (c) 2009-2014 Digital Bazaar, Inc. + * + * The TLS Handshake Protocol involves the following steps: + * + * - Exchange hello messages to agree on algorithms, exchange random values, + * and check for session resumption. + * + * - Exchange the necessary cryptographic parameters to allow the client and + * server to agree on a premaster secret. + * + * - Exchange certificates and cryptographic information to allow the client + * and server to authenticate themselves. + * + * - Generate a master secret from the premaster secret and exchanged random + * values. + * + * - Provide security parameters to the record layer. + * + * - Allow the client and server to verify that their peer has calculated the + * same security parameters and that the handshake occurred without tampering + * by an attacker. + * + * Up to 4 different messages may be sent during a key exchange. The server + * certificate, the server key exchange, the client certificate, and the + * client key exchange. + * + * A typical handshake (from the client's perspective). + * + * 1. Client sends ClientHello. + * 2. Client receives ServerHello. + * 3. Client receives optional Certificate. + * 4. Client receives optional ServerKeyExchange. + * 5. Client receives ServerHelloDone. + * 6. Client sends optional Certificate. + * 7. Client sends ClientKeyExchange. + * 8. Client sends optional CertificateVerify. + * 9. Client sends ChangeCipherSpec. + * 10. Client sends Finished. + * 11. Client receives ChangeCipherSpec. + * 12. Client receives Finished. + * 13. Client sends/receives application data. + * + * To reuse an existing session: + * + * 1. Client sends ClientHello with session ID for reuse. + * 2. Client receives ServerHello with same session ID if reusing. + * 3. Client receives ChangeCipherSpec message if reusing. + * 4. Client receives Finished. + * 5. Client sends ChangeCipherSpec. + * 6. Client sends Finished. + * + * Note: Client ignores HelloRequest if in the middle of a handshake. + * + * Record Layer: + * + * The record layer fragments information blocks into TLSPlaintext records + * carrying data in chunks of 2^14 bytes or less. Client message boundaries are + * not preserved in the record layer (i.e., multiple client messages of the + * same ContentType MAY be coalesced into a single TLSPlaintext record, or a + * single message MAY be fragmented across several records). + * + * struct { + * uint8 major; + * uint8 minor; + * } ProtocolVersion; + * + * struct { + * ContentType type; + * ProtocolVersion version; + * uint16 length; + * opaque fragment[TLSPlaintext.length]; + * } TLSPlaintext; + * + * type: + * The higher-level protocol used to process the enclosed fragment. + * + * version: + * The version of the protocol being employed. TLS Version 1.2 uses version + * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that + * supports multiple versions of TLS may not know what version will be + * employed before it receives the ServerHello. + * + * length: + * The length (in bytes) of the following TLSPlaintext.fragment. The length + * MUST NOT exceed 2^14 = 16384 bytes. + * + * fragment: + * The application data. This data is transparent and treated as an + * independent block to be dealt with by the higher-level protocol specified + * by the type field. + * + * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or + * ChangeCipherSpec content types. Zero-length fragments of Application data + * MAY be sent as they are potentially useful as a traffic analysis + * countermeasure. + * + * Note: Data of different TLS record layer content types MAY be interleaved. + * Application data is generally of lower precedence for transmission than + * other content types. However, records MUST be delivered to the network in + * the same order as they are protected by the record layer. Recipients MUST + * receive and process interleaved application layer traffic during handshakes + * subsequent to the first one on a connection. + * + * struct { + * ContentType type; // same as TLSPlaintext.type + * ProtocolVersion version;// same as TLSPlaintext.version + * uint16 length; + * opaque fragment[TLSCompressed.length]; + * } TLSCompressed; + * + * length: + * The length (in bytes) of the following TLSCompressed.fragment. + * The length MUST NOT exceed 2^14 + 1024. + * + * fragment: + * The compressed form of TLSPlaintext.fragment. + * + * Note: A CompressionMethod.null operation is an identity operation; no fields + * are altered. In this implementation, since no compression is supported, + * uncompressed records are always the same as compressed records. + * + * Encryption Information: + * + * The encryption and MAC functions translate a TLSCompressed structure into a + * TLSCiphertext. The decryption functions reverse the process. The MAC of the + * record also includes a sequence number so that missing, extra, or repeated + * messages are detectable. + * + * struct { + * ContentType type; + * ProtocolVersion version; + * uint16 length; + * select (SecurityParameters.cipher_type) { + * case stream: GenericStreamCipher; + * case block: GenericBlockCipher; + * case aead: GenericAEADCipher; + * } fragment; + * } TLSCiphertext; + * + * type: + * The type field is identical to TLSCompressed.type. + * + * version: + * The version field is identical to TLSCompressed.version. + * + * length: + * The length (in bytes) of the following TLSCiphertext.fragment. + * The length MUST NOT exceed 2^14 + 2048. + * + * fragment: + * The encrypted form of TLSCompressed.fragment, with the MAC. + * + * Note: Only CBC Block Ciphers are supported by this implementation. + * + * The TLSCompressed.fragment structures are converted to/from block + * TLSCiphertext.fragment structures. + * + * struct { + * opaque IV[SecurityParameters.record_iv_length]; + * block-ciphered struct { + * opaque content[TLSCompressed.length]; + * opaque MAC[SecurityParameters.mac_length]; + * uint8 padding[GenericBlockCipher.padding_length]; + * uint8 padding_length; + * }; + * } GenericBlockCipher; + * + * The MAC is generated as described in Section 6.2.3.1. + * + * IV: + * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be + * unpredictable. Note that in versions of TLS prior to 1.1, there was no + * IV field, and the last ciphertext block of the previous record (the "CBC + * residue") was used as the IV. This was changed to prevent the attacks + * described in [CBCATT]. For block ciphers, the IV length is of length + * SecurityParameters.record_iv_length, which is equal to the + * SecurityParameters.block_size. + * + * padding: + * Padding that is added to force the length of the plaintext to be an + * integral multiple of the block cipher's block length. The padding MAY be + * any length up to 255 bytes, as long as it results in the + * TLSCiphertext.length being an integral multiple of the block length. + * Lengths longer than necessary might be desirable to frustrate attacks on + * a protocol that are based on analysis of the lengths of exchanged + * messages. Each uint8 in the padding data vector MUST be filled with the + * padding length value. The receiver MUST check this padding and MUST use + * the bad_record_mac alert to indicate padding errors. + * + * padding_length: + * The padding length MUST be such that the total size of the + * GenericBlockCipher structure is a multiple of the cipher's block length. + * Legal values range from zero to 255, inclusive. This length specifies the + * length of the padding field exclusive of the padding_length field itself. + * + * The encrypted data length (TLSCiphertext.length) is one more than the sum of + * SecurityParameters.block_length, TLSCompressed.length, + * SecurityParameters.mac_length, and padding_length. + * + * Example: If the block length is 8 bytes, the content length + * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the + * length before padding is 82 bytes (this does not include the IV. Thus, the + * padding length modulo 8 must be equal to 6 in order to make the total length + * an even multiple of 8 bytes (the block length). The padding length can be + * 6, 14, 22, and so on, through 254. If the padding length were the minimum + * necessary, 6, the padding would be 6 bytes, each containing the value 6. + * Thus, the last 8 octets of the GenericBlockCipher before block encryption + * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC. + * + * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical + * that the entire plaintext of the record be known before any ciphertext is + * transmitted. Otherwise, it is possible for the attacker to mount the attack + * described in [CBCATT]. + * + * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing + * attack on CBC padding based on the time required to compute the MAC. In + * order to defend against this attack, implementations MUST ensure that + * record processing time is essentially the same whether or not the padding + * is correct. In general, the best way to do this is to compute the MAC even + * if the padding is incorrect, and only then reject the packet. For instance, + * if the pad appears to be incorrect, the implementation might assume a + * zero-length pad and then compute the MAC. This leaves a small timing + * channel, since MAC performance depends, to some extent, on the size of the + * data fragment, but it is not believed to be large enough to be exploitable, + * due to the large block size of existing MACs and the small size of the + * timing signal. + */ + +var forge$b = forge$F; + + + + + + + + + +/** + * Generates pseudo random bytes by mixing the result of two hash functions, + * MD5 and SHA-1. + * + * prf_TLS1(secret, label, seed) = + * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed); + * + * Each P_hash function functions as follows: + * + * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + + * HMAC_hash(secret, A(2) + seed) + + * HMAC_hash(secret, A(3) + seed) + ... + * A() is defined as: + * A(0) = seed + * A(i) = HMAC_hash(secret, A(i-1)) + * + * The '+' operator denotes concatenation. + * + * As many iterations A(N) as are needed are performed to generate enough + * pseudo random byte output. If an iteration creates more data than is + * necessary, then it is truncated. + * + * Therefore: + * A(1) = HMAC_hash(secret, A(0)) + * = HMAC_hash(secret, seed) + * A(2) = HMAC_hash(secret, A(1)) + * = HMAC_hash(secret, HMAC_hash(secret, seed)) + * + * Therefore: + * P_hash(secret, seed) = + * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) + + * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) + + * ... + * + * Therefore: + * P_hash(secret, seed) = + * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) + + * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) + + * ... + * + * @param secret the secret to use. + * @param label the label to use. + * @param seed the seed value to use. + * @param length the number of bytes to generate. + * + * @return the pseudo random bytes in a byte buffer. + */ +var prf_TLS1 = function(secret, label, seed, length) { + var rval = forge$b.util.createBuffer(); + + /* For TLS 1.0, the secret is split in half, into two secrets of equal + length. If the secret has an odd length then the last byte of the first + half will be the same as the first byte of the second. The length of the + two secrets is half of the secret rounded up. */ + var idx = (secret.length >> 1); + var slen = idx + (secret.length & 1); + var s1 = secret.substr(0, slen); + var s2 = secret.substr(idx, slen); + var ai = forge$b.util.createBuffer(); + var hmac = forge$b.hmac.create(); + seed = label + seed; + + // determine the number of iterations that must be performed to generate + // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20 + var md5itr = Math.ceil(length / 16); + var sha1itr = Math.ceil(length / 20); + + // do md5 iterations + hmac.start('MD5', s1); + var md5bytes = forge$b.util.createBuffer(); + ai.putBytes(seed); + for(var i = 0; i < md5itr; ++i) { + // HMAC_hash(secret, A(i-1)) + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + + // HMAC_hash(secret, A(i) + seed) + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + md5bytes.putBuffer(hmac.digest()); + } + + // do sha1 iterations + hmac.start('SHA1', s2); + var sha1bytes = forge$b.util.createBuffer(); + ai.clear(); + ai.putBytes(seed); + for(var i = 0; i < sha1itr; ++i) { + // HMAC_hash(secret, A(i-1)) + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + + // HMAC_hash(secret, A(i) + seed) + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + sha1bytes.putBuffer(hmac.digest()); + } + + // XOR the md5 bytes with the sha1 bytes + rval.putBytes(forge$b.util.xorBytes( + md5bytes.getBytes(), sha1bytes.getBytes(), length)); + + return rval; +}; + +/** + * Gets a MAC for a record using the SHA-1 hash algorithm. + * + * @param key the mac key. + * @param state the sequence number (array of two 32-bit integers). + * @param record the record. + * + * @return the sha-1 hash (20 bytes) for the given record. + */ +var hmac_sha1 = function(key, seqNum, record) { + /* MAC is computed like so: + HMAC_hash( + key, seqNum + + TLSCompressed.type + + TLSCompressed.version + + TLSCompressed.length + + TLSCompressed.fragment) + */ + var hmac = forge$b.hmac.create(); + hmac.start('SHA1', key); + var b = forge$b.util.createBuffer(); + b.putInt32(seqNum[0]); + b.putInt32(seqNum[1]); + b.putByte(record.type); + b.putByte(record.version.major); + b.putByte(record.version.minor); + b.putInt16(record.length); + b.putBytes(record.fragment.bytes()); + hmac.update(b.getBytes()); + return hmac.digest().getBytes(); +}; + +/** + * Compresses the TLSPlaintext record into a TLSCompressed record using the + * deflate algorithm. + * + * @param c the TLS connection. + * @param record the TLSPlaintext record to compress. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +var deflate = function(c, record, s) { + var rval = false; + + try { + var bytes = c.deflate(record.fragment.getBytes()); + record.fragment = forge$b.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch(ex) { + // deflate error, fail out + } + + return rval; +}; + +/** + * Decompresses the TLSCompressed record into a TLSPlaintext record using the + * deflate algorithm. + * + * @param c the TLS connection. + * @param record the TLSCompressed record to decompress. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +var inflate = function(c, record, s) { + var rval = false; + + try { + var bytes = c.inflate(record.fragment.getBytes()); + record.fragment = forge$b.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch(ex) { + // inflate error, fail out + } + + return rval; +}; + +/** + * Reads a TLS variable-length vector from a byte buffer. + * + * Variable-length vectors are defined by specifying a subrange of legal + * lengths, inclusively, using the notation . When these are + * encoded, the actual length precedes the vector's contents in the byte + * stream. The length will be in the form of a number consuming as many bytes + * as required to hold the vector's specified maximum (ceiling) length. A + * variable-length vector with an actual length field of zero is referred to + * as an empty vector. + * + * @param b the byte buffer. + * @param lenBytes the number of bytes required to store the length. + * + * @return the resulting byte buffer. + */ +var readVector = function(b, lenBytes) { + var len = 0; + switch(lenBytes) { + case 1: + len = b.getByte(); + break; + case 2: + len = b.getInt16(); + break; + case 3: + len = b.getInt24(); + break; + case 4: + len = b.getInt32(); + break; + } + + // read vector bytes into a new buffer + return forge$b.util.createBuffer(b.getBytes(len)); +}; + +/** + * Writes a TLS variable-length vector to a byte buffer. + * + * @param b the byte buffer. + * @param lenBytes the number of bytes required to store the length. + * @param v the byte buffer vector. + */ +var writeVector = function(b, lenBytes, v) { + // encode length at the start of the vector, where the number of bytes for + // the length is the maximum number of bytes it would take to encode the + // vector's ceiling + b.putInt(v.length(), lenBytes << 3); + b.putBuffer(v); +}; + +/** + * The tls implementation. + */ +var tls$1 = {}; + +/** + * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and + * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time + * of this implementation so TLS 1.0 was implemented instead. + */ +tls$1.Versions = { + TLS_1_0: {major: 3, minor: 1}, + TLS_1_1: {major: 3, minor: 2}, + TLS_1_2: {major: 3, minor: 3} +}; +tls$1.SupportedVersions = [ + tls$1.Versions.TLS_1_1, + tls$1.Versions.TLS_1_0 +]; +tls$1.Version = tls$1.SupportedVersions[0]; + +/** + * Maximum fragment size. True maximum is 16384, but we fragment before that + * to allow for unusual small increases during compression. + */ +tls$1.MaxFragment = 16384 - 1024; + +/** + * Whether this entity is considered the "client" or "server". + * enum { server, client } ConnectionEnd; + */ +tls$1.ConnectionEnd = { + server: 0, + client: 1 +}; + +/** + * Pseudo-random function algorithm used to generate keys from the master + * secret. + * enum { tls_prf_sha256 } PRFAlgorithm; + */ +tls$1.PRFAlgorithm = { + tls_prf_sha256: 0 +}; + +/** + * Bulk encryption algorithms. + * enum { null, rc4, des3, aes } BulkCipherAlgorithm; + */ +tls$1.BulkCipherAlgorithm = { + none: null, + rc4: 0, + des3: 1, + aes: 2 +}; + +/** + * Cipher types. + * enum { stream, block, aead } CipherType; + */ +tls$1.CipherType = { + stream: 0, + block: 1, + aead: 2 +}; + +/** + * MAC (Message Authentication Code) algorithms. + * enum { null, hmac_md5, hmac_sha1, hmac_sha256, + * hmac_sha384, hmac_sha512} MACAlgorithm; + */ +tls$1.MACAlgorithm = { + none: null, + hmac_md5: 0, + hmac_sha1: 1, + hmac_sha256: 2, + hmac_sha384: 3, + hmac_sha512: 4 +}; + +/** + * Compression algorithms. + * enum { null(0), deflate(1), (255) } CompressionMethod; + */ +tls$1.CompressionMethod = { + none: 0, + deflate: 1 +}; + +/** + * TLS record content types. + * enum { + * change_cipher_spec(20), alert(21), handshake(22), + * application_data(23), (255) + * } ContentType; + */ +tls$1.ContentType = { + change_cipher_spec: 20, + alert: 21, + handshake: 22, + application_data: 23, + heartbeat: 24 +}; + +/** + * TLS handshake types. + * enum { + * hello_request(0), client_hello(1), server_hello(2), + * certificate(11), server_key_exchange (12), + * certificate_request(13), server_hello_done(14), + * certificate_verify(15), client_key_exchange(16), + * finished(20), (255) + * } HandshakeType; + */ +tls$1.HandshakeType = { + hello_request: 0, + client_hello: 1, + server_hello: 2, + certificate: 11, + server_key_exchange: 12, + certificate_request: 13, + server_hello_done: 14, + certificate_verify: 15, + client_key_exchange: 16, + finished: 20 +}; + +/** + * TLS Alert Protocol. + * + * enum { warning(1), fatal(2), (255) } AlertLevel; + * + * enum { + * close_notify(0), + * unexpected_message(10), + * bad_record_mac(20), + * decryption_failed(21), + * record_overflow(22), + * decompression_failure(30), + * handshake_failure(40), + * bad_certificate(42), + * unsupported_certificate(43), + * certificate_revoked(44), + * certificate_expired(45), + * certificate_unknown(46), + * illegal_parameter(47), + * unknown_ca(48), + * access_denied(49), + * decode_error(50), + * decrypt_error(51), + * export_restriction(60), + * protocol_version(70), + * insufficient_security(71), + * internal_error(80), + * user_canceled(90), + * no_renegotiation(100), + * (255) + * } AlertDescription; + * + * struct { + * AlertLevel level; + * AlertDescription description; + * } Alert; + */ +tls$1.Alert = {}; +tls$1.Alert.Level = { + warning: 1, + fatal: 2 +}; +tls$1.Alert.Description = { + close_notify: 0, + unexpected_message: 10, + bad_record_mac: 20, + decryption_failed: 21, + record_overflow: 22, + decompression_failure: 30, + handshake_failure: 40, + bad_certificate: 42, + unsupported_certificate: 43, + certificate_revoked: 44, + certificate_expired: 45, + certificate_unknown: 46, + illegal_parameter: 47, + unknown_ca: 48, + access_denied: 49, + decode_error: 50, + decrypt_error: 51, + export_restriction: 60, + protocol_version: 70, + insufficient_security: 71, + internal_error: 80, + user_canceled: 90, + no_renegotiation: 100 +}; + +/** + * TLS Heartbeat Message types. + * enum { + * heartbeat_request(1), + * heartbeat_response(2), + * (255) + * } HeartbeatMessageType; + */ +tls$1.HeartbeatMessageType = { + heartbeat_request: 1, + heartbeat_response: 2 +}; + +/** + * Supported cipher suites. + */ +tls$1.CipherSuites = {}; + +/** + * Gets a supported cipher suite from its 2 byte ID. + * + * @param twoBytes two bytes in a string. + * + * @return the matching supported cipher suite or null. + */ +tls$1.getCipherSuite = function(twoBytes) { + var rval = null; + for(var key in tls$1.CipherSuites) { + var cs = tls$1.CipherSuites[key]; + if(cs.id[0] === twoBytes.charCodeAt(0) && + cs.id[1] === twoBytes.charCodeAt(1)) { + rval = cs; + break; + } + } + return rval; +}; + +/** + * Called when an unexpected record is encountered. + * + * @param c the connection. + * @param record the record. + */ +tls$1.handleUnexpected = function(c, record) { + // if connection is client and closed, ignore unexpected messages + var ignore = (!c.open && c.entity === tls$1.ConnectionEnd.client); + if(!ignore) { + c.error(c, { + message: 'Unexpected message. Received TLS record out of order.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.unexpected_message + } + }); + } +}; + +/** + * Called when a client receives a HelloRequest record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls$1.handleHelloRequest = function(c, record, length) { + // ignore renegotiation requests from the server during a handshake, but + // if handshaking, send a warning alert that renegotation is denied + if(!c.handshaking && c.handshakes > 0) { + // send alert warning + tls$1.queue(c, tls$1.createAlert(c, { + level: tls$1.Alert.Level.warning, + description: tls$1.Alert.Description.no_renegotiation + })); + tls$1.flush(c); + } + + // continue + c.process(); +}; + +/** + * Parses a hello message from a ClientHello or ServerHello record. + * + * @param record the record to parse. + * + * @return the parsed message. + */ +tls$1.parseHelloMessage = function(c, record, length) { + var msg = null; + + var client = (c.entity === tls$1.ConnectionEnd.client); + + // minimum of 38 bytes in message + if(length < 38) { + c.error(c, { + message: client ? + 'Invalid ServerHello message. Message too short.' : + 'Invalid ClientHello message. Message too short.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.illegal_parameter + } + }); + } else { + // use 'remaining' to calculate # of remaining bytes in the message + var b = record.fragment; + var remaining = b.length(); + msg = { + version: { + major: b.getByte(), + minor: b.getByte() + }, + random: forge$b.util.createBuffer(b.getBytes(32)), + session_id: readVector(b, 1), + extensions: [] + }; + if(client) { + msg.cipher_suite = b.getBytes(2); + msg.compression_method = b.getByte(); + } else { + msg.cipher_suites = readVector(b, 2); + msg.compression_methods = readVector(b, 1); + } + + // read extensions if there are any bytes left in the message + remaining = length - (remaining - b.length()); + if(remaining > 0) { + // parse extensions + var exts = readVector(b, 2); + while(exts.length() > 0) { + msg.extensions.push({ + type: [exts.getByte(), exts.getByte()], + data: readVector(exts, 2) + }); + } + + // TODO: make extension support modular + if(!client) { + for(var i = 0; i < msg.extensions.length; ++i) { + var ext = msg.extensions[i]; + + // support SNI extension + if(ext.type[0] === 0x00 && ext.type[1] === 0x00) { + // get server name list + var snl = readVector(ext.data, 2); + while(snl.length() > 0) { + // read server name type + var snType = snl.getByte(); + + // only HostName type (0x00) is known, break out if + // another type is detected + if(snType !== 0x00) { + break; + } + + // add host name to server name list + c.session.extensions.server_name.serverNameList.push( + readVector(snl, 2).getBytes()); + } + } + } + } + } + + // version already set, do not allow version change + if(c.session.version) { + if(msg.version.major !== c.session.version.major || + msg.version.minor !== c.session.version.minor) { + return c.error(c, { + message: 'TLS version change is disallowed during renegotiation.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.protocol_version + } + }); + } + } + + // get the chosen (ServerHello) cipher suite + if(client) { + // FIXME: should be checking configured acceptable cipher suites + c.session.cipherSuite = tls$1.getCipherSuite(msg.cipher_suite); + } else { + // get a supported preferred (ClientHello) cipher suite + // choose the first supported cipher suite + var tmp = forge$b.util.createBuffer(msg.cipher_suites.bytes()); + while(tmp.length() > 0) { + // FIXME: should be checking configured acceptable suites + // cipher suites take up 2 bytes + c.session.cipherSuite = tls$1.getCipherSuite(tmp.getBytes(2)); + if(c.session.cipherSuite !== null) { + break; + } + } + } + + // cipher suite not supported + if(c.session.cipherSuite === null) { + return c.error(c, { + message: 'No cipher suites in common.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.handshake_failure + }, + cipherSuite: forge$b.util.bytesToHex(msg.cipher_suite) + }); + } + + // TODO: handle compression methods + if(client) { + c.session.compressionMethod = msg.compression_method; + } else { + // no compression + c.session.compressionMethod = tls$1.CompressionMethod.none; + } + } + + return msg; +}; + +/** + * Creates security parameters for the given connection based on the given + * hello message. + * + * @param c the TLS connection. + * @param msg the hello message. + */ +tls$1.createSecurityParameters = function(c, msg) { + /* Note: security params are from TLS 1.2, some values like prf_algorithm + are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is + used. */ + + // TODO: handle other options from server when more supported + + // get client and server randoms + var client = (c.entity === tls$1.ConnectionEnd.client); + var msgRandom = msg.random.bytes(); + var cRandom = client ? c.session.sp.client_random : msgRandom; + var sRandom = client ? msgRandom : tls$1.createRandom().getBytes(); + + // create new security parameters + c.session.sp = { + entity: c.entity, + prf_algorithm: tls$1.PRFAlgorithm.tls_prf_sha256, + bulk_cipher_algorithm: null, + cipher_type: null, + enc_key_length: null, + block_length: null, + fixed_iv_length: null, + record_iv_length: null, + mac_algorithm: null, + mac_length: null, + mac_key_length: null, + compression_algorithm: c.session.compressionMethod, + pre_master_secret: null, + master_secret: null, + client_random: cRandom, + server_random: sRandom + }; +}; + +/** + * Called when a client receives a ServerHello record. + * + * When a ServerHello message will be sent: + * The server will send this message in response to a client hello message + * when it was able to find an acceptable set of algorithms. If it cannot + * find such a match, it will respond with a handshake failure alert. + * + * uint24 length; + * struct { + * ProtocolVersion server_version; + * Random random; + * SessionID session_id; + * CipherSuite cipher_suite; + * CompressionMethod compression_method; + * select(extensions_present) { + * case false: + * struct {}; + * case true: + * Extension extensions<0..2^16-1>; + * }; + * } ServerHello; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls$1.handleServerHello = function(c, record, length) { + var msg = tls$1.parseHelloMessage(c, record, length); + if(c.fail) { + return; + } + + // ensure server version is compatible + if(msg.version.minor <= c.version.minor) { + c.version.minor = msg.version.minor; + } else { + return c.error(c, { + message: 'Incompatible TLS version.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.protocol_version + } + }); + } + + // indicate session version has been set + c.session.version = c.version; + + // get the session ID from the message + var sessionId = msg.session_id.bytes(); + + // if the session ID is not blank and matches the cached one, resume + // the session + if(sessionId.length > 0 && sessionId === c.session.id) { + // resuming session, expect a ChangeCipherSpec next + c.expect = SCC; + c.session.resuming = true; + + // get new server random + c.session.sp.server_random = msg.random.bytes(); + } else { + // not resuming, expect a server Certificate message next + c.expect = SCE; + c.session.resuming = false; + + // create new security parameters + tls$1.createSecurityParameters(c, msg); + } + + // set new session ID + c.session.id = sessionId; + + // continue + c.process(); +}; + +/** + * Called when a server receives a ClientHello record. + * + * When a ClientHello message will be sent: + * When a client first connects to a server it is required to send the + * client hello as its first message. The client can also send a client + * hello in response to a hello request or on its own initiative in order + * to renegotiate the security parameters in an existing connection. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls$1.handleClientHello = function(c, record, length) { + var msg = tls$1.parseHelloMessage(c, record, length); + if(c.fail) { + return; + } + + // get the session ID from the message + var sessionId = msg.session_id.bytes(); + + // see if the given session ID is in the cache + var session = null; + if(c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + if(session === null) { + // session ID not found + sessionId = ''; + } else if(session.version.major !== msg.version.major || + session.version.minor > msg.version.minor) { + // if session version is incompatible with client version, do not resume + session = null; + sessionId = ''; + } + } + + // no session found to resume, generate a new session ID + if(sessionId.length === 0) { + sessionId = forge$b.random.getBytes(32); + } + + // update session + c.session.id = sessionId; + c.session.clientHelloVersion = msg.version; + c.session.sp = {}; + if(session) { + // use version and security parameters from resumed session + c.version = c.session.version = session.version; + c.session.sp = session.sp; + } else { + // use highest compatible minor version + var version; + for(var i = 1; i < tls$1.SupportedVersions.length; ++i) { + version = tls$1.SupportedVersions[i]; + if(version.minor <= msg.version.minor) { + break; + } + } + c.version = {major: version.major, minor: version.minor}; + c.session.version = c.version; + } + + // if a session is set, resume it + if(session !== null) { + // resuming session, expect a ChangeCipherSpec next + c.expect = CCC; + c.session.resuming = true; + + // get new client random + c.session.sp.client_random = msg.random.bytes(); + } else { + // not resuming, expect a Certificate or ClientKeyExchange + c.expect = (c.verifyClient !== false) ? CCE : CKE; + c.session.resuming = false; + + // create new security parameters + tls$1.createSecurityParameters(c, msg); + } + + // connection now open + c.open = true; + + // queue server hello + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createServerHello(c) + })); + + if(c.session.resuming) { + // queue change cipher spec message + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.change_cipher_spec, + data: tls$1.createChangeCipherSpec() + })); + + // create pending state + c.state.pending = tls$1.createConnectionState(c); + + // change current write state to pending write state + c.state.current.write = c.state.pending.write; + + // queue finished + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createFinished(c) + })); + } else { + // queue server certificate + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createCertificate(c) + })); + + if(!c.fail) { + // queue server key exchange + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createServerKeyExchange(c) + })); + + // request client certificate if set + if(c.verifyClient !== false) { + // queue certificate request + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createCertificateRequest(c) + })); + } + + // queue server hello done + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createServerHelloDone(c) + })); + } + } + + // send records + tls$1.flush(c); + + // continue + c.process(); +}; + +/** + * Called when a client receives a Certificate record. + * + * When this message will be sent: + * The server must send a certificate whenever the agreed-upon key exchange + * method is not an anonymous one. This message will always immediately + * follow the server hello message. + * + * Meaning of this message: + * The certificate type must be appropriate for the selected cipher suite's + * key exchange algorithm, and is generally an X.509v3 certificate. It must + * contain a key which matches the key exchange method, as follows. Unless + * otherwise specified, the signing algorithm for the certificate must be + * the same as the algorithm for the certificate key. Unless otherwise + * specified, the public key may be of any length. + * + * opaque ASN.1Cert<1..2^24-1>; + * struct { + * ASN.1Cert certificate_list<1..2^24-1>; + * } Certificate; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls$1.handleCertificate = function(c, record, length) { + // minimum of 3 bytes in message + if(length < 3) { + return c.error(c, { + message: 'Invalid Certificate message. Message too short.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.illegal_parameter + } + }); + } + + var b = record.fragment; + var msg = { + certificate_list: readVector(b, 3) + }; + + /* The sender's certificate will be first in the list (chain), each + subsequent one that follows will certify the previous one, but root + certificates (self-signed) that specify the certificate authority may + be omitted under the assumption that clients must already possess it. */ + var cert, asn1; + var certs = []; + try { + while(msg.certificate_list.length() > 0) { + // each entry in msg.certificate_list is a vector with 3 len bytes + cert = readVector(msg.certificate_list, 3); + asn1 = forge$b.asn1.fromDer(cert); + cert = forge$b.pki.certificateFromAsn1(asn1, true); + certs.push(cert); + } + } catch(ex) { + return c.error(c, { + message: 'Could not parse certificate list.', + cause: ex, + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.bad_certificate + } + }); + } + + // ensure at least 1 certificate was provided if in client-mode + // or if verifyClient was set to true to require a certificate + // (as opposed to 'optional') + var client = (c.entity === tls$1.ConnectionEnd.client); + if((client || c.verifyClient === true) && certs.length === 0) { + // error, no certificate + c.error(c, { + message: client ? + 'No server certificate provided.' : + 'No client certificate provided.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.illegal_parameter + } + }); + } else if(certs.length === 0) { + // no certs to verify + // expect a ServerKeyExchange or ClientKeyExchange message next + c.expect = client ? SKE : CKE; + } else { + // save certificate in session + if(client) { + c.session.serverCertificate = certs[0]; + } else { + c.session.clientCertificate = certs[0]; + } + + if(tls$1.verifyCertificateChain(c, certs)) { + // expect a ServerKeyExchange or ClientKeyExchange message next + c.expect = client ? SKE : CKE; + } + } + + // continue + c.process(); +}; + +/** + * Called when a client receives a ServerKeyExchange record. + * + * When this message will be sent: + * This message will be sent immediately after the server certificate + * message (or the server hello message, if this is an anonymous + * negotiation). + * + * The server key exchange message is sent by the server only when the + * server certificate message (if sent) does not contain enough data to + * allow the client to exchange a premaster secret. + * + * Meaning of this message: + * This message conveys cryptographic information to allow the client to + * communicate the premaster secret: either an RSA public key to encrypt + * the premaster secret with, or a Diffie-Hellman public key with which the + * client can complete a key exchange (with the result being the premaster + * secret.) + * + * enum { + * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa + * } KeyExchangeAlgorithm; + * + * struct { + * opaque dh_p<1..2^16-1>; + * opaque dh_g<1..2^16-1>; + * opaque dh_Ys<1..2^16-1>; + * } ServerDHParams; + * + * struct { + * select(KeyExchangeAlgorithm) { + * case dh_anon: + * ServerDHParams params; + * case dhe_dss: + * case dhe_rsa: + * ServerDHParams params; + * digitally-signed struct { + * opaque client_random[32]; + * opaque server_random[32]; + * ServerDHParams params; + * } signed_params; + * case rsa: + * case dh_dss: + * case dh_rsa: + * struct {}; + * }; + * } ServerKeyExchange; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls$1.handleServerKeyExchange = function(c, record, length) { + // this implementation only supports RSA, no Diffie-Hellman support + // so any length > 0 is invalid + if(length > 0) { + return c.error(c, { + message: 'Invalid key parameters. Only RSA is supported.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.unsupported_certificate + } + }); + } + + // expect an optional CertificateRequest message next + c.expect = SCR; + + // continue + c.process(); +}; + +/** + * Called when a client receives a ClientKeyExchange record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls$1.handleClientKeyExchange = function(c, record, length) { + // this implementation only supports RSA, no Diffie-Hellman support + // so any length < 48 is invalid + if(length < 48) { + return c.error(c, { + message: 'Invalid key parameters. Only RSA is supported.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.unsupported_certificate + } + }); + } + + var b = record.fragment; + var msg = { + enc_pre_master_secret: readVector(b, 2).getBytes() + }; + + // do rsa decryption + var privateKey = null; + if(c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.serverCertificate); + privateKey = forge$b.pki.privateKeyFromPem(privateKey); + } catch(ex) { + c.error(c, { + message: 'Could not get private key.', + cause: ex, + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.internal_error + } + }); + } + } + + if(privateKey === null) { + return c.error(c, { + message: 'No private key set.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.internal_error + } + }); + } + + try { + // decrypt 48-byte pre-master secret + var sp = c.session.sp; + sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); + + // ensure client hello version matches first 2 bytes + var version = c.session.clientHelloVersion; + if(version.major !== sp.pre_master_secret.charCodeAt(0) || + version.minor !== sp.pre_master_secret.charCodeAt(1)) { + // error, do not send alert (see BLEI attack below) + throw new Error('TLS version rollback attack detected.'); + } + } catch(ex) { + /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a + TLS server which is using PKCS#1 encoded RSA, so instead of + failing here, we generate 48 random bytes and use that as + the pre-master secret. */ + sp.pre_master_secret = forge$b.random.getBytes(48); + } + + // expect a CertificateVerify message if a Certificate was received that + // does not have fixed Diffie-Hellman params, otherwise expect + // ChangeCipherSpec + c.expect = CCC; + if(c.session.clientCertificate !== null) { + // only RSA support, so expect CertificateVerify + // TODO: support Diffie-Hellman + c.expect = CCV; + } + + // continue + c.process(); +}; + +/** + * Called when a client receives a CertificateRequest record. + * + * When this message will be sent: + * A non-anonymous server can optionally request a certificate from the + * client, if appropriate for the selected cipher suite. This message, if + * sent, will immediately follow the Server Key Exchange message (if it is + * sent; otherwise, the Server Certificate message). + * + * enum { + * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4), + * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6), + * fortezza_dms_RESERVED(20), (255) + * } ClientCertificateType; + * + * opaque DistinguishedName<1..2^16-1>; + * + * struct { + * ClientCertificateType certificate_types<1..2^8-1>; + * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>; + * DistinguishedName certificate_authorities<0..2^16-1>; + * } CertificateRequest; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls$1.handleCertificateRequest = function(c, record, length) { + // minimum of 3 bytes in message + if(length < 3) { + return c.error(c, { + message: 'Invalid CertificateRequest. Message too short.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.illegal_parameter + } + }); + } + + // TODO: TLS 1.2+ has different format including + // SignatureAndHashAlgorithm after cert types + var b = record.fragment; + var msg = { + certificate_types: readVector(b, 1), + certificate_authorities: readVector(b, 2) + }; + + // save certificate request in session + c.session.certificateRequest = msg; + + // expect a ServerHelloDone message next + c.expect = SHD; + + // continue + c.process(); +}; + +/** + * Called when a server receives a CertificateVerify record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls$1.handleCertificateVerify = function(c, record, length) { + if(length < 2) { + return c.error(c, { + message: 'Invalid CertificateVerify. Message too short.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.illegal_parameter + } + }); + } + + // rewind to get full bytes for message so it can be manually + // digested below (special case for CertificateVerify messages because + // they must be digested *after* handling as opposed to all others) + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; + + var msg = { + signature: readVector(b, 2).getBytes() + }; + + // TODO: add support for DSA + + // generate data to verify + var verify = forge$b.util.createBuffer(); + verify.putBuffer(c.session.md5.digest()); + verify.putBuffer(c.session.sha1.digest()); + verify = verify.getBytes(); + + try { + var cert = c.session.clientCertificate; + /*b = forge.pki.rsa.decrypt( + msg.signature, cert.publicKey, true, verify.length); + if(b !== verify) {*/ + if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) { + throw new Error('CertificateVerify signature does not match.'); + } + + // digest message now that it has been handled + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + } catch(ex) { + return c.error(c, { + message: 'Bad signature in CertificateVerify.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.handshake_failure + } + }); + } + + // expect ChangeCipherSpec + c.expect = CCC; + + // continue + c.process(); +}; + +/** + * Called when a client receives a ServerHelloDone record. + * + * When this message will be sent: + * The server hello done message is sent by the server to indicate the end + * of the server hello and associated messages. After sending this message + * the server will wait for a client response. + * + * Meaning of this message: + * This message means that the server is done sending messages to support + * the key exchange, and the client can proceed with its phase of the key + * exchange. + * + * Upon receipt of the server hello done message the client should verify + * that the server provided a valid certificate if required and check that + * the server hello parameters are acceptable. + * + * struct {} ServerHelloDone; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls$1.handleServerHelloDone = function(c, record, length) { + // len must be 0 bytes + if(length > 0) { + return c.error(c, { + message: 'Invalid ServerHelloDone message. Invalid length.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.record_overflow + } + }); + } + + if(c.serverCertificate === null) { + // no server certificate was provided + var error = { + message: 'No server certificate provided. Not enough security.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.insufficient_security + } + }; + + // call application callback + var depth = 0; + var ret = c.verify(c, error.alert.description, depth, []); + if(ret !== true) { + // check for custom alert info + if(ret || ret === 0) { + // set custom message and alert description + if(typeof ret === 'object' && !forge$b.util.isArray(ret)) { + if(ret.message) { + error.message = ret.message; + } + if(ret.alert) { + error.alert.description = ret.alert; + } + } else if(typeof ret === 'number') { + // set custom alert description + error.alert.description = ret; + } + } + + // send error + return c.error(c, error); + } + } + + // create client certificate message if requested + if(c.session.certificateRequest !== null) { + record = tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createCertificate(c) + }); + tls$1.queue(c, record); + } + + // create client key exchange message + record = tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createClientKeyExchange(c) + }); + tls$1.queue(c, record); + + // expect no messages until the following callback has been called + c.expect = SER; + + // create callback to handle client signature (for client-certs) + var callback = function(c, signature) { + if(c.session.certificateRequest !== null && + c.session.clientCertificate !== null) { + // create certificate verify message + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createCertificateVerify(c, signature) + })); + } + + // create change cipher spec message + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.change_cipher_spec, + data: tls$1.createChangeCipherSpec() + })); + + // create pending state + c.state.pending = tls$1.createConnectionState(c); + + // change current write state to pending write state + c.state.current.write = c.state.pending.write; + + // create finished message + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createFinished(c) + })); + + // expect a server ChangeCipherSpec message next + c.expect = SCC; + + // send records + tls$1.flush(c); + + // continue + c.process(); + }; + + // if there is no certificate request or no client certificate, do + // callback immediately + if(c.session.certificateRequest === null || + c.session.clientCertificate === null) { + return callback(c, null); + } + + // otherwise get the client signature + tls$1.getClientSignature(c, callback); +}; + +/** + * Called when a ChangeCipherSpec record is received. + * + * @param c the connection. + * @param record the record. + */ +tls$1.handleChangeCipherSpec = function(c, record) { + if(record.fragment.getByte() !== 0x01) { + return c.error(c, { + message: 'Invalid ChangeCipherSpec message received.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.illegal_parameter + } + }); + } + + // create pending state if: + // 1. Resuming session in client mode OR + // 2. NOT resuming session in server mode + var client = (c.entity === tls$1.ConnectionEnd.client); + if((c.session.resuming && client) || (!c.session.resuming && !client)) { + c.state.pending = tls$1.createConnectionState(c); + } + + // change current read state to pending read state + c.state.current.read = c.state.pending.read; + + // clear pending state if: + // 1. NOT resuming session in client mode OR + // 2. resuming a session in server mode + if((!c.session.resuming && client) || (c.session.resuming && !client)) { + c.state.pending = null; + } + + // expect a Finished record next + c.expect = client ? SFI : CFI; + + // continue + c.process(); +}; + +/** + * Called when a Finished record is received. + * + * When this message will be sent: + * A finished message is always sent immediately after a change + * cipher spec message to verify that the key exchange and + * authentication processes were successful. It is essential that a + * change cipher spec message be received between the other + * handshake messages and the Finished message. + * + * Meaning of this message: + * The finished message is the first protected with the just- + * negotiated algorithms, keys, and secrets. Recipients of finished + * messages must verify that the contents are correct. Once a side + * has sent its Finished message and received and validated the + * Finished message from its peer, it may begin to send and receive + * application data over the connection. + * + * struct { + * opaque verify_data[verify_data_length]; + * } Finished; + * + * verify_data + * PRF(master_secret, finished_label, Hash(handshake_messages)) + * [0..verify_data_length-1]; + * + * finished_label + * For Finished messages sent by the client, the string + * "client finished". For Finished messages sent by the server, the + * string "server finished". + * + * verify_data_length depends on the cipher suite. If it is not specified + * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used + * 12 bytes. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls$1.handleFinished = function(c, record, length) { + // rewind to get full bytes for message so it can be manually + // digested below (special case for Finished messages because they + // must be digested *after* handling as opposed to all others) + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; + + // message contains only verify_data + var vd = record.fragment.getBytes(); + + // ensure verify data is correct + b = forge$b.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + + // set label based on entity type + var client = (c.entity === tls$1.ConnectionEnd.client); + var label = client ? 'server finished' : 'client finished'; + + // TODO: determine prf function and verify length for TLS 1.2 + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + if(b.getBytes() !== vd) { + return c.error(c, { + message: 'Invalid verify_data in Finished message.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.decrypt_error + } + }); + } + + // digest finished message now that it has been handled + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + + // resuming session as client or NOT resuming session as server + if((c.session.resuming && client) || (!c.session.resuming && !client)) { + // create change cipher spec message + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.change_cipher_spec, + data: tls$1.createChangeCipherSpec() + })); + + // change current write state to pending write state, clear pending + c.state.current.write = c.state.pending.write; + c.state.pending = null; + + // create finished message + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createFinished(c) + })); + } + + // expect application data next + c.expect = client ? SAD : CAD; + + // handshake complete + c.handshaking = false; + ++c.handshakes; + + // save access to peer certificate + c.peerCertificate = client ? + c.session.serverCertificate : c.session.clientCertificate; + + // send records + tls$1.flush(c); + + // now connected + c.isConnected = true; + c.connected(c); + + // continue + c.process(); +}; + +/** + * Called when an Alert record is received. + * + * @param c the connection. + * @param record the record. + */ +tls$1.handleAlert = function(c, record) { + // read alert + var b = record.fragment; + var alert = { + level: b.getByte(), + description: b.getByte() + }; + + // TODO: consider using a table? + // get appropriate message + var msg; + switch(alert.description) { + case tls$1.Alert.Description.close_notify: + msg = 'Connection closed.'; + break; + case tls$1.Alert.Description.unexpected_message: + msg = 'Unexpected message.'; + break; + case tls$1.Alert.Description.bad_record_mac: + msg = 'Bad record MAC.'; + break; + case tls$1.Alert.Description.decryption_failed: + msg = 'Decryption failed.'; + break; + case tls$1.Alert.Description.record_overflow: + msg = 'Record overflow.'; + break; + case tls$1.Alert.Description.decompression_failure: + msg = 'Decompression failed.'; + break; + case tls$1.Alert.Description.handshake_failure: + msg = 'Handshake failure.'; + break; + case tls$1.Alert.Description.bad_certificate: + msg = 'Bad certificate.'; + break; + case tls$1.Alert.Description.unsupported_certificate: + msg = 'Unsupported certificate.'; + break; + case tls$1.Alert.Description.certificate_revoked: + msg = 'Certificate revoked.'; + break; + case tls$1.Alert.Description.certificate_expired: + msg = 'Certificate expired.'; + break; + case tls$1.Alert.Description.certificate_unknown: + msg = 'Certificate unknown.'; + break; + case tls$1.Alert.Description.illegal_parameter: + msg = 'Illegal parameter.'; + break; + case tls$1.Alert.Description.unknown_ca: + msg = 'Unknown certificate authority.'; + break; + case tls$1.Alert.Description.access_denied: + msg = 'Access denied.'; + break; + case tls$1.Alert.Description.decode_error: + msg = 'Decode error.'; + break; + case tls$1.Alert.Description.decrypt_error: + msg = 'Decrypt error.'; + break; + case tls$1.Alert.Description.export_restriction: + msg = 'Export restriction.'; + break; + case tls$1.Alert.Description.protocol_version: + msg = 'Unsupported protocol version.'; + break; + case tls$1.Alert.Description.insufficient_security: + msg = 'Insufficient security.'; + break; + case tls$1.Alert.Description.internal_error: + msg = 'Internal error.'; + break; + case tls$1.Alert.Description.user_canceled: + msg = 'User canceled.'; + break; + case tls$1.Alert.Description.no_renegotiation: + msg = 'Renegotiation not supported.'; + break; + default: + msg = 'Unknown error.'; + break; + } + + // close connection on close_notify, not an error + if(alert.description === tls$1.Alert.Description.close_notify) { + return c.close(); + } + + // call error handler + c.error(c, { + message: msg, + send: false, + // origin is the opposite end + origin: (c.entity === tls$1.ConnectionEnd.client) ? 'server' : 'client', + alert: alert + }); + + // continue + c.process(); +}; + +/** + * Called when a Handshake record is received. + * + * @param c the connection. + * @param record the record. + */ +tls$1.handleHandshake = function(c, record) { + // get the handshake type and message length + var b = record.fragment; + var type = b.getByte(); + var length = b.getInt24(); + + // see if the record fragment doesn't yet contain the full message + if(length > b.length()) { + // cache the record, clear its fragment, and reset the buffer read + // pointer before the type and length were read + c.fragmented = record; + record.fragment = forge$b.util.createBuffer(); + b.read -= 4; + + // continue + return c.process(); + } + + // full message now available, clear cache, reset read pointer to + // before type and length + c.fragmented = null; + b.read -= 4; + + // save the handshake bytes for digestion after handler is found + // (include type and length of handshake msg) + var bytes = b.bytes(length + 4); + + // restore read pointer + b.read += 4; + + // handle expected message + if(type in hsTable[c.entity][c.expect]) { + // initialize server session + if(c.entity === tls$1.ConnectionEnd.server && !c.open && !c.fail) { + c.handshaking = true; + c.session = { + version: null, + extensions: { + server_name: { + serverNameList: [] + } + }, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + clientCertificate: null, + md5: forge$b.md.md5.create(), + sha1: forge$b.md.sha1.create() + }; + } + + /* Update handshake messages digest. Finished and CertificateVerify + messages are not digested here. They can't be digested as part of + the verify_data that they contain. These messages are manually + digested in their handlers. HelloRequest messages are simply never + included in the handshake message digest according to spec. */ + if(type !== tls$1.HandshakeType.hello_request && + type !== tls$1.HandshakeType.certificate_verify && + type !== tls$1.HandshakeType.finished) { + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + } + + // handle specific handshake type record + hsTable[c.entity][c.expect][type](c, record, length); + } else { + // unexpected record + tls$1.handleUnexpected(c, record); + } +}; + +/** + * Called when an ApplicationData record is received. + * + * @param c the connection. + * @param record the record. + */ +tls$1.handleApplicationData = function(c, record) { + // buffer data, notify that its ready + c.data.putBuffer(record.fragment); + c.dataReady(c); + + // continue + c.process(); +}; + +/** + * Called when a Heartbeat record is received. + * + * @param c the connection. + * @param record the record. + */ +tls$1.handleHeartbeat = function(c, record) { + // get the heartbeat type and payload + var b = record.fragment; + var type = b.getByte(); + var length = b.getInt16(); + var payload = b.getBytes(length); + + if(type === tls$1.HeartbeatMessageType.heartbeat_request) { + // discard request during handshake or if length is too large + if(c.handshaking || length > payload.length) { + // continue + return c.process(); + } + // retransmit payload + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.heartbeat, + data: tls$1.createHeartbeat( + tls$1.HeartbeatMessageType.heartbeat_response, payload) + })); + tls$1.flush(c); + } else if(type === tls$1.HeartbeatMessageType.heartbeat_response) { + // check payload against expected payload, discard heartbeat if no match + if(payload !== c.expectedHeartbeatPayload) { + // continue + return c.process(); + } + + // notify that a valid heartbeat was received + if(c.heartbeatReceived) { + c.heartbeatReceived(c, forge$b.util.createBuffer(payload)); + } + } + + // continue + c.process(); +}; + +/** + * The transistional state tables for receiving TLS records. It maps the + * current TLS engine state and a received record to a function to handle the + * record and update the state. + * + * For instance, if the current state is SHE, then the TLS engine is expecting + * a ServerHello record. Once a record is received, the handler function is + * looked up using the state SHE and the record's content type. + * + * The resulting function will either be an error handler or a record handler. + * The function will take whatever action is appropriate and update the state + * for the next record. + * + * The states are all based on possible server record types. Note that the + * client will never specifically expect to receive a HelloRequest or an alert + * from the server so there is no state that reflects this. These messages may + * occur at any time. + * + * There are two tables for mapping states because there is a second tier of + * types for handshake messages. Once a record with a content type of handshake + * is received, the handshake record handler will look up the handshake type in + * the secondary map to get its appropriate handler. + * + * Valid message orders are as follows: + * + * =======================FULL HANDSHAKE====================== + * Client Server + * + * ClientHello --------> + * ServerHello + * Certificate* + * ServerKeyExchange* + * CertificateRequest* + * <-------- ServerHelloDone + * Certificate* + * ClientKeyExchange + * CertificateVerify* + * [ChangeCipherSpec] + * Finished --------> + * [ChangeCipherSpec] + * <-------- Finished + * Application Data <-------> Application Data + * + * =====================SESSION RESUMPTION===================== + * Client Server + * + * ClientHello --------> + * ServerHello + * [ChangeCipherSpec] + * <-------- Finished + * [ChangeCipherSpec] + * Finished --------> + * Application Data <-------> Application Data + */ +// client expect states (indicate which records are expected to be received) +var SHE = 0; // rcv server hello +var SCE = 1; // rcv server certificate +var SKE = 2; // rcv server key exchange +var SCR = 3; // rcv certificate request +var SHD = 4; // rcv server hello done +var SCC = 5; // rcv change cipher spec +var SFI = 6; // rcv finished +var SAD = 7; // rcv application data +var SER = 8; // not expecting any messages at this point + +// server expect states +var CHE = 0; // rcv client hello +var CCE = 1; // rcv client certificate +var CKE = 2; // rcv client key exchange +var CCV = 3; // rcv certificate verify +var CCC = 4; // rcv change cipher spec +var CFI = 5; // rcv finished +var CAD = 6; // rcv application data + +// map client current expect state and content type to function +var __ = tls$1.handleUnexpected; +var R0 = tls$1.handleChangeCipherSpec; +var R1 = tls$1.handleAlert; +var R2 = tls$1.handleHandshake; +var R3 = tls$1.handleApplicationData; +var R4 = tls$1.handleHeartbeat; +var ctTable = []; +ctTable[tls$1.ConnectionEnd.client] = [ +// CC,AL,HS,AD,HB +/*SHE*/[__,R1,R2,__,R4], +/*SCE*/[__,R1,R2,__,R4], +/*SKE*/[__,R1,R2,__,R4], +/*SCR*/[__,R1,R2,__,R4], +/*SHD*/[__,R1,R2,__,R4], +/*SCC*/[R0,R1,__,__,R4], +/*SFI*/[__,R1,R2,__,R4], +/*SAD*/[__,R1,R2,R3,R4], +/*SER*/[__,R1,R2,__,R4] +]; + +// map server current expect state and content type to function +ctTable[tls$1.ConnectionEnd.server] = [ +// CC,AL,HS,AD +/*CHE*/[__,R1,R2,__,R4], +/*CCE*/[__,R1,R2,__,R4], +/*CKE*/[__,R1,R2,__,R4], +/*CCV*/[__,R1,R2,__,R4], +/*CCC*/[R0,R1,__,__,R4], +/*CFI*/[__,R1,R2,__,R4], +/*CAD*/[__,R1,R2,R3,R4], +/*CER*/[__,R1,R2,__,R4] +]; + +// map client current expect state and handshake type to function +var H0 = tls$1.handleHelloRequest; +var H1 = tls$1.handleServerHello; +var H2 = tls$1.handleCertificate; +var H3 = tls$1.handleServerKeyExchange; +var H4 = tls$1.handleCertificateRequest; +var H5 = tls$1.handleServerHelloDone; +var H6 = tls$1.handleFinished; +var hsTable = []; +hsTable[tls$1.ConnectionEnd.client] = [ +// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI +/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__], +/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__], +/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__], +/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__], +/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], +/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] +]; + +// map server current expect state and handshake type to function +// Note: CAD[CH] does not map to FB because renegotation is prohibited +var H7 = tls$1.handleClientHello; +var H8 = tls$1.handleClientKeyExchange; +var H9 = tls$1.handleCertificateVerify; +hsTable[tls$1.ConnectionEnd.server] = [ +// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI +/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__], +/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__], +/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__], +/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], +/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] +]; + +/** + * Generates the master_secret and keys using the given security parameters. + * + * The security parameters for a TLS connection state are defined as such: + * + * struct { + * ConnectionEnd entity; + * PRFAlgorithm prf_algorithm; + * BulkCipherAlgorithm bulk_cipher_algorithm; + * CipherType cipher_type; + * uint8 enc_key_length; + * uint8 block_length; + * uint8 fixed_iv_length; + * uint8 record_iv_length; + * MACAlgorithm mac_algorithm; + * uint8 mac_length; + * uint8 mac_key_length; + * CompressionMethod compression_algorithm; + * opaque master_secret[48]; + * opaque client_random[32]; + * opaque server_random[32]; + * } SecurityParameters; + * + * Note that this definition is from TLS 1.2. In TLS 1.0 some of these + * parameters are ignored because, for instance, the PRFAlgorithm is a + * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0. + * + * The Record Protocol requires an algorithm to generate keys required by the + * current connection state. + * + * The master secret is expanded into a sequence of secure bytes, which is then + * split to a client write MAC key, a server write MAC key, a client write + * encryption key, and a server write encryption key. In TLS 1.0 a client write + * IV and server write IV are also generated. Each of these is generated from + * the byte sequence in that order. Unused values are empty. In TLS 1.2, some + * AEAD ciphers may additionally require a client write IV and a server write + * IV (see Section 6.2.3.3). + * + * When keys, MAC keys, and IVs are generated, the master secret is used as an + * entropy source. + * + * To generate the key material, compute: + * + * master_secret = PRF(pre_master_secret, "master secret", + * ClientHello.random + ServerHello.random) + * + * key_block = PRF(SecurityParameters.master_secret, + * "key expansion", + * SecurityParameters.server_random + + * SecurityParameters.client_random); + * + * until enough output has been generated. Then, the key_block is + * partitioned as follows: + * + * client_write_MAC_key[SecurityParameters.mac_key_length] + * server_write_MAC_key[SecurityParameters.mac_key_length] + * client_write_key[SecurityParameters.enc_key_length] + * server_write_key[SecurityParameters.enc_key_length] + * client_write_IV[SecurityParameters.fixed_iv_length] + * server_write_IV[SecurityParameters.fixed_iv_length] + * + * In TLS 1.2, the client_write_IV and server_write_IV are only generated for + * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This + * implementation uses TLS 1.0 so IVs are generated. + * + * Implementation note: The currently defined cipher suite which requires the + * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32 + * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also + * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material. + * + * @param c the connection. + * @param sp the security parameters to use. + * + * @return the security keys. + */ +tls$1.generateKeys = function(c, sp) { + // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) & + // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented + // at present + + // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with + // TLS 1.0 but we don't care right now because AES is better and we have + // an implementation for it + + // TODO: TLS 1.2 implementation + /* + // determine the PRF + var prf; + switch(sp.prf_algorithm) { + case tls.PRFAlgorithm.tls_prf_sha256: + prf = prf_sha256; + break; + default: + // should never happen + throw new Error('Invalid PRF'); + } + */ + + // TLS 1.0/1.1 implementation + var prf = prf_TLS1; + + // concatenate server and client random + var random = sp.client_random + sp.server_random; + + // only create master secret if session is new + if(!c.session.resuming) { + // create master secret, clean up pre-master secret + sp.master_secret = prf( + sp.pre_master_secret, 'master secret', random, 48).bytes(); + sp.pre_master_secret = null; + } + + // generate the amount of key material needed + random = sp.server_random + sp.client_random; + var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; + + // include IV for TLS/1.0 + var tls10 = (c.version.major === tls$1.Versions.TLS_1_0.major && + c.version.minor === tls$1.Versions.TLS_1_0.minor); + if(tls10) { + length += 2 * sp.fixed_iv_length; + } + var km = prf(sp.master_secret, 'key expansion', random, length); + + // split the key material into the MAC and encryption keys + var rval = { + client_write_MAC_key: km.getBytes(sp.mac_key_length), + server_write_MAC_key: km.getBytes(sp.mac_key_length), + client_write_key: km.getBytes(sp.enc_key_length), + server_write_key: km.getBytes(sp.enc_key_length) + }; + + // include TLS 1.0 IVs + if(tls10) { + rval.client_write_IV = km.getBytes(sp.fixed_iv_length); + rval.server_write_IV = km.getBytes(sp.fixed_iv_length); + } + + return rval; +}; + +/** + * Creates a new initialized TLS connection state. A connection state has + * a read mode and a write mode. + * + * compression state: + * The current state of the compression algorithm. + * + * cipher state: + * The current state of the encryption algorithm. This will consist of the + * scheduled key for that connection. For stream ciphers, this will also + * contain whatever state information is necessary to allow the stream to + * continue to encrypt or decrypt data. + * + * MAC key: + * The MAC key for the connection. + * + * sequence number: + * Each connection state contains a sequence number, which is maintained + * separately for read and write states. The sequence number MUST be set to + * zero whenever a connection state is made the active state. Sequence + * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do + * not wrap. If a TLS implementation would need to wrap a sequence number, + * it must renegotiate instead. A sequence number is incremented after each + * record: specifically, the first record transmitted under a particular + * connection state MUST use sequence number 0. + * + * @param c the connection. + * + * @return the new initialized TLS connection state. + */ +tls$1.createConnectionState = function(c) { + var client = (c.entity === tls$1.ConnectionEnd.client); + + var createMode = function() { + var mode = { + // two 32-bit numbers, first is most significant + sequenceNumber: [0, 0], + macKey: null, + macLength: 0, + macFunction: null, + cipherState: null, + cipherFunction: function(record) {return true;}, + compressionState: null, + compressFunction: function(record) {return true;}, + updateSequenceNumber: function() { + if(mode.sequenceNumber[1] === 0xFFFFFFFF) { + mode.sequenceNumber[1] = 0; + ++mode.sequenceNumber[0]; + } else { + ++mode.sequenceNumber[1]; + } + } + }; + return mode; + }; + var state = { + read: createMode(), + write: createMode() + }; + + // update function in read mode will decrypt then decompress a record + state.read.update = function(c, record) { + if(!state.read.cipherFunction(record, state.read)) { + c.error(c, { + message: 'Could not decrypt record or bad MAC.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + // doesn't matter if decryption failed or MAC was + // invalid, return the same error so as not to reveal + // which one occurred + description: tls$1.Alert.Description.bad_record_mac + } + }); + } else if(!state.read.compressFunction(c, record, state.read)) { + c.error(c, { + message: 'Could not decompress record.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.decompression_failure + } + }); + } + return !c.fail; + }; + + // update function in write mode will compress then encrypt a record + state.write.update = function(c, record) { + if(!state.write.compressFunction(c, record, state.write)) { + // error, but do not send alert since it would require + // compression as well + c.error(c, { + message: 'Could not compress record.', + send: false, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.internal_error + } + }); + } else if(!state.write.cipherFunction(record, state.write)) { + // error, but do not send alert since it would require + // encryption as well + c.error(c, { + message: 'Could not encrypt record.', + send: false, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.internal_error + } + }); + } + return !c.fail; + }; + + // handle security parameters + if(c.session) { + var sp = c.session.sp; + c.session.cipherSuite.initSecurityParameters(sp); + + // generate keys + sp.keys = tls$1.generateKeys(c, sp); + state.read.macKey = client ? + sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; + state.write.macKey = client ? + sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; + + // cipher suite setup + c.session.cipherSuite.initConnectionState(state, c, sp); + + // compression setup + switch(sp.compression_algorithm) { + case tls$1.CompressionMethod.none: + break; + case tls$1.CompressionMethod.deflate: + state.read.compressFunction = inflate; + state.write.compressFunction = deflate; + break; + default: + throw new Error('Unsupported compression algorithm.'); + } + } + + return state; +}; + +/** + * Creates a Random structure. + * + * struct { + * uint32 gmt_unix_time; + * opaque random_bytes[28]; + * } Random; + * + * gmt_unix_time: + * The current time and date in standard UNIX 32-bit format (seconds since + * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according + * to the sender's internal clock. Clocks are not required to be set + * correctly by the basic TLS protocol; higher-level or application + * protocols may define additional requirements. Note that, for historical + * reasons, the data element is named using GMT, the predecessor of the + * current worldwide time base, UTC. + * random_bytes: + * 28 bytes generated by a secure random number generator. + * + * @return the Random structure as a byte array. + */ +tls$1.createRandom = function() { + // get UTC milliseconds + var d = new Date(); + var utc = +d + d.getTimezoneOffset() * 60000; + var rval = forge$b.util.createBuffer(); + rval.putInt32(utc); + rval.putBytes(forge$b.random.getBytes(28)); + return rval; +}; + +/** + * Creates a TLS record with the given type and data. + * + * @param c the connection. + * @param options: + * type: the record type. + * data: the plain text data in a byte buffer. + * + * @return the created record. + */ +tls$1.createRecord = function(c, options) { + if(!options.data) { + return null; + } + var record = { + type: options.type, + version: { + major: c.version.major, + minor: c.version.minor + }, + length: options.data.length(), + fragment: options.data + }; + return record; +}; + +/** + * Creates a TLS alert record. + * + * @param c the connection. + * @param alert: + * level: the TLS alert level. + * description: the TLS alert description. + * + * @return the created alert record. + */ +tls$1.createAlert = function(c, alert) { + var b = forge$b.util.createBuffer(); + b.putByte(alert.level); + b.putByte(alert.description); + return tls$1.createRecord(c, { + type: tls$1.ContentType.alert, + data: b + }); +}; + +/* The structure of a TLS handshake message. + * + * struct { + * HandshakeType msg_type; // handshake type + * uint24 length; // bytes in message + * select(HandshakeType) { + * case hello_request: HelloRequest; + * case client_hello: ClientHello; + * case server_hello: ServerHello; + * case certificate: Certificate; + * case server_key_exchange: ServerKeyExchange; + * case certificate_request: CertificateRequest; + * case server_hello_done: ServerHelloDone; + * case certificate_verify: CertificateVerify; + * case client_key_exchange: ClientKeyExchange; + * case finished: Finished; + * } body; + * } Handshake; + */ + +/** + * Creates a ClientHello message. + * + * opaque SessionID<0..32>; + * enum { null(0), deflate(1), (255) } CompressionMethod; + * uint8 CipherSuite[2]; + * + * struct { + * ProtocolVersion client_version; + * Random random; + * SessionID session_id; + * CipherSuite cipher_suites<2..2^16-2>; + * CompressionMethod compression_methods<1..2^8-1>; + * select(extensions_present) { + * case false: + * struct {}; + * case true: + * Extension extensions<0..2^16-1>; + * }; + * } ClientHello; + * + * The extension format for extended client hellos and server hellos is: + * + * struct { + * ExtensionType extension_type; + * opaque extension_data<0..2^16-1>; + * } Extension; + * + * Here: + * + * - "extension_type" identifies the particular extension type. + * - "extension_data" contains information specific to the particular + * extension type. + * + * The extension types defined in this document are: + * + * enum { + * server_name(0), max_fragment_length(1), + * client_certificate_url(2), trusted_ca_keys(3), + * truncated_hmac(4), status_request(5), (65535) + * } ExtensionType; + * + * @param c the connection. + * + * @return the ClientHello byte buffer. + */ +tls$1.createClientHello = function(c) { + // save hello version + c.session.clientHelloVersion = { + major: c.version.major, + minor: c.version.minor + }; + + // create supported cipher suites + var cipherSuites = forge$b.util.createBuffer(); + for(var i = 0; i < c.cipherSuites.length; ++i) { + var cs = c.cipherSuites[i]; + cipherSuites.putByte(cs.id[0]); + cipherSuites.putByte(cs.id[1]); + } + var cSuites = cipherSuites.length(); + + // create supported compression methods, null always supported, but + // also support deflate if connection has inflate and deflate methods + var compressionMethods = forge$b.util.createBuffer(); + compressionMethods.putByte(tls$1.CompressionMethod.none); + // FIXME: deflate support disabled until issues with raw deflate data + // without zlib headers are resolved + /* + if(c.inflate !== null && c.deflate !== null) { + compressionMethods.putByte(tls.CompressionMethod.deflate); + } + */ + var cMethods = compressionMethods.length(); + + // create TLS SNI (server name indication) extension if virtual host + // has been specified, see RFC 3546 + var extensions = forge$b.util.createBuffer(); + if(c.virtualHost) { + // create extension struct + var ext = forge$b.util.createBuffer(); + ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes) + ext.putByte(0x00); + + /* In order to provide the server name, clients MAY include an + * extension of type "server_name" in the (extended) client hello. + * The "extension_data" field of this extension SHALL contain + * "ServerNameList" where: + * + * struct { + * NameType name_type; + * select(name_type) { + * case host_name: HostName; + * } name; + * } ServerName; + * + * enum { + * host_name(0), (255) + * } NameType; + * + * opaque HostName<1..2^16-1>; + * + * struct { + * ServerName server_name_list<1..2^16-1> + * } ServerNameList; + */ + var serverName = forge$b.util.createBuffer(); + serverName.putByte(0x00); // type host_name + writeVector(serverName, 2, forge$b.util.createBuffer(c.virtualHost)); + + // ServerNameList is in extension_data + var snList = forge$b.util.createBuffer(); + writeVector(snList, 2, serverName); + writeVector(ext, 2, snList); + extensions.putBuffer(ext); + } + var extLength = extensions.length(); + if(extLength > 0) { + // add extension vector length + extLength += 2; + } + + // determine length of the handshake message + // cipher suites and compression methods size will need to be + // updated if more get added to the list + var sessionId = c.session.id; + var length = + sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + cSuites + // cipher suites vector + 1 + cMethods + // compression methods vector + extLength; // extensions vector + + // build record fragment + var rval = forge$b.util.createBuffer(); + rval.putByte(tls$1.HandshakeType.client_hello); + rval.putInt24(length); // handshake length + rval.putByte(c.version.major); // major version + rval.putByte(c.version.minor); // minor version + rval.putBytes(c.session.sp.client_random); // random time + bytes + writeVector(rval, 1, forge$b.util.createBuffer(sessionId)); + writeVector(rval, 2, cipherSuites); + writeVector(rval, 1, compressionMethods); + if(extLength > 0) { + writeVector(rval, 2, extensions); + } + return rval; +}; + +/** + * Creates a ServerHello message. + * + * @param c the connection. + * + * @return the ServerHello byte buffer. + */ +tls$1.createServerHello = function(c) { + // determine length of the handshake message + var sessionId = c.session.id; + var length = + sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + // chosen cipher suite + 1; // chosen compression method + + // build record fragment + var rval = forge$b.util.createBuffer(); + rval.putByte(tls$1.HandshakeType.server_hello); + rval.putInt24(length); // handshake length + rval.putByte(c.version.major); // major version + rval.putByte(c.version.minor); // minor version + rval.putBytes(c.session.sp.server_random); // random time + bytes + writeVector(rval, 1, forge$b.util.createBuffer(sessionId)); + rval.putByte(c.session.cipherSuite.id[0]); + rval.putByte(c.session.cipherSuite.id[1]); + rval.putByte(c.session.compressionMethod); + return rval; +}; + +/** + * Creates a Certificate message. + * + * When this message will be sent: + * This is the first message the client can send after receiving a server + * hello done message and the first message the server can send after + * sending a ServerHello. This client message is only sent if the server + * requests a certificate. If no suitable certificate is available, the + * client should send a certificate message containing no certificates. If + * client authentication is required by the server for the handshake to + * continue, it may respond with a fatal handshake failure alert. + * + * opaque ASN.1Cert<1..2^24-1>; + * + * struct { + * ASN.1Cert certificate_list<0..2^24-1>; + * } Certificate; + * + * @param c the connection. + * + * @return the Certificate byte buffer. + */ +tls$1.createCertificate = function(c) { + // TODO: check certificate request to ensure types are supported + + // get a certificate (a certificate as a PEM string) + var client = (c.entity === tls$1.ConnectionEnd.client); + var cert = null; + if(c.getCertificate) { + var hint; + if(client) { + hint = c.session.certificateRequest; + } else { + hint = c.session.extensions.server_name.serverNameList; + } + cert = c.getCertificate(c, hint); + } + + // buffer to hold certificate list + var certList = forge$b.util.createBuffer(); + if(cert !== null) { + try { + // normalize cert to a chain of certificates + if(!forge$b.util.isArray(cert)) { + cert = [cert]; + } + var asn1 = null; + for(var i = 0; i < cert.length; ++i) { + var msg = forge$b.pem.decode(cert[i])[0]; + if(msg.type !== 'CERTIFICATE' && + msg.type !== 'X509 CERTIFICATE' && + msg.type !== 'TRUSTED CERTIFICATE') { + var error = new Error('Could not convert certificate from PEM; PEM ' + + 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' + + '"TRUSTED CERTIFICATE".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certificate from PEM; PEM is encrypted.'); + } + + var der = forge$b.util.createBuffer(msg.body); + if(asn1 === null) { + asn1 = forge$b.asn1.fromDer(der.bytes(), false); + } + + // certificate entry is itself a vector with 3 length bytes + var certBuffer = forge$b.util.createBuffer(); + writeVector(certBuffer, 3, der); + + // add cert vector to cert list vector + certList.putBuffer(certBuffer); + } + + // save certificate + cert = forge$b.pki.certificateFromAsn1(asn1); + if(client) { + c.session.clientCertificate = cert; + } else { + c.session.serverCertificate = cert; + } + } catch(ex) { + return c.error(c, { + message: 'Could not send certificate list.', + cause: ex, + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.bad_certificate + } + }); + } + } + + // determine length of the handshake message + var length = 3 + certList.length(); // cert list vector + + // build record fragment + var rval = forge$b.util.createBuffer(); + rval.putByte(tls$1.HandshakeType.certificate); + rval.putInt24(length); + writeVector(rval, 3, certList); + return rval; +}; + +/** + * Creates a ClientKeyExchange message. + * + * When this message will be sent: + * This message is always sent by the client. It will immediately follow the + * client certificate message, if it is sent. Otherwise it will be the first + * message sent by the client after it receives the server hello done + * message. + * + * Meaning of this message: + * With this message, the premaster secret is set, either though direct + * transmission of the RSA-encrypted secret, or by the transmission of + * Diffie-Hellman parameters which will allow each side to agree upon the + * same premaster secret. When the key exchange method is DH_RSA or DH_DSS, + * client certification has been requested, and the client was able to + * respond with a certificate which contained a Diffie-Hellman public key + * whose parameters (group and generator) matched those specified by the + * server in its certificate, this message will not contain any data. + * + * Meaning of this message: + * If RSA is being used for key agreement and authentication, the client + * generates a 48-byte premaster secret, encrypts it using the public key + * from the server's certificate or the temporary RSA key provided in a + * server key exchange message, and sends the result in an encrypted + * premaster secret message. This structure is a variant of the client + * key exchange message, not a message in itself. + * + * struct { + * select(KeyExchangeAlgorithm) { + * case rsa: EncryptedPreMasterSecret; + * case diffie_hellman: ClientDiffieHellmanPublic; + * } exchange_keys; + * } ClientKeyExchange; + * + * struct { + * ProtocolVersion client_version; + * opaque random[46]; + * } PreMasterSecret; + * + * struct { + * public-key-encrypted PreMasterSecret pre_master_secret; + * } EncryptedPreMasterSecret; + * + * A public-key-encrypted element is encoded as a vector <0..2^16-1>. + * + * @param c the connection. + * + * @return the ClientKeyExchange byte buffer. + */ +tls$1.createClientKeyExchange = function(c) { + // create buffer to encrypt + var b = forge$b.util.createBuffer(); + + // add highest client-supported protocol to help server avoid version + // rollback attacks + b.putByte(c.session.clientHelloVersion.major); + b.putByte(c.session.clientHelloVersion.minor); + + // generate and add 46 random bytes + b.putBytes(forge$b.random.getBytes(46)); + + // save pre-master secret + var sp = c.session.sp; + sp.pre_master_secret = b.getBytes(); + + // RSA-encrypt the pre-master secret + var key = c.session.serverCertificate.publicKey; + b = key.encrypt(sp.pre_master_secret); + + /* Note: The encrypted pre-master secret will be stored in a + public-key-encrypted opaque vector that has the length prefixed using + 2 bytes, so include those 2 bytes in the handshake message length. This + is done as a minor optimization instead of calling writeVector(). */ + + // determine length of the handshake message + var length = b.length + 2; + + // build record fragment + var rval = forge$b.util.createBuffer(); + rval.putByte(tls$1.HandshakeType.client_key_exchange); + rval.putInt24(length); + // add vector length bytes + rval.putInt16(b.length); + rval.putBytes(b); + return rval; +}; + +/** + * Creates a ServerKeyExchange message. + * + * @param c the connection. + * + * @return the ServerKeyExchange byte buffer. + */ +tls$1.createServerKeyExchange = function(c) { + + // build record fragment + var rval = forge$b.util.createBuffer(); + return rval; +}; + +/** + * Gets the signed data used to verify a client-side certificate. See + * tls.createCertificateVerify() for details. + * + * @param c the connection. + * @param callback the callback to call once the signed data is ready. + */ +tls$1.getClientSignature = function(c, callback) { + // generate data to RSA encrypt + var b = forge$b.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + b = b.getBytes(); + + // create default signing function as necessary + c.getSignature = c.getSignature || function(c, b, callback) { + // do rsa encryption, call callback + var privateKey = null; + if(c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.clientCertificate); + privateKey = forge$b.pki.privateKeyFromPem(privateKey); + } catch(ex) { + c.error(c, { + message: 'Could not get private key.', + cause: ex, + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.internal_error + } + }); + } + } + if(privateKey === null) { + c.error(c, { + message: 'No private key set.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.internal_error + } + }); + } else { + b = privateKey.sign(b, null); + } + callback(c, b); + }; + + // get client signature + c.getSignature(c, b, callback); +}; + +/** + * Creates a CertificateVerify message. + * + * Meaning of this message: + * This structure conveys the client's Diffie-Hellman public value + * (Yc) if it was not already included in the client's certificate. + * The encoding used for Yc is determined by the enumerated + * PublicValueEncoding. This structure is a variant of the client + * key exchange message, not a message in itself. + * + * When this message will be sent: + * This message is used to provide explicit verification of a client + * certificate. This message is only sent following a client + * certificate that has signing capability (i.e. all certificates + * except those containing fixed Diffie-Hellman parameters). When + * sent, it will immediately follow the client key exchange message. + * + * struct { + * Signature signature; + * } CertificateVerify; + * + * CertificateVerify.signature.md5_hash + * MD5(handshake_messages); + * + * Certificate.signature.sha_hash + * SHA(handshake_messages); + * + * Here handshake_messages refers to all handshake messages sent or + * received starting at client hello up to but not including this + * message, including the type and length fields of the handshake + * messages. + * + * select(SignatureAlgorithm) { + * case anonymous: struct { }; + * case rsa: + * digitally-signed struct { + * opaque md5_hash[16]; + * opaque sha_hash[20]; + * }; + * case dsa: + * digitally-signed struct { + * opaque sha_hash[20]; + * }; + * } Signature; + * + * In digital signing, one-way hash functions are used as input for a + * signing algorithm. A digitally-signed element is encoded as an opaque + * vector <0..2^16-1>, where the length is specified by the signing + * algorithm and key. + * + * In RSA signing, a 36-byte structure of two hashes (one SHA and one + * MD5) is signed (encrypted with the private key). It is encoded with + * PKCS #1 block type 0 or type 1 as described in [PKCS1]. + * + * In DSS, the 20 bytes of the SHA hash are run directly through the + * Digital Signing Algorithm with no additional hashing. + * + * @param c the connection. + * @param signature the signature to include in the message. + * + * @return the CertificateVerify byte buffer. + */ +tls$1.createCertificateVerify = function(c, signature) { + /* Note: The signature will be stored in a "digitally-signed" opaque + vector that has the length prefixed using 2 bytes, so include those + 2 bytes in the handshake message length. This is done as a minor + optimization instead of calling writeVector(). */ + + // determine length of the handshake message + var length = signature.length + 2; + + // build record fragment + var rval = forge$b.util.createBuffer(); + rval.putByte(tls$1.HandshakeType.certificate_verify); + rval.putInt24(length); + // add vector length bytes + rval.putInt16(signature.length); + rval.putBytes(signature); + return rval; +}; + +/** + * Creates a CertificateRequest message. + * + * @param c the connection. + * + * @return the CertificateRequest byte buffer. + */ +tls$1.createCertificateRequest = function(c) { + // TODO: support other certificate types + var certTypes = forge$b.util.createBuffer(); + + // common RSA certificate type + certTypes.putByte(0x01); + + // add distinguished names from CA store + var cAs = forge$b.util.createBuffer(); + for(var key in c.caStore.certs) { + var cert = c.caStore.certs[key]; + var dn = forge$b.pki.distinguishedNameToAsn1(cert.subject); + var byteBuffer = forge$b.asn1.toDer(dn); + cAs.putInt16(byteBuffer.length()); + cAs.putBuffer(byteBuffer); + } + + // TODO: TLS 1.2+ has a different format + + // determine length of the handshake message + var length = + 1 + certTypes.length() + + 2 + cAs.length(); + + // build record fragment + var rval = forge$b.util.createBuffer(); + rval.putByte(tls$1.HandshakeType.certificate_request); + rval.putInt24(length); + writeVector(rval, 1, certTypes); + writeVector(rval, 2, cAs); + return rval; +}; + +/** + * Creates a ServerHelloDone message. + * + * @param c the connection. + * + * @return the ServerHelloDone byte buffer. + */ +tls$1.createServerHelloDone = function(c) { + // build record fragment + var rval = forge$b.util.createBuffer(); + rval.putByte(tls$1.HandshakeType.server_hello_done); + rval.putInt24(0); + return rval; +}; + +/** + * Creates a ChangeCipherSpec message. + * + * The change cipher spec protocol exists to signal transitions in + * ciphering strategies. The protocol consists of a single message, + * which is encrypted and compressed under the current (not the pending) + * connection state. The message consists of a single byte of value 1. + * + * struct { + * enum { change_cipher_spec(1), (255) } type; + * } ChangeCipherSpec; + * + * @return the ChangeCipherSpec byte buffer. + */ +tls$1.createChangeCipherSpec = function() { + var rval = forge$b.util.createBuffer(); + rval.putByte(0x01); + return rval; +}; + +/** + * Creates a Finished message. + * + * struct { + * opaque verify_data[12]; + * } Finished; + * + * verify_data + * PRF(master_secret, finished_label, MD5(handshake_messages) + + * SHA-1(handshake_messages)) [0..11]; + * + * finished_label + * For Finished messages sent by the client, the string "client + * finished". For Finished messages sent by the server, the + * string "server finished". + * + * handshake_messages + * All of the data from all handshake messages up to but not + * including this message. This is only data visible at the + * handshake layer and does not include record layer headers. + * This is the concatenation of all the Handshake structures as + * defined in 7.4 exchanged thus far. + * + * @param c the connection. + * + * @return the Finished byte buffer. + */ +tls$1.createFinished = function(c) { + // generate verify_data + var b = forge$b.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + + // TODO: determine prf function and verify length for TLS 1.2 + var client = (c.entity === tls$1.ConnectionEnd.client); + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + var label = client ? 'client finished' : 'server finished'; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + + // build record fragment + var rval = forge$b.util.createBuffer(); + rval.putByte(tls$1.HandshakeType.finished); + rval.putInt24(b.length()); + rval.putBuffer(b); + return rval; +}; + +/** + * Creates a HeartbeatMessage (See RFC 6520). + * + * struct { + * HeartbeatMessageType type; + * uint16 payload_length; + * opaque payload[HeartbeatMessage.payload_length]; + * opaque padding[padding_length]; + * } HeartbeatMessage; + * + * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or + * max_fragment_length when negotiated as defined in [RFC6066]. + * + * type: The message type, either heartbeat_request or heartbeat_response. + * + * payload_length: The length of the payload. + * + * payload: The payload consists of arbitrary content. + * + * padding: The padding is random content that MUST be ignored by the + * receiver. The length of a HeartbeatMessage is TLSPlaintext.length + * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the + * length of the type field is 1 byte, and the length of the + * payload_length is 2. Therefore, the padding_length is + * TLSPlaintext.length - payload_length - 3 for TLS and + * DTLSPlaintext.length - payload_length - 3 for DTLS. The + * padding_length MUST be at least 16. + * + * The sender of a HeartbeatMessage MUST use a random padding of at + * least 16 bytes. The padding of a received HeartbeatMessage message + * MUST be ignored. + * + * If the payload_length of a received HeartbeatMessage is too large, + * the received HeartbeatMessage MUST be discarded silently. + * + * @param c the connection. + * @param type the tls.HeartbeatMessageType. + * @param payload the heartbeat data to send as the payload. + * @param [payloadLength] the payload length to use, defaults to the + * actual payload length. + * + * @return the HeartbeatRequest byte buffer. + */ +tls$1.createHeartbeat = function(type, payload, payloadLength) { + if(typeof payloadLength === 'undefined') { + payloadLength = payload.length; + } + // build record fragment + var rval = forge$b.util.createBuffer(); + rval.putByte(type); // heartbeat message type + rval.putInt16(payloadLength); // payload length + rval.putBytes(payload); // payload + // padding + var plaintextLength = rval.length(); + var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); + rval.putBytes(forge$b.random.getBytes(paddingLength)); + return rval; +}; + +/** + * Fragments, compresses, encrypts, and queues a record for delivery. + * + * @param c the connection. + * @param record the record to queue. + */ +tls$1.queue = function(c, record) { + // error during record creation + if(!record) { + return; + } + + if(record.fragment.length() === 0) { + if(record.type === tls$1.ContentType.handshake || + record.type === tls$1.ContentType.alert || + record.type === tls$1.ContentType.change_cipher_spec) { + // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent. + return; + } + } + + // if the record is a handshake record, update handshake hashes + if(record.type === tls$1.ContentType.handshake) { + var bytes = record.fragment.bytes(); + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + bytes = null; + } + + // handle record fragmentation + var records; + if(record.fragment.length() <= tls$1.MaxFragment) { + records = [record]; + } else { + // fragment data as long as it is too long + records = []; + var data = record.fragment.bytes(); + while(data.length > tls$1.MaxFragment) { + records.push(tls$1.createRecord(c, { + type: record.type, + data: forge$b.util.createBuffer(data.slice(0, tls$1.MaxFragment)) + })); + data = data.slice(tls$1.MaxFragment); + } + // add last record + if(data.length > 0) { + records.push(tls$1.createRecord(c, { + type: record.type, + data: forge$b.util.createBuffer(data) + })); + } + } + + // compress and encrypt all fragmented records + for(var i = 0; i < records.length && !c.fail; ++i) { + // update the record using current write state + var rec = records[i]; + var s = c.state.current.write; + if(s.update(c, rec)) { + // store record + c.records.push(rec); + } + } +}; + +/** + * Flushes all queued records to the output buffer and calls the + * tlsDataReady() handler on the given connection. + * + * @param c the connection. + * + * @return true on success, false on failure. + */ +tls$1.flush = function(c) { + for(var i = 0; i < c.records.length; ++i) { + var record = c.records[i]; + + // add record header and fragment + c.tlsData.putByte(record.type); + c.tlsData.putByte(record.version.major); + c.tlsData.putByte(record.version.minor); + c.tlsData.putInt16(record.fragment.length()); + c.tlsData.putBuffer(c.records[i].fragment); + } + c.records = []; + return c.tlsDataReady(c); +}; + +/** + * Maps a pki.certificateError to a tls.Alert.Description. + * + * @param error the error to map. + * + * @return the alert description. + */ +var _certErrorToAlertDesc = function(error) { + switch(error) { + case true: + return true; + case forge$b.pki.certificateError.bad_certificate: + return tls$1.Alert.Description.bad_certificate; + case forge$b.pki.certificateError.unsupported_certificate: + return tls$1.Alert.Description.unsupported_certificate; + case forge$b.pki.certificateError.certificate_revoked: + return tls$1.Alert.Description.certificate_revoked; + case forge$b.pki.certificateError.certificate_expired: + return tls$1.Alert.Description.certificate_expired; + case forge$b.pki.certificateError.certificate_unknown: + return tls$1.Alert.Description.certificate_unknown; + case forge$b.pki.certificateError.unknown_ca: + return tls$1.Alert.Description.unknown_ca; + default: + return tls$1.Alert.Description.bad_certificate; + } +}; + +/** + * Maps a tls.Alert.Description to a pki.certificateError. + * + * @param desc the alert description. + * + * @return the certificate error. + */ +var _alertDescToCertError = function(desc) { + switch(desc) { + case true: + return true; + case tls$1.Alert.Description.bad_certificate: + return forge$b.pki.certificateError.bad_certificate; + case tls$1.Alert.Description.unsupported_certificate: + return forge$b.pki.certificateError.unsupported_certificate; + case tls$1.Alert.Description.certificate_revoked: + return forge$b.pki.certificateError.certificate_revoked; + case tls$1.Alert.Description.certificate_expired: + return forge$b.pki.certificateError.certificate_expired; + case tls$1.Alert.Description.certificate_unknown: + return forge$b.pki.certificateError.certificate_unknown; + case tls$1.Alert.Description.unknown_ca: + return forge$b.pki.certificateError.unknown_ca; + default: + return forge$b.pki.certificateError.bad_certificate; + } +}; + +/** + * Verifies a certificate chain against the given connection's + * Certificate Authority store. + * + * @param c the TLS connection. + * @param chain the certificate chain to verify, with the root or highest + * authority at the end. + * + * @return true if successful, false if not. + */ +tls$1.verifyCertificateChain = function(c, chain) { + try { + // Make a copy of c.verifyOptions so that we can modify options.verify + // without modifying c.verifyOptions. + var options = {}; + for (var key in c.verifyOptions) { + options[key] = c.verifyOptions[key]; + } + + options.verify = function(vfd, depth, chain) { + + // call application callback + var ret = c.verify(c, vfd, depth, chain); + if(ret !== true) { + if(typeof ret === 'object' && !forge$b.util.isArray(ret)) { + // throw custom error + var error = new Error('The application rejected the certificate.'); + error.send = true; + error.alert = { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.bad_certificate + }; + if(ret.message) { + error.message = ret.message; + } + if(ret.alert) { + error.alert.description = ret.alert; + } + throw error; + } + + // convert tls alert description to pki.certificateError + if(ret !== vfd) { + ret = _alertDescToCertError(ret); + } + } + + return ret; + }; + + // verify chain + forge$b.pki.verifyCertificateChain(c.caStore, chain, options); + } catch(ex) { + // build tls error if not already customized + var err = ex; + if(typeof err !== 'object' || forge$b.util.isArray(err)) { + err = { + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: _certErrorToAlertDesc(ex) + } + }; + } + if(!('send' in err)) { + err.send = true; + } + if(!('alert' in err)) { + err.alert = { + level: tls$1.Alert.Level.fatal, + description: _certErrorToAlertDesc(err.error) + }; + } + + // send error + c.error(c, err); + } + + return !c.fail; +}; + +/** + * Creates a new TLS session cache. + * + * @param cache optional map of session ID to cached session. + * @param capacity the maximum size for the cache (default: 100). + * + * @return the new TLS session cache. + */ +tls$1.createSessionCache = function(cache, capacity) { + var rval = null; + + // assume input is already a session cache object + if(cache && cache.getSession && cache.setSession && cache.order) { + rval = cache; + } else { + // create cache + rval = {}; + rval.cache = cache || {}; + rval.capacity = Math.max(capacity || 100, 1); + rval.order = []; + + // store order for sessions, delete session overflow + for(var key in cache) { + if(rval.order.length <= capacity) { + rval.order.push(key); + } else { + delete cache[key]; + } + } + + // get a session from a session ID (or get any session) + rval.getSession = function(sessionId) { + var session = null; + var key = null; + + // if session ID provided, use it + if(sessionId) { + key = forge$b.util.bytesToHex(sessionId); + } else if(rval.order.length > 0) { + // get first session from cache + key = rval.order[0]; + } + + if(key !== null && key in rval.cache) { + // get cached session and remove from cache + session = rval.cache[key]; + delete rval.cache[key]; + for(var i in rval.order) { + if(rval.order[i] === key) { + rval.order.splice(i, 1); + break; + } + } + } + + return session; + }; + + // set a session in the cache + rval.setSession = function(sessionId, session) { + // remove session from cache if at capacity + if(rval.order.length === rval.capacity) { + var key = rval.order.shift(); + delete rval.cache[key]; + } + // add session to cache + var key = forge$b.util.bytesToHex(sessionId); + rval.order.push(key); + rval.cache[key] = session; + }; + } + + return rval; +}; + +/** + * Creates a new TLS connection. + * + * See public createConnection() docs for more details. + * + * @param options the options for this connection. + * + * @return the new TLS connection. + */ +tls$1.createConnection = function(options) { + var caStore = null; + if(options.caStore) { + // if CA store is an array, convert it to a CA store object + if(forge$b.util.isArray(options.caStore)) { + caStore = forge$b.pki.createCaStore(options.caStore); + } else { + caStore = options.caStore; + } + } else { + // create empty CA store + caStore = forge$b.pki.createCaStore(); + } + + // setup default cipher suites + var cipherSuites = options.cipherSuites || null; + if(cipherSuites === null) { + cipherSuites = []; + for(var key in tls$1.CipherSuites) { + cipherSuites.push(tls$1.CipherSuites[key]); + } + } + + // set default entity + var entity = (options.server || false) ? + tls$1.ConnectionEnd.server : tls$1.ConnectionEnd.client; + + // create session cache if requested + var sessionCache = options.sessionCache ? + tls$1.createSessionCache(options.sessionCache) : null; + + // create TLS connection + var c = { + version: {major: tls$1.Version.major, minor: tls$1.Version.minor}, + entity: entity, + sessionId: options.sessionId, + caStore: caStore, + sessionCache: sessionCache, + cipherSuites: cipherSuites, + connected: options.connected, + virtualHost: options.virtualHost || null, + verifyClient: options.verifyClient || false, + verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;}, + verifyOptions: options.verifyOptions || {}, + getCertificate: options.getCertificate || null, + getPrivateKey: options.getPrivateKey || null, + getSignature: options.getSignature || null, + input: forge$b.util.createBuffer(), + tlsData: forge$b.util.createBuffer(), + data: forge$b.util.createBuffer(), + tlsDataReady: options.tlsDataReady, + dataReady: options.dataReady, + heartbeatReceived: options.heartbeatReceived, + closed: options.closed, + error: function(c, ex) { + // set origin if not set + ex.origin = ex.origin || + ((c.entity === tls$1.ConnectionEnd.client) ? 'client' : 'server'); + + // send TLS alert + if(ex.send) { + tls$1.queue(c, tls$1.createAlert(c, ex.alert)); + tls$1.flush(c); + } + + // error is fatal by default + var fatal = (ex.fatal !== false); + if(fatal) { + // set fail flag + c.fail = true; + } + + // call error handler first + options.error(c, ex); + + if(fatal) { + // fatal error, close connection, do not clear fail + c.close(false); + } + }, + deflate: options.deflate || null, + inflate: options.inflate || null + }; + + /** + * Resets a closed TLS connection for reuse. Called in c.close(). + * + * @param clearFail true to clear the fail flag (default: true). + */ + c.reset = function(clearFail) { + c.version = {major: tls$1.Version.major, minor: tls$1.Version.minor}; + c.record = null; + c.session = null; + c.peerCertificate = null; + c.state = { + pending: null, + current: null + }; + c.expect = (c.entity === tls$1.ConnectionEnd.client) ? SHE : CHE; + c.fragmented = null; + c.records = []; + c.open = false; + c.handshakes = 0; + c.handshaking = false; + c.isConnected = false; + c.fail = !(clearFail || typeof(clearFail) === 'undefined'); + c.input.clear(); + c.tlsData.clear(); + c.data.clear(); + c.state.current = tls$1.createConnectionState(c); + }; + + // do initial reset of connection + c.reset(); + + /** + * Updates the current TLS engine state based on the given record. + * + * @param c the TLS connection. + * @param record the TLS record to act on. + */ + var _update = function(c, record) { + // get record handler (align type in table by subtracting lowest) + var aligned = record.type - tls$1.ContentType.change_cipher_spec; + var handlers = ctTable[c.entity][c.expect]; + if(aligned in handlers) { + handlers[aligned](c, record); + } else { + // unexpected record + tls$1.handleUnexpected(c, record); + } + }; + + /** + * Reads the record header and initializes the next record on the given + * connection. + * + * @param c the TLS connection with the next record. + * + * @return 0 if the input data could be processed, otherwise the + * number of bytes required for data to be processed. + */ + var _readRecordHeader = function(c) { + var rval = 0; + + // get input buffer and its length + var b = c.input; + var len = b.length(); + + // need at least 5 bytes to initialize a record + if(len < 5) { + rval = 5 - len; + } else { + // enough bytes for header + // initialize record + c.record = { + type: b.getByte(), + version: { + major: b.getByte(), + minor: b.getByte() + }, + length: b.getInt16(), + fragment: forge$b.util.createBuffer(), + ready: false + }; + + // check record version + var compatibleVersion = (c.record.version.major === c.version.major); + if(compatibleVersion && c.session && c.session.version) { + // session version already set, require same minor version + compatibleVersion = (c.record.version.minor === c.version.minor); + } + if(!compatibleVersion) { + c.error(c, { + message: 'Incompatible TLS version.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: tls$1.Alert.Description.protocol_version + } + }); + } + } + + return rval; + }; + + /** + * Reads the next record's contents and appends its message to any + * previously fragmented message. + * + * @param c the TLS connection with the next record. + * + * @return 0 if the input data could be processed, otherwise the + * number of bytes required for data to be processed. + */ + var _readRecord = function(c) { + var rval = 0; + + // ensure there is enough input data to get the entire record + var b = c.input; + var len = b.length(); + if(len < c.record.length) { + // not enough data yet, return how much is required + rval = c.record.length - len; + } else { + // there is enough data to parse the pending record + // fill record fragment and compact input buffer + c.record.fragment.putBytes(b.getBytes(c.record.length)); + b.compact(); + + // update record using current read state + var s = c.state.current.read; + if(s.update(c, c.record)) { + // see if there is a previously fragmented message that the + // new record's message fragment should be appended to + if(c.fragmented !== null) { + // if the record type matches a previously fragmented + // record, append the record fragment to it + if(c.fragmented.type === c.record.type) { + // concatenate record fragments + c.fragmented.fragment.putBuffer(c.record.fragment); + c.record = c.fragmented; + } else { + // error, invalid fragmented record + c.error(c, { + message: 'Invalid fragmented record.', + send: true, + alert: { + level: tls$1.Alert.Level.fatal, + description: + tls$1.Alert.Description.unexpected_message + } + }); + } + } + + // record is now ready + c.record.ready = true; + } + } + + return rval; + }; + + /** + * Performs a handshake using the TLS Handshake Protocol, as a client. + * + * This method should only be called if the connection is in client mode. + * + * @param sessionId the session ID to use, null to start a new one. + */ + c.handshake = function(sessionId) { + // error to call this in non-client mode + if(c.entity !== tls$1.ConnectionEnd.client) { + // not fatal error + c.error(c, { + message: 'Cannot initiate handshake as a server.', + fatal: false + }); + } else if(c.handshaking) { + // handshake is already in progress, fail but not fatal error + c.error(c, { + message: 'Handshake already in progress.', + fatal: false + }); + } else { + // clear fail flag on reuse + if(c.fail && !c.open && c.handshakes === 0) { + c.fail = false; + } + + // now handshaking + c.handshaking = true; + + // default to blank (new session) + sessionId = sessionId || ''; + + // if a session ID was specified, try to find it in the cache + var session = null; + if(sessionId.length > 0) { + if(c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + } + + // matching session not found in cache, clear session ID + if(session === null) { + sessionId = ''; + } + } + + // no session given, grab a session from the cache, if available + if(sessionId.length === 0 && c.sessionCache) { + session = c.sessionCache.getSession(); + if(session !== null) { + sessionId = session.id; + } + } + + // set up session + c.session = { + id: sessionId, + version: null, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + certificateRequest: null, + clientCertificate: null, + sp: {}, + md5: forge$b.md.md5.create(), + sha1: forge$b.md.sha1.create() + }; + + // use existing session information + if(session) { + // only update version on connection, session version not yet set + c.version = session.version; + c.session.sp = session.sp; + } + + // generate new client random + c.session.sp.client_random = tls$1.createRandom().getBytes(); + + // connection now open + c.open = true; + + // send hello + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.handshake, + data: tls$1.createClientHello(c) + })); + tls$1.flush(c); + } + }; + + /** + * Called when TLS protocol data has been received from somewhere and should + * be processed by the TLS engine. + * + * @param data the TLS protocol data, as a string, to process. + * + * @return 0 if the data could be processed, otherwise the number of bytes + * required for data to be processed. + */ + c.process = function(data) { + var rval = 0; + + // buffer input data + if(data) { + c.input.putBytes(data); + } + + // process next record if no failure, process will be called after + // each record is handled (since handling can be asynchronous) + if(!c.fail) { + // reset record if ready and now empty + if(c.record !== null && + c.record.ready && c.record.fragment.isEmpty()) { + c.record = null; + } + + // if there is no pending record, try to read record header + if(c.record === null) { + rval = _readRecordHeader(c); + } + + // read the next record (if record not yet ready) + if(!c.fail && c.record !== null && !c.record.ready) { + rval = _readRecord(c); + } + + // record ready to be handled, update engine state + if(!c.fail && c.record !== null && c.record.ready) { + _update(c, c.record); + } + } + + return rval; + }; + + /** + * Requests that application data be packaged into a TLS record. The + * tlsDataReady handler will be called when the TLS record(s) have been + * prepared. + * + * @param data the application data, as a raw 'binary' encoded string, to + * be sent; to send utf-16/utf-8 string data, use the return value + * of util.encodeUtf8(str). + * + * @return true on success, false on failure. + */ + c.prepare = function(data) { + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.application_data, + data: forge$b.util.createBuffer(data) + })); + return tls$1.flush(c); + }; + + /** + * Requests that a heartbeat request be packaged into a TLS record for + * transmission. The tlsDataReady handler will be called when TLS record(s) + * have been prepared. + * + * When a heartbeat response has been received, the heartbeatReceived + * handler will be called with the matching payload. This handler can + * be used to clear a retransmission timer, etc. + * + * @param payload the heartbeat data to send as the payload in the message. + * @param [payloadLength] the payload length to use, defaults to the + * actual payload length. + * + * @return true on success, false on failure. + */ + c.prepareHeartbeatRequest = function(payload, payloadLength) { + if(payload instanceof forge$b.util.ByteBuffer) { + payload = payload.bytes(); + } + if(typeof payloadLength === 'undefined') { + payloadLength = payload.length; + } + c.expectedHeartbeatPayload = payload; + tls$1.queue(c, tls$1.createRecord(c, { + type: tls$1.ContentType.heartbeat, + data: tls$1.createHeartbeat( + tls$1.HeartbeatMessageType.heartbeat_request, payload, payloadLength) + })); + return tls$1.flush(c); + }; + + /** + * Closes the connection (sends a close_notify alert). + * + * @param clearFail true to clear the fail flag (default: true). + */ + c.close = function(clearFail) { + // save session if connection didn't fail + if(!c.fail && c.sessionCache && c.session) { + // only need to preserve session ID, version, and security params + var session = { + id: c.session.id, + version: c.session.version, + sp: c.session.sp + }; + session.sp.keys = null; + c.sessionCache.setSession(session.id, session); + } + + if(c.open) { + // connection no longer open, clear input + c.open = false; + c.input.clear(); + + // if connected or handshaking, send an alert + if(c.isConnected || c.handshaking) { + c.isConnected = c.handshaking = false; + + // send close_notify alert + tls$1.queue(c, tls$1.createAlert(c, { + level: tls$1.Alert.Level.warning, + description: tls$1.Alert.Description.close_notify + })); + tls$1.flush(c); + } + + // call handler + c.closed(c); + } + + // reset TLS connection, do not clear fail flag + c.reset(clearFail); + }; + + return c; +}; + +/* TLS API */ +forge$b.tls = forge$b.tls || {}; + +// expose non-functions +for(var key in tls$1) { + if(typeof tls$1[key] !== 'function') { + forge$b.tls[key] = tls$1[key]; + } +} + +// expose prf_tls1 for testing +forge$b.tls.prf_tls1 = prf_TLS1; + +// expose sha1 hmac method +forge$b.tls.hmac_sha1 = hmac_sha1; + +// expose session cache creation +forge$b.tls.createSessionCache = tls$1.createSessionCache; + +/** + * Creates a new TLS connection. This does not make any assumptions about the + * transport layer that TLS is working on top of, ie: it does not assume there + * is a TCP/IP connection or establish one. A TLS connection is totally + * abstracted away from the layer is runs on top of, it merely establishes a + * secure channel between a client" and a "server". + * + * A TLS connection contains 4 connection states: pending read and write, and + * current read and write. + * + * At initialization, the current read and write states will be null. Only once + * the security parameters have been set and the keys have been generated can + * the pending states be converted into current states. Current states will be + * updated for each record processed. + * + * A custom certificate verify callback may be provided to check information + * like the common name on the server's certificate. It will be called for + * every certificate in the chain. It has the following signature: + * + * variable func(c, certs, index, preVerify) + * Where: + * c The TLS connection + * verified Set to true if certificate was verified, otherwise the alert + * tls.Alert.Description for why the certificate failed. + * depth The current index in the chain, where 0 is the server's cert. + * certs The certificate chain, *NOTE* if the server was anonymous then + * the chain will be empty. + * + * The function returns true on success and on failure either the appropriate + * tls.Alert.Description or an object with 'alert' set to the appropriate + * tls.Alert.Description and 'message' set to a custom error message. If true + * is not returned then the connection will abort using, in order of + * availability, first the returned alert description, second the preVerify + * alert description, and lastly the default 'bad_certificate'. + * + * There are three callbacks that can be used to make use of client-side + * certificates where each takes the TLS connection as the first parameter: + * + * getCertificate(conn, hint) + * The second parameter is a hint as to which certificate should be + * returned. If the connection entity is a client, then the hint will be + * the CertificateRequest message from the server that is part of the + * TLS protocol. If the connection entity is a server, then it will be + * the servername list provided via an SNI extension the ClientHello, if + * one was provided (empty array if not). The hint can be examined to + * determine which certificate to use (advanced). Most implementations + * will just return a certificate. The return value must be a + * PEM-formatted certificate or an array of PEM-formatted certificates + * that constitute a certificate chain, with the first in the array/chain + * being the client's certificate. + * getPrivateKey(conn, certificate) + * The second parameter is an forge.pki X.509 certificate object that + * is associated with the requested private key. The return value must + * be a PEM-formatted private key. + * getSignature(conn, bytes, callback) + * This callback can be used instead of getPrivateKey if the private key + * is not directly accessible in javascript or should not be. For + * instance, a secure external web service could provide the signature + * in exchange for appropriate credentials. The second parameter is a + * string of bytes to be signed that are part of the TLS protocol. These + * bytes are used to verify that the private key for the previously + * provided client-side certificate is accessible to the client. The + * callback is a function that takes 2 parameters, the TLS connection + * and the RSA encrypted (signed) bytes as a string. This callback must + * be called once the signature is ready. + * + * @param options the options for this connection: + * server: true if the connection is server-side, false for client. + * sessionId: a session ID to reuse, null for a new connection. + * caStore: an array of certificates to trust. + * sessionCache: a session cache to use. + * cipherSuites: an optional array of cipher suites to use, + * see tls.CipherSuites. + * connected: function(conn) called when the first handshake completes. + * virtualHost: the virtual server name to use in a TLS SNI extension. + * verifyClient: true to require a client certificate in server mode, + * 'optional' to request one, false not to (default: false). + * verify: a handler used to custom verify certificates in the chain. + * verifyOptions: an object with options for the certificate chain validation. + * See documentation of pki.verifyCertificateChain for possible options. + * verifyOptions.verify is ignored. If you wish to specify a verify handler + * use the verify key. + * getCertificate: an optional callback used to get a certificate or + * a chain of certificates (as an array). + * getPrivateKey: an optional callback used to get a private key. + * getSignature: an optional callback used to get a signature. + * tlsDataReady: function(conn) called when TLS protocol data has been + * prepared and is ready to be used (typically sent over a socket + * connection to its destination), read from conn.tlsData buffer. + * dataReady: function(conn) called when application data has + * been parsed from a TLS record and should be consumed by the + * application, read from conn.data buffer. + * closed: function(conn) called when the connection has been closed. + * error: function(conn, error) called when there was an error. + * deflate: function(inBytes) if provided, will deflate TLS records using + * the deflate algorithm if the server supports it. + * inflate: function(inBytes) if provided, will inflate TLS records using + * the deflate algorithm if the server supports it. + * + * @return the new TLS connection. + */ +forge$b.tls.createConnection = tls$1.createConnection; + +/** + * A Javascript implementation of AES Cipher Suites for TLS. + * + * @author Dave Longley + * + * Copyright (c) 2009-2015 Digital Bazaar, Inc. + * + */ + +var forge$a = forge$F; + + + +var tls = forge$a.tls; + +/** + * Supported cipher suites. + */ +tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = { + id: [0x00, 0x2f], + name: 'TLS_RSA_WITH_AES_128_CBC_SHA', + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 16; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState: initConnectionState +}; +tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = { + id: [0x00, 0x35], + name: 'TLS_RSA_WITH_AES_256_CBC_SHA', + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 32; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState: initConnectionState +}; + +function initConnectionState(state, c, sp) { + var client = (c.entity === forge$a.tls.ConnectionEnd.client); + + // cipher setup + state.read.cipherState = { + init: false, + cipher: forge$a.cipher.createDecipher('AES-CBC', client ? + sp.keys.server_write_key : sp.keys.client_write_key), + iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV + }; + state.write.cipherState = { + init: false, + cipher: forge$a.cipher.createCipher('AES-CBC', client ? + sp.keys.client_write_key : sp.keys.server_write_key), + iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV + }; + state.read.cipherFunction = decrypt_aes_cbc_sha1; + state.write.cipherFunction = encrypt_aes_cbc_sha1; + + // MAC setup + state.read.macLength = state.write.macLength = sp.mac_length; + state.read.macFunction = state.write.macFunction = tls.hmac_sha1; +} + +/** + * Encrypts the TLSCompressed record into a TLSCipherText record using AES + * in CBC mode. + * + * @param record the TLSCompressed record to encrypt. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +function encrypt_aes_cbc_sha1(record, s) { + var rval = false; + + // append MAC to fragment, update sequence number + var mac = s.macFunction(s.macKey, s.sequenceNumber, record); + record.fragment.putBytes(mac); + s.updateSequenceNumber(); + + // TLS 1.1+ use an explicit IV every time to protect against CBC attacks + var iv; + if(record.version.minor === tls.Versions.TLS_1_0.minor) { + // use the pre-generated IV when initializing for TLS 1.0, otherwise use + // the residue from the previous encryption + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + iv = forge$a.random.getBytesSync(16); + } + + s.cipherState.init = true; + + // start cipher + var cipher = s.cipherState.cipher; + cipher.start({iv: iv}); + + // TLS 1.1+ write IV into output + if(record.version.minor >= tls.Versions.TLS_1_1.minor) { + cipher.output.putBytes(iv); + } + + // do encryption (default padding is appropriate) + cipher.update(record.fragment); + if(cipher.finish(encrypt_aes_cbc_sha1_padding)) { + // set record fragment to encrypted output + record.fragment = cipher.output; + record.length = record.fragment.length(); + rval = true; + } + + return rval; +} + +/** + * Handles padding for aes_cbc_sha1 in encrypt mode. + * + * @param blockSize the block size. + * @param input the input buffer. + * @param decrypt true in decrypt mode, false in encrypt mode. + * + * @return true on success, false on failure. + */ +function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { + /* The encrypted data length (TLSCiphertext.length) is one more than the sum + of SecurityParameters.block_length, TLSCompressed.length, + SecurityParameters.mac_length, and padding_length. + + The padding may be any length up to 255 bytes long, as long as it results in + the TLSCiphertext.length being an integral multiple of the block length. + Lengths longer than necessary might be desirable to frustrate attacks on a + protocol based on analysis of the lengths of exchanged messages. Each uint8 + in the padding data vector must be filled with the padding length value. + + The padding length should be such that the total size of the + GenericBlockCipher structure is a multiple of the cipher's block length. + Legal values range from zero to 255, inclusive. This length specifies the + length of the padding field exclusive of the padding_length field itself. + + This is slightly different from PKCS#7 because the padding value is 1 + less than the actual number of padding bytes if you include the + padding_length uint8 itself as a padding byte. */ + if(!decrypt) { + // get the number of padding bytes required to reach the blockSize and + // subtract 1 for the padding value (to make room for the padding_length + // uint8) + var padding = blockSize - (input.length() % blockSize); + input.fillWithByte(padding - 1, padding); + } + return true; +} + +/** + * Handles padding for aes_cbc_sha1 in decrypt mode. + * + * @param blockSize the block size. + * @param output the output buffer. + * @param decrypt true in decrypt mode, false in encrypt mode. + * + * @return true on success, false on failure. + */ +function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { + var rval = true; + if(decrypt) { + /* The last byte in the output specifies the number of padding bytes not + including itself. Each of the padding bytes has the same value as that + last byte (known as the padding_length). Here we check all padding + bytes to ensure they have the value of padding_length even if one of + them is bad in order to ward-off timing attacks. */ + var len = output.length(); + var paddingLength = output.last(); + for(var i = len - 1 - paddingLength; i < len - 1; ++i) { + rval = rval && (output.at(i) == paddingLength); + } + if(rval) { + // trim off padding bytes and last padding length byte + output.truncate(paddingLength + 1); + } + } + return rval; +} + +/** + * Decrypts a TLSCipherText record into a TLSCompressed record using + * AES in CBC mode. + * + * @param record the TLSCipherText record to decrypt. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +function decrypt_aes_cbc_sha1(record, s) { + var rval = false; + + var iv; + if(record.version.minor === tls.Versions.TLS_1_0.minor) { + // use pre-generated IV when initializing for TLS 1.0, otherwise use the + // residue from the previous decryption + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + // TLS 1.1+ use an explicit IV every time to protect against CBC attacks + // that is appended to the record fragment + iv = record.fragment.getBytes(16); + } + + s.cipherState.init = true; + + // start cipher + var cipher = s.cipherState.cipher; + cipher.start({iv: iv}); + + // do decryption + cipher.update(record.fragment); + rval = cipher.finish(decrypt_aes_cbc_sha1_padding); + + // even if decryption fails, keep going to minimize timing attacks + + // decrypted data: + // first (len - 20) bytes = application data + // last 20 bytes = MAC + var macLen = s.macLength; + + // create a random MAC to check against should the mac length check fail + // Note: do this regardless of the failure to keep timing consistent + var mac = forge$a.random.getBytesSync(macLen); + + // get fragment and mac + var len = cipher.output.length(); + if(len >= macLen) { + record.fragment = cipher.output.getBytes(len - macLen); + mac = cipher.output.getBytes(macLen); + } else { + // bad data, but get bytes anyway to try to keep timing consistent + record.fragment = cipher.output.getBytes(); + } + record.fragment = forge$a.util.createBuffer(record.fragment); + record.length = record.fragment.length(); + + // see if data integrity checks out, update sequence number + var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); + s.updateSequenceNumber(); + rval = compareMacs(s.macKey, mac, mac2) && rval; + return rval; +} + +/** + * Safely compare two MACs. This function will compare two MACs in a way + * that protects against timing attacks. + * + * TODO: Expose elsewhere as a utility API. + * + * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/ + * + * @param key the MAC key to use. + * @param mac1 as a binary-encoded string of bytes. + * @param mac2 as a binary-encoded string of bytes. + * + * @return true if the MACs are the same, false if not. + */ +function compareMacs(key, mac1, mac2) { + var hmac = forge$a.hmac.create(); + + hmac.start('SHA1', key); + hmac.update(mac1); + mac1 = hmac.digest().getBytes(); + + hmac.start(null, null); + hmac.update(mac2); + mac2 = hmac.digest().getBytes(); + + return mac1 === mac2; +} + +/** + * Debugging support for web applications. + * + * @author David I. Lehn + * + * Copyright 2008-2013 Digital Bazaar, Inc. + */ + +var forge$9 = forge$F; + +/* DEBUG API */ +forge$9.debug = forge$9.debug || {}; + +// Private storage for debugging. +// Useful to expose data that is otherwise unviewable behind closures. +// NOTE: remember that this can hold references to data and cause leaks! +// format is "forge._debug.. = data" +// Example: +// (function() { +// var cat = 'forge.test.Test'; // debugging category +// var sState = {...}; // local state +// forge.debug.set(cat, 'sState', sState); +// })(); +forge$9.debug.storage = {}; + +/** + * Gets debug data. Omit name for all cat data Omit name and cat for + * all data. + * + * @param cat name of debugging category. + * @param name name of data to get (optional). + * @return object with requested debug data or undefined. + */ +forge$9.debug.get = function(cat, name) { + var rval; + if(typeof(cat) === 'undefined') { + rval = forge$9.debug.storage; + } else if(cat in forge$9.debug.storage) { + if(typeof(name) === 'undefined') { + rval = forge$9.debug.storage[cat]; + } else { + rval = forge$9.debug.storage[cat][name]; + } + } + return rval; +}; + +/** + * Sets debug data. + * + * @param cat name of debugging category. + * @param name name of data to set. + * @param data data to set. + */ +forge$9.debug.set = function(cat, name, data) { + if(!(cat in forge$9.debug.storage)) { + forge$9.debug.storage[cat] = {}; + } + forge$9.debug.storage[cat][name] = data; +}; + +/** + * Clears debug data. Omit name for all cat data. Omit name and cat for + * all data. + * + * @param cat name of debugging category. + * @param name name of data to clear or omit to clear entire category. + */ +forge$9.debug.clear = function(cat, name) { + if(typeof(cat) === 'undefined') { + forge$9.debug.storage = {}; + } else if(cat in forge$9.debug.storage) { + if(typeof(name) === 'undefined') { + delete forge$9.debug.storage[cat]; + } else { + delete forge$9.debug.storage[cat][name]; + } + } +}; + +/** + * Secure Hash Algorithm with a 1024-bit block size implementation. + * + * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For + * SHA-256 (block size 512 bits), see sha256.js. + * + * See FIPS 180-4 for details. + * + * @author Dave Longley + * + * Copyright (c) 2014-2015 Digital Bazaar, Inc. + */ + +var forge$8 = forge$F; + + + +var sha512$1 = forge$8.sha512 = forge$8.sha512 || {}; + +// SHA-512 +forge$8.md.sha512 = forge$8.md.algorithms.sha512 = sha512$1; + +// SHA-384 +var sha384 = forge$8.sha384 = forge$8.sha512.sha384 = forge$8.sha512.sha384 || {}; +sha384.create = function() { + return sha512$1.create('SHA-384'); +}; +forge$8.md.sha384 = forge$8.md.algorithms.sha384 = sha384; + +// SHA-512/256 +forge$8.sha512.sha256 = forge$8.sha512.sha256 || { + create: function() { + return sha512$1.create('SHA-512/256'); + } +}; +forge$8.md['sha512/256'] = forge$8.md.algorithms['sha512/256'] = + forge$8.sha512.sha256; + +// SHA-512/224 +forge$8.sha512.sha224 = forge$8.sha512.sha224 || { + create: function() { + return sha512$1.create('SHA-512/224'); + } +}; +forge$8.md['sha512/224'] = forge$8.md.algorithms['sha512/224'] = + forge$8.sha512.sha224; + +/** + * Creates a SHA-2 message digest object. + * + * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224, + * SHA-512/256). + * + * @return a message digest object. + */ +sha512$1.create = function(algorithm) { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + if(typeof algorithm === 'undefined') { + algorithm = 'SHA-512'; + } + + if(!(algorithm in _states)) { + throw new Error('Invalid SHA-512 algorithm: ' + algorithm); + } + + // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints) + var _state = _states[algorithm]; + var _h = null; + + // input buffer + var _input = forge$8.util.createBuffer(); + + // used for 64-bit word storage + var _w = new Array(80); + for(var wi = 0; wi < 80; ++wi) { + _w[wi] = new Array(2); + } + + // determine digest length by algorithm name (default) + var digestLength = 64; + switch(algorithm) { + case 'SHA-384': + digestLength = 48; + break; + case 'SHA-512/256': + digestLength = 32; + break; + case 'SHA-512/224': + digestLength = 28; + break; + } + + // message digest object + var md = { + // SHA-512 => sha512 + algorithm: algorithm.replace('-', '').toLowerCase(), + blockLength: 128, + digestLength: digestLength, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 16 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength128 for backwards-compatibility) + md.fullMessageLength = md.messageLength128 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge$8.util.createBuffer(); + _h = new Array(_state.length); + for(var i = 0; i < _state.length; ++i) { + _h[i] = _state[i].slice(0); + } + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge$8.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_h, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-512 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 896 mod 1024. In other words, + the data to be digested must be a multiple of 1024 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 16 bytes (128 + bits), that means that the last segment of the data must have 112 bytes + (896 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 896 mod 1024 because + 1024 - 128 = 896. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 896 mod 1024, then 1024 padding bits must be added. */ + + var finalBlock = forge$8.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var h = new Array(_h.length); + for(var i = 0; i < _h.length; ++i) { + h[i] = _h[i].slice(0); + } + _update(h, _w, finalBlock); + var rval = forge$8.util.createBuffer(); + var hlen; + if(algorithm === 'SHA-512') { + hlen = h.length; + } else if(algorithm === 'SHA-384') { + hlen = h.length - 2; + } else { + hlen = h.length - 4; + } + for(var i = 0; i < hlen; ++i) { + rval.putInt32(h[i][0]); + if(i !== hlen - 1 || algorithm !== 'SHA-512/224') { + rval.putInt32(h[i][1]); + } + } + return rval; + }; + + return md; +}; + +// sha-512 padding bytes not initialized yet +var _padding = null; +var _initialized = false; + +// table of constants +var _k = null; + +// initial hash states +var _states = null; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge$8.util.fillString(String.fromCharCode(0x00), 128); + + // create K table for SHA-512 + _k = [ + [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd], + [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc], + [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019], + [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118], + [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe], + [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2], + [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1], + [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694], + [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3], + [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65], + [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483], + [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5], + [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210], + [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4], + [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725], + [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70], + [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926], + [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df], + [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8], + [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b], + [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001], + [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30], + [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910], + [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8], + [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53], + [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8], + [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb], + [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3], + [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60], + [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec], + [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9], + [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b], + [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207], + [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178], + [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6], + [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b], + [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493], + [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c], + [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a], + [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817] + ]; + + // initial hash states + _states = {}; + _states['SHA-512'] = [ + [0x6a09e667, 0xf3bcc908], + [0xbb67ae85, 0x84caa73b], + [0x3c6ef372, 0xfe94f82b], + [0xa54ff53a, 0x5f1d36f1], + [0x510e527f, 0xade682d1], + [0x9b05688c, 0x2b3e6c1f], + [0x1f83d9ab, 0xfb41bd6b], + [0x5be0cd19, 0x137e2179] + ]; + _states['SHA-384'] = [ + [0xcbbb9d5d, 0xc1059ed8], + [0x629a292a, 0x367cd507], + [0x9159015a, 0x3070dd17], + [0x152fecd8, 0xf70e5939], + [0x67332667, 0xffc00b31], + [0x8eb44a87, 0x68581511], + [0xdb0c2e0d, 0x64f98fa7], + [0x47b5481d, 0xbefa4fa4] + ]; + _states['SHA-512/256'] = [ + [0x22312194, 0xFC2BF72C], + [0x9F555FA3, 0xC84C64C2], + [0x2393B86B, 0x6F53B151], + [0x96387719, 0x5940EABD], + [0x96283EE2, 0xA88EFFE3], + [0xBE5E1E25, 0x53863992], + [0x2B0199FC, 0x2C85B8AA], + [0x0EB72DDC, 0x81C52CA2] + ]; + _states['SHA-512/224'] = [ + [0x8C3D37C8, 0x19544DA2], + [0x73E19966, 0x89DCD4D6], + [0x1DFAB7AE, 0x32FF9C82], + [0x679DD514, 0x582F9FCF], + [0x0F6D2B69, 0x7BD44DA8], + [0x77E36F73, 0x04C48942], + [0x3F9D85A8, 0x6A1D36C8], + [0x1112E6AD, 0x91D692A1] + ]; + + // now initialized + _initialized = true; +} + +/** + * Updates a SHA-512 state with the given byte buffer. + * + * @param s the SHA-512 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (128 byte) chunks + var t1_hi, t1_lo; + var t2_hi, t2_lo; + var s0_hi, s0_lo; + var s1_hi, s1_lo; + var ch_hi, ch_lo; + var maj_hi, maj_lo; + var a_hi, a_lo; + var b_hi, b_lo; + var c_hi, c_lo; + var d_hi, d_lo; + var e_hi, e_lo; + var f_hi, f_lo; + var g_hi, g_lo; + var h_hi, h_lo; + var i, hi, lo, w2, w7, w15, w16; + var len = bytes.length(); + while(len >= 128) { + // the w array will be populated with sixteen 64-bit big-endian words + // and then extended into 64 64-bit words according to SHA-512 + for(i = 0; i < 16; ++i) { + w[i][0] = bytes.getInt32() >>> 0; + w[i][1] = bytes.getInt32() >>> 0; + } + for(; i < 80; ++i) { + // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x) + w2 = w[i - 2]; + hi = w2[0]; + lo = w2[1]; + + // high bits + t1_hi = ( + ((hi >>> 19) | (lo << 13)) ^ // ROTR 19 + ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29) + (hi >>> 6)) >>> 0; // SHR 6 + // low bits + t1_lo = ( + ((hi << 13) | (lo >>> 19)) ^ // ROTR 19 + ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29) + ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6 + + // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x) + w15 = w[i - 15]; + hi = w15[0]; + lo = w15[1]; + + // high bits + t2_hi = ( + ((hi >>> 1) | (lo << 31)) ^ // ROTR 1 + ((hi >>> 8) | (lo << 24)) ^ // ROTR 8 + (hi >>> 7)) >>> 0; // SHR 7 + // low bits + t2_lo = ( + ((hi << 31) | (lo >>> 1)) ^ // ROTR 1 + ((hi << 24) | (lo >>> 8)) ^ // ROTR 8 + ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7 + + // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow) + w7 = w[i - 7]; + w16 = w[i - 16]; + lo = (t1_lo + w7[1] + t2_lo + w16[1]); + w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] + + ((lo / 0x100000000) >>> 0)) >>> 0; + w[i][1] = lo >>> 0; + } + + // initialize hash value for this chunk + a_hi = s[0][0]; + a_lo = s[0][1]; + b_hi = s[1][0]; + b_lo = s[1][1]; + c_hi = s[2][0]; + c_lo = s[2][1]; + d_hi = s[3][0]; + d_lo = s[3][1]; + e_hi = s[4][0]; + e_lo = s[4][1]; + f_hi = s[5][0]; + f_lo = s[5][1]; + g_hi = s[6][0]; + g_lo = s[6][1]; + h_hi = s[7][0]; + h_lo = s[7][1]; + + // round function + for(i = 0; i < 80; ++i) { + // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e) + s1_hi = ( + ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14 + ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18 + ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9) + s1_lo = ( + ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14 + ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18 + ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9) + + // Ch(e, f, g) (optimized the same way as SHA-1) + ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0; + ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0; + + // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a) + s0_hi = ( + ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28 + ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2) + ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7) + s0_lo = ( + ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28 + ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2) + ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7) + + // Maj(a, b, c) (optimized the same way as SHA-1) + maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0; + maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0; + + // main algorithm + // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow) + lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]); + t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + + ((lo / 0x100000000) >>> 0)) >>> 0; + t1_lo = lo >>> 0; + + // t2 = s0 + maj modulo 2^64 (carry lo overflow) + lo = s0_lo + maj_lo; + t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + t2_lo = lo >>> 0; + + h_hi = g_hi; + h_lo = g_lo; + + g_hi = f_hi; + g_lo = f_lo; + + f_hi = e_hi; + f_lo = e_lo; + + // e = (d + t1) modulo 2^64 (carry lo overflow) + lo = d_lo + t1_lo; + e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + e_lo = lo >>> 0; + + d_hi = c_hi; + d_lo = c_lo; + + c_hi = b_hi; + c_lo = b_lo; + + b_hi = a_hi; + b_lo = a_lo; + + // a = (t1 + t2) modulo 2^64 (carry lo overflow) + lo = t1_lo + t2_lo; + a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + a_lo = lo >>> 0; + } + + // update hash state (additional modulo 2^64) + lo = s[0][1] + a_lo; + s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[0][1] = lo >>> 0; + + lo = s[1][1] + b_lo; + s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[1][1] = lo >>> 0; + + lo = s[2][1] + c_lo; + s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[2][1] = lo >>> 0; + + lo = s[3][1] + d_lo; + s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[3][1] = lo >>> 0; + + lo = s[4][1] + e_lo; + s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[4][1] = lo >>> 0; + + lo = s[5][1] + f_lo; + s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[5][1] = lo >>> 0; + + lo = s[6][1] + g_lo; + s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[6][1] = lo >>> 0; + + lo = s[7][1] + h_lo; + s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[7][1] = lo >>> 0; + + len -= 128; + } +} + +var asn1Validator$1 = {}; + +/** + * Copyright (c) 2019 Digital Bazaar, Inc. + */ + +var forge$7 = forge$F; + +var asn1$1 = forge$7.asn1; + +asn1Validator$1.privateKeyValidator = { + // PrivateKeyInfo + name: 'PrivateKeyInfo', + tagClass: asn1$1.Class.UNIVERSAL, + type: asn1$1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'PrivateKeyInfo.version', + tagClass: asn1$1.Class.UNIVERSAL, + type: asn1$1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // privateKeyAlgorithm + name: 'PrivateKeyInfo.privateKeyAlgorithm', + tagClass: asn1$1.Class.UNIVERSAL, + type: asn1$1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1$1.Class.UNIVERSAL, + type: asn1$1.Type.OID, + constructed: false, + capture: 'privateKeyOid' + }] + }, { + // PrivateKey + name: 'PrivateKeyInfo', + tagClass: asn1$1.Class.UNIVERSAL, + type: asn1$1.Type.OCTETSTRING, + constructed: false, + capture: 'privateKey' + }] +}; + +asn1Validator$1.publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1$1.Class.UNIVERSAL, + type: asn1$1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [{ + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1$1.Class.UNIVERSAL, + type: asn1$1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1$1.Class.UNIVERSAL, + type: asn1$1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + }] + }, + // capture group for ed25519PublicKey + { + tagClass: asn1$1.Class.UNIVERSAL, + type: asn1$1.Type.BITSTRING, + constructed: false, + composed: true, + captureBitStringValue: 'ed25519PublicKey' + } + // FIXME: this is capture group for rsaPublicKey, use it in this API or + // discard? + /* { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + } */ + ] +}; + +/** + * JavaScript implementation of Ed25519. + * + * Copyright (c) 2017-2019 Digital Bazaar, Inc. + * + * This implementation is based on the most excellent TweetNaCl which is + * in the public domain. Many thanks to its contributors: + * + * https://github.com/dchest/tweetnacl-js + */ + +var forge$6 = forge$F; + + + + +var asn1Validator = asn1Validator$1; +var publicKeyValidator = asn1Validator.publicKeyValidator; +var privateKeyValidator = asn1Validator.privateKeyValidator; + +var ByteBuffer = forge$6.util.ByteBuffer; +var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer; + +/* + * Ed25519 algorithms, see RFC 8032: + * https://tools.ietf.org/html/rfc8032 + */ +forge$6.pki = forge$6.pki || {}; +forge$6.pki.ed25519 = forge$6.ed25519 = forge$6.ed25519 || {}; +var ed25519 = forge$6.ed25519; + +ed25519.constants = {}; +ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; +ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; +ed25519.constants.SEED_BYTE_LENGTH = 32; +ed25519.constants.SIGN_BYTE_LENGTH = 64; +ed25519.constants.HASH_BYTE_LENGTH = 64; + +ed25519.generateKeyPair = function(options) { + options = options || {}; + var seed = options.seed; + if(seed === undefined) { + // generate seed + seed = forge$6.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); + } else if(typeof seed === 'string') { + if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { + throw new TypeError( + '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + + ' bytes in length.'); + } + } else if(!(seed instanceof Uint8Array)) { + throw new TypeError( + '"seed" must be a node.js Buffer, Uint8Array, or a binary string.'); + } + + seed = messageToNativeBuffer({message: seed, encoding: 'binary'}); + + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + for(var i = 0; i < 32; ++i) { + sk[i] = seed[i]; + } + crypto_sign_keypair(pk, sk); + return {publicKey: pk, privateKey: sk}; +}; + +/** + * Converts a private key from a RFC8410 ASN.1 encoding. + * + * @param obj - The asn1 representation of a private key. + * + * @returns {Object} keyInfo - The key information. + * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes. + */ +ed25519.privateKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + var valid = forge$6.asn1.validate(obj, privateKeyValidator, capture, errors); + if(!valid) { + var error = new Error('Invalid Key.'); + error.errors = errors; + throw error; + } + var oid = forge$6.asn1.derToOid(capture.privateKeyOid); + var ed25519Oid = forge$6.oids.EdDSA25519; + if(oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + + ed25519Oid + '".'); + } + var privateKey = capture.privateKey; + // manually extract the private key bytes from nested octet string, see FIXME: + // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542 + var privateKeyBytes = messageToNativeBuffer({ + message: forge$6.asn1.fromDer(privateKey).value, + encoding: 'binary' + }); + // TODO: RFC8410 specifies a format for encoding the public key bytes along + // with the private key bytes. `publicKeyBytes` can be returned in the + // future. https://tools.ietf.org/html/rfc8410#section-10.3 + return {privateKeyBytes: privateKeyBytes}; +}; + +/** + * Converts a public key from a RFC8410 ASN.1 encoding. + * + * @param obj - The asn1 representation of a public key. + * + * @return {Buffer|Uint8Array} - 32 public key bytes. + */ +ed25519.publicKeyFromAsn1 = function(obj) { + // get SubjectPublicKeyInfo + var capture = {}; + var errors = []; + var valid = forge$6.asn1.validate(obj, publicKeyValidator, capture, errors); + if(!valid) { + var error = new Error('Invalid Key.'); + error.errors = errors; + throw error; + } + var oid = forge$6.asn1.derToOid(capture.publicKeyOid); + var ed25519Oid = forge$6.oids.EdDSA25519; + if(oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + + ed25519Oid + '".'); + } + var publicKeyBytes = capture.ed25519PublicKey; + if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new Error('Key length is invalid.'); + } + return messageToNativeBuffer({ + message: publicKeyBytes, + encoding: 'binary' + }); +}; + +ed25519.publicKeyFromPrivateKey = function(options) { + options = options || {}; + var privateKey = messageToNativeBuffer({ + message: options.privateKey, encoding: 'binary' + }); + if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + } + + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + for(var i = 0; i < pk.length; ++i) { + pk[i] = privateKey[32 + i]; + } + return pk; +}; + +ed25519.sign = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + var privateKey = messageToNativeBuffer({ + message: options.privateKey, + encoding: 'binary' + }); + if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { + var keyPair = ed25519.generateKeyPair({seed: privateKey}); + privateKey = keyPair.privateKey; + } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + + ed25519.constants.SEED_BYTE_LENGTH + ' or ' + + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + } + + var signedMsg = new NativeBuffer( + ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + crypto_sign(signedMsg, msg, msg.length, privateKey); + + var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); + for(var i = 0; i < sig.length; ++i) { + sig[i] = signedMsg[i]; + } + return sig; +}; + +ed25519.verify = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + if(options.signature === undefined) { + throw new TypeError( + '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' + + 'ByteBuffer, or a binary string.'); + } + var sig = messageToNativeBuffer({ + message: options.signature, + encoding: 'binary' + }); + if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { + throw new TypeError( + '"options.signature" must have a byte length of ' + + ed25519.constants.SIGN_BYTE_LENGTH); + } + var publicKey = messageToNativeBuffer({ + message: options.publicKey, + encoding: 'binary' + }); + if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.publicKey" must have a byte length of ' + + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + } + + var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var i; + for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { + sm[i] = sig[i]; + } + for(i = 0; i < msg.length; ++i) { + sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; + } + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +function messageToNativeBuffer(options) { + var message = options.message; + if(message instanceof Uint8Array || message instanceof NativeBuffer) { + return message; + } + + var encoding = options.encoding; + if(message === undefined) { + if(options.md) { + // TODO: more rigorous validation that `md` is a MessageDigest + message = options.md.digest().getBytes(); + encoding = 'binary'; + } else { + throw new TypeError('"options.message" or "options.md" not specified.'); + } + } + + if(typeof message === 'string' && !encoding) { + throw new TypeError('"options.encoding" must be "binary" or "utf8".'); + } + + if(typeof message === 'string') { + if(typeof Buffer !== 'undefined') { + return Buffer.from(message, encoding); + } + message = new ByteBuffer(message, encoding); + } else if(!(message instanceof ByteBuffer)) { + throw new TypeError( + '"options.message" must be a node.js Buffer, a Uint8Array, a forge ' + + 'ByteBuffer, or a string with "options.encoding" specifying its ' + + 'encoding.'); + } + + // convert to native buffer + var buffer = new NativeBuffer(message.length()); + for(var i = 0; i < buffer.length; ++i) { + buffer[i] = message.at(i); + } + return buffer; +} + +var gf0 = gf(); +var gf1 = gf([1]); +var D = gf([ + 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, + 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]); +var D2 = gf([ + 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, + 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]); +var X = gf([ + 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, + 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]); +var Y = gf([ + 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, + 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]); +var L = new Float64Array([ + 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, + 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); +var I = gf([ + 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, + 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`, +// whichever is available, to improve performance +function sha512(msg, msgLen) { + // Note: `out` and `msg` are NativeBuffer + var md = forge$6.md.sha512.create(); + var buffer = new ByteBuffer(msg); + md.update(buffer.getBytes(msgLen), 'binary'); + var hash = md.digest().getBytes(); + if(typeof Buffer !== 'undefined') { + return Buffer.from(hash, 'binary'); + } + var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); + for(var i = 0; i < 64; ++i) { + out[i] = hash.charCodeAt(i); + } + return out; +} + +function crypto_sign_keypair(pk, sk) { + var p = [gf(), gf(), gf(), gf()]; + var i; + + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for(i = 0; i < 32; ++i) { + sk[i + 32] = pk[i]; + } + return 0; +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for(i = 0; i < n; ++i) { + sm[64 + i] = m[i]; + } + for(i = 0; i < 32; ++i) { + sm[32 + i] = d[32 + i]; + } + + var r = sha512(sm.subarray(32), n + 32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for(i = 32; i < 64; ++i) { + sm[i] = sk[i]; + } + var h = sha512(sm, n + 64); + reduce(h); + + for(i = 32; i < 64; ++i) { + x[i] = 0; + } + for(i = 0; i < 32; ++i) { + x[i] = r[i]; + } + for(i = 0; i < 32; ++i) { + for(j = 0; j < 32; j++) { + x[i + j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new NativeBuffer(32); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + mlen = -1; + if(n < 64) { + return -1; + } + + if(unpackneg(q, pk)) { + return -1; + } + + for(i = 0; i < n; ++i) { + m[i] = sm[i]; + } + for(i = 0; i < 32; ++i) { + m[i + 32] = pk[i]; + } + var h = sha512(m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if(crypto_verify_32(sm, 0, t, 0)) { + for(i = 0; i < n; ++i) { + m[i] = 0; + } + return -1; + } + + for(i = 0; i < n; ++i) { + m[i] = sm[i + 64]; + } + mlen = n; + return mlen; +} + +function modL(r, x) { + var carry, i, j, k; + for(i = 63; i >= 32; --i) { + carry = 0; + for(j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = (x[j] + 128) >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for(j = 0; j < 32; ++j) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for(j = 0; j < 32; ++j) { + x[j] -= carry * L[j]; + } + for(i = 0; i < 32; ++i) { + x[i + 1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64); + for(var i = 0; i < 64; ++i) { + x[i] = r[i]; + r[i] = 0; + } + modL(r, x); +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + for(var i = 0; i < 4; ++i) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for(i = 0; i < 16; ++i) { + t[i] = n[i]; + } + car25519(t); + car25519(t); + car25519(t); + for(j = 0; j < 2; ++j) { + m[0] = t[0] - 0xffed; + for(i = 1; i < 15; ++i) { + m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); + b = (m[15] >> 16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1 - b); + } + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 0xff; + o[2 * i + 1] = t[i] >> 8; + } +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if(neq25519(chk, num)) { + M(r[0], r[0], I); + } + + S(chk, r[0]); + M(chk, chk, den); + if(neq25519(chk, num)) { + return -1; + } + + if(par25519(r[0]) === (p[31] >> 7)) { + Z(r[0], gf0, r[0]); + } + + M(r[3], r[0], r[1]); + return 0; +} + +function unpack25519(o, n) { + var i; + for(i = 0; i < 16; ++i) { + o[i] = n[2 * i] + (n[2 * i + 1] << 8); + } + o[15] &= 0x7fff; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for(a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for(a = 250; a >= 0; --a) { + S(c, c); + if(a !== 1) { + M(c, c, i); + } + } + for(a = 0; a < 16; ++a) { + o[a] = c[a]; + } +} + +function neq25519(a, b) { + var c = new NativeBuffer(32); + var d = new NativeBuffer(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); +} + +function vn(x, xi, y, yi, n) { + var i, d = 0; + for(i = 0; i < n; ++i) { + d |= x[xi + i] ^ y[yi + i]; + } + return (1 & ((d - 1) >>> 8)) - 1; +} + +function par25519(a) { + var d = new NativeBuffer(32); + pack25519(d, a); + return d[0] & 1; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for(i = 255; i >= 0; --i) { + b = (s[(i / 8)|0] >> (i & 7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function set25519(r, a) { + var i; + for(i = 0; i < 16; i++) { + r[i] = a[i] | 0; + } +} + +function inv25519(o, i) { + var c = gf(); + var a; + for(a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for(a = 253; a >= 0; --a) { + S(c, c); + if(a !== 2 && a !== 4) { + M(c, c, i); + } + } + for(a = 0; a < 16; ++a) { + o[a] = c[a]; + } +} + +function car25519(o) { + var i, v, c = 1; + for(i = 0; i < 16; ++i) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c - 1 + 37 * (c - 1); +} + +function sel25519(p, q, b) { + var t, c = ~(b - 1); + for(var i = 0; i < 16; ++i) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function gf(init) { + var i, r = new Float64Array(16); + if(init) { + for(i = 0; i < init.length; ++i) { + r[i] = init[i]; + } + } + return r; +} + +function A(o, a, b) { + for(var i = 0; i < 16; ++i) { + o[i] = a[i] + b[i]; + } +} + +function Z(o, a, b) { + for(var i = 0; i < 16; ++i) { + o[i] = a[i] - b[i]; + } +} + +function S(o, a) { + M(o, a, a); +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} + +/** + * Javascript implementation of RSA-KEM. + * + * @author Lautaro Cozzani Rodriguez + * @author Dave Longley + * + * Copyright (c) 2014 Lautaro Cozzani + * Copyright (c) 2014 Digital Bazaar, Inc. + */ + +var forge$5 = forge$F; + + + + +forge$5.kem = forge$5.kem || {}; + +var BigInteger = forge$5.jsbn.BigInteger; + +/** + * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2. + */ +forge$5.kem.rsa = {}; + +/** + * Creates an RSA KEM API object for generating a secret asymmetric key. + * + * The symmetric key may be generated via a call to 'encrypt', which will + * produce a ciphertext to be transmitted to the recipient and a key to be + * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which + * will produce the same secret key for the recipient to use to decrypt a + * message that was encrypted with the secret key. + * + * @param kdf the KDF API to use (eg: new forge.kem.kdf1()). + * @param options the options to use. + * [prng] a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + */ +forge$5.kem.rsa.create = function(kdf, options) { + options = options || {}; + var prng = options.prng || forge$5.random; + + var kem = {}; + + /** + * Generates a secret key and its encapsulation. + * + * @param publicKey the RSA public key to encrypt with. + * @param keyLength the length, in bytes, of the secret key to generate. + * + * @return an object with: + * encapsulation: the ciphertext for generating the secret key, as a + * binary-encoded string of bytes. + * key: the secret key to use for encrypting a message. + */ + kem.encrypt = function(publicKey, keyLength) { + // generate a random r where 1 < r < n + var byteLength = Math.ceil(publicKey.n.bitLength() / 8); + var r; + do { + r = new BigInteger( + forge$5.util.bytesToHex(prng.getBytesSync(byteLength)), + 16).mod(publicKey.n); + } while(r.compareTo(BigInteger.ONE) <= 0); + + // prepend r with zeros + r = forge$5.util.hexToBytes(r.toString(16)); + var zeros = byteLength - r.length; + if(zeros > 0) { + r = forge$5.util.fillString(String.fromCharCode(0), zeros) + r; + } + + // encrypt the random + var encapsulation = publicKey.encrypt(r, 'NONE'); + + // generate the secret key + var key = kdf.generate(r, keyLength); + + return {encapsulation: encapsulation, key: key}; + }; + + /** + * Decrypts an encapsulated secret key. + * + * @param privateKey the RSA private key to decrypt with. + * @param encapsulation the ciphertext for generating the secret key, as + * a binary-encoded string of bytes. + * @param keyLength the length, in bytes, of the secret key to generate. + * + * @return the secret key as a binary-encoded string of bytes. + */ + kem.decrypt = function(privateKey, encapsulation, keyLength) { + // decrypt the encapsulation and generate the secret key + var r = privateKey.decrypt(encapsulation, 'NONE'); + return kdf.generate(r, keyLength); + }; + + return kem; +}; + +// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API? + +/** + * Creates a key derivation API object that implements KDF1 per ISO 18033-2. + * + * @param md the hash API to use. + * @param [digestLength] an optional digest length that must be positive and + * less than or equal to md.digestLength. + * + * @return a KDF1 API object. + */ +forge$5.kem.kdf1 = function(md, digestLength) { + _createKDF(this, md, 0, digestLength || md.digestLength); +}; + +/** + * Creates a key derivation API object that implements KDF2 per ISO 18033-2. + * + * @param md the hash API to use. + * @param [digestLength] an optional digest length that must be positive and + * less than or equal to md.digestLength. + * + * @return a KDF2 API object. + */ +forge$5.kem.kdf2 = function(md, digestLength) { + _createKDF(this, md, 1, digestLength || md.digestLength); +}; + +/** + * Creates a KDF1 or KDF2 API object. + * + * @param md the hash API to use. + * @param counterStart the starting index for the counter. + * @param digestLength the digest length to use. + * + * @return the KDF API object. + */ +function _createKDF(kdf, md, counterStart, digestLength) { + /** + * Generate a key of the specified length. + * + * @param x the binary-encoded byte string to generate a key from. + * @param length the number of bytes to generate (the size of the key). + * + * @return the key as a binary-encoded string. + */ + kdf.generate = function(x, length) { + var key = new forge$5.util.ByteBuffer(); + + // run counter from counterStart to ceil(length / Hash.len) + var k = Math.ceil(length / digestLength) + counterStart; + + var c = new forge$5.util.ByteBuffer(); + for(var i = counterStart; i < k; ++i) { + // I2OSP(i, 4): convert counter to an octet string of 4 octets + c.putInt32(i); + + // digest 'x' and the counter and add the result to the key + md.start(); + md.update(x + c.getBytes()); + var hash = md.digest(); + key.putBytes(hash.getBytes(digestLength)); + } + + // truncate to the correct key length + key.truncate(key.length() - length); + return key.getBytes(); + }; +} + +/** + * Cross-browser support for logging in a web application. + * + * @author David I. Lehn + * + * Copyright (c) 2008-2013 Digital Bazaar, Inc. + */ + +var forge$4 = forge$F; + + +/* LOG API */ +forge$4.log = forge$4.log || {}; + +/** + * Application logging system. + * + * Each logger level available as it's own function of the form: + * forge.log.level(category, args...) + * The category is an arbitrary string, and the args are the same as + * Firebug's console.log API. By default the call will be output as: + * 'LEVEL [category] , args[1], ...' + * This enables proper % formatting via the first argument. + * Each category is enabled by default but can be enabled or disabled with + * the setCategoryEnabled() function. + */ +// list of known levels +forge$4.log.levels = [ + 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max']; +// info on the levels indexed by name: +// index: level index +// name: uppercased display name +var sLevelInfo = {}; +// list of loggers +var sLoggers = []; +/** + * Standard console logger. If no console support is enabled this will + * remain null. Check before using. + */ +var sConsoleLogger = null; + +// logger flags +/** + * Lock the level at the current value. Used in cases where user config may + * set the level such that only critical messages are seen but more verbose + * messages are needed for debugging or other purposes. + */ +forge$4.log.LEVEL_LOCKED = (1 << 1); +/** + * Always call log function. By default, the logging system will check the + * message level against logger.level before calling the log function. This + * flag allows the function to do its own check. + */ +forge$4.log.NO_LEVEL_CHECK = (1 << 2); +/** + * Perform message interpolation with the passed arguments. "%" style + * fields in log messages will be replaced by arguments as needed. Some + * loggers, such as Firebug, may do this automatically. The original log + * message will be available as 'message' and the interpolated version will + * be available as 'fullMessage'. + */ +forge$4.log.INTERPOLATE = (1 << 3); + +// setup each log level +for(var i = 0; i < forge$4.log.levels.length; ++i) { + var level = forge$4.log.levels[i]; + sLevelInfo[level] = { + index: i, + name: level.toUpperCase() + }; +} + +/** + * Message logger. Will dispatch a message to registered loggers as needed. + * + * @param message message object + */ +forge$4.log.logMessage = function(message) { + var messageLevelIndex = sLevelInfo[message.level].index; + for(var i = 0; i < sLoggers.length; ++i) { + var logger = sLoggers[i]; + if(logger.flags & forge$4.log.NO_LEVEL_CHECK) { + logger.f(message); + } else { + // get logger level + var loggerLevelIndex = sLevelInfo[logger.level].index; + // check level + if(messageLevelIndex <= loggerLevelIndex) { + // message critical enough, call logger + logger.f(logger, message); + } + } + } +}; + +/** + * Sets the 'standard' key on a message object to: + * "LEVEL [category] " + message + * + * @param message a message log object + */ +forge$4.log.prepareStandard = function(message) { + if(!('standard' in message)) { + message.standard = + sLevelInfo[message.level].name + + //' ' + +message.timestamp + + ' [' + message.category + '] ' + + message.message; + } +}; + +/** + * Sets the 'full' key on a message object to the original message + * interpolated via % formatting with the message arguments. + * + * @param message a message log object. + */ +forge$4.log.prepareFull = function(message) { + if(!('full' in message)) { + // copy args and insert message at the front + var args = [message.message]; + args = args.concat([] || message['arguments']); + // format the message + message.full = forge$4.util.format.apply(this, args); + } +}; + +/** + * Applies both preparseStandard() and prepareFull() to a message object and + * store result in 'standardFull'. + * + * @param message a message log object. + */ +forge$4.log.prepareStandardFull = function(message) { + if(!('standardFull' in message)) { + // FIXME implement 'standardFull' logging + forge$4.log.prepareStandard(message); + message.standardFull = message.standard; + } +}; + +// create log level functions +{ + // levels for which we want functions + var levels = ['error', 'warning', 'info', 'debug', 'verbose']; + for(var i = 0; i < levels.length; ++i) { + // wrap in a function to ensure proper level var is passed + (function(level) { + // create function for this level + forge$4.log[level] = function(category, message/*, args...*/) { + // convert arguments to real array, remove category and message + var args = Array.prototype.slice.call(arguments).slice(2); + // create message object + // Note: interpolation and standard formatting is done lazily + var msg = { + timestamp: new Date(), + level: level, + category: category, + message: message, + 'arguments': args + /*standard*/ + /*full*/ + /*fullMessage*/ + }; + // process this message + forge$4.log.logMessage(msg); + }; + })(levels[i]); + } +} + +/** + * Creates a new logger with specified custom logging function. + * + * The logging function has a signature of: + * function(logger, message) + * logger: current logger + * message: object: + * level: level id + * category: category + * message: string message + * arguments: Array of extra arguments + * fullMessage: interpolated message and arguments if INTERPOLATE flag set + * + * @param logFunction a logging function which takes a log message object + * as a parameter. + * + * @return a logger object. + */ +forge$4.log.makeLogger = function(logFunction) { + var logger = { + flags: 0, + f: logFunction + }; + forge$4.log.setLevel(logger, 'none'); + return logger; +}; + +/** + * Sets the current log level on a logger. + * + * @param logger the target logger. + * @param level the new maximum log level as a string. + * + * @return true if set, false if not. + */ +forge$4.log.setLevel = function(logger, level) { + var rval = false; + if(logger && !(logger.flags & forge$4.log.LEVEL_LOCKED)) { + for(var i = 0; i < forge$4.log.levels.length; ++i) { + var aValidLevel = forge$4.log.levels[i]; + if(level == aValidLevel) { + // set level + logger.level = level; + rval = true; + break; + } + } + } + + return rval; +}; + +/** + * Locks the log level at its current value. + * + * @param logger the target logger. + * @param lock boolean lock value, default to true. + */ +forge$4.log.lock = function(logger, lock) { + if(typeof lock === 'undefined' || lock) { + logger.flags |= forge$4.log.LEVEL_LOCKED; + } else { + logger.flags &= ~forge$4.log.LEVEL_LOCKED; + } +}; + +/** + * Adds a logger. + * + * @param logger the logger object. + */ +forge$4.log.addLogger = function(logger) { + sLoggers.push(logger); +}; + +// setup the console logger if possible, else create fake console.log +if(typeof(console) !== 'undefined' && 'log' in console) { + var logger; + if(console.error && console.warn && console.info && console.debug) { + // looks like Firebug-style logging is available + // level handlers map + var levelHandlers = { + error: console.error, + warning: console.warn, + info: console.info, + debug: console.debug, + verbose: console.debug + }; + var f = function(logger, message) { + forge$4.log.prepareStandard(message); + var handler = levelHandlers[message.level]; + // prepend standard message and concat args + var args = [message.standard]; + args = args.concat(message['arguments'].slice()); + // apply to low-level console function + handler.apply(console, args); + }; + logger = forge$4.log.makeLogger(f); + } else { + // only appear to have basic console.log + var f = function(logger, message) { + forge$4.log.prepareStandardFull(message); + console.log(message.standardFull); + }; + logger = forge$4.log.makeLogger(f); + } + forge$4.log.setLevel(logger, 'debug'); + forge$4.log.addLogger(logger); + sConsoleLogger = logger; +} else { + // define fake console.log to avoid potential script errors on + // browsers that do not have console logging + console = { + log: function() {} + }; +} + +/* + * Check for logging control query vars. + * + * console.level= + * Set's the console log level by name. Useful to override defaults and + * allow more verbose logging before a user config is loaded. + * + * console.lock= + * Lock the console log level at whatever level it is set at. This is run + * after console.level is processed. Useful to force a level of verbosity + * that could otherwise be limited by a user config. + */ +if(sConsoleLogger !== null) { + var query = forge$4.util.getQueryVariables(); + if('console.level' in query) { + // set with last value + forge$4.log.setLevel( + sConsoleLogger, query['console.level'].slice(-1)[0]); + } + if('console.lock' in query) { + // set with last value + var lock = query['console.lock'].slice(-1)[0]; + if(lock == 'true') { + forge$4.log.lock(sConsoleLogger); + } + } +} + +// provide public access to console logger +forge$4.log.consoleLogger = sConsoleLogger; + +/** + * Javascript implementation of PKCS#7 v1.5. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2012-2015 Digital Bazaar, Inc. + * + * Currently this implementation only supports ContentType of EnvelopedData, + * EncryptedData, or SignedData at the root level. The top level elements may + * contain only a ContentInfo of ContentType Data, i.e. plain data. Further + * nesting is not (yet) supported. + * + * The Forge validators for PKCS #7's ASN.1 structures are available from + * a separate file pkcs7asn1.js, since those are referenced from other + * PKCS standards like PKCS #12. + */ + +var forge$3 = forge$F; + + + + + + + + + + +// shortcut for ASN.1 API +var asn1 = forge$3.asn1; + +// shortcut for PKCS#7 API +var p7 = forge$3.pkcs7 = forge$3.pkcs7 || {}; + +/** + * Converts a PKCS#7 message from PEM format. + * + * @param pem the PEM-formatted PKCS#7 message. + * + * @return the PKCS#7 message. + */ +p7.messageFromPem = function(pem) { + var msg = forge$3.pem.decode(pem)[0]; + + if(msg.type !== 'PKCS7') { + var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' + + 'header type is not "PKCS#7".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body); + + return p7.messageFromAsn1(obj); +}; + +/** + * Converts a PKCS#7 message to PEM format. + * + * @param msg The PKCS#7 message object + * @param maxline The maximum characters per line, defaults to 64. + * + * @return The PEM-formatted PKCS#7 message. + */ +p7.messageToPem = function(msg, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var pemObj = { + type: 'PKCS7', + body: asn1.toDer(msg.toAsn1()).getBytes() + }; + return forge$3.pem.encode(pemObj, {maxline: maxline}); +}; + +/** + * Converts a PKCS#7 message from an ASN.1 object. + * + * @param obj the ASN.1 representation of a ContentInfo. + * + * @return the PKCS#7 message. + */ +p7.messageFromAsn1 = function(obj) { + // validate root level ContentInfo and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 message. ' + + 'ASN.1 object is not an PKCS#7 ContentInfo.'); + error.errors = errors; + throw error; + } + + var contentType = asn1.derToOid(capture.contentType); + var msg; + + switch(contentType) { + case forge$3.pki.oids.envelopedData: + msg = p7.createEnvelopedData(); + break; + + case forge$3.pki.oids.encryptedData: + msg = p7.createEncryptedData(); + break; + + case forge$3.pki.oids.signedData: + msg = p7.createSignedData(); + break; + + default: + throw new Error('Cannot read PKCS#7 message. ContentType with OID ' + + contentType + ' is not (yet) supported.'); + } + + msg.fromAsn1(capture.content.value[0]); + return msg; +}; + +p7.createSignedData = function() { + var msg = null; + msg = { + type: forge$3.pki.oids.signedData, + version: 1, + certificates: [], + crls: [], + // TODO: add json-formatted signer stuff here? + signers: [], + // populated during sign() + digestAlgorithmIdentifiers: [], + contentInfo: null, + signerInfos: [], + + fromAsn1: function(obj) { + // validate SignedData content block and capture data. + _fromAsn1(msg, obj, p7.asn1.signedDataValidator); + msg.certificates = []; + msg.crls = []; + msg.digestAlgorithmIdentifiers = []; + msg.contentInfo = null; + msg.signerInfos = []; + + if(msg.rawCapture.certificates) { + var certs = msg.rawCapture.certificates.value; + for(var i = 0; i < certs.length; ++i) { + msg.certificates.push(forge$3.pki.certificateFromAsn1(certs[i])); + } + } + + // TODO: parse crls + }, + + toAsn1: function() { + // degenerate case with no content + if(!msg.contentInfo) { + msg.sign(); + } + + var certs = []; + for(var i = 0; i < msg.certificates.length; ++i) { + certs.push(forge$3.pki.certificateToAsn1(msg.certificates[i])); + } + + var crls = []; + // TODO: implement CRLs + + // [0] SignedData + var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(msg.version).getBytes()), + // DigestAlgorithmIdentifiers + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SET, true, + msg.digestAlgorithmIdentifiers), + // ContentInfo + msg.contentInfo + ]) + ]); + if(certs.length > 0) { + // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs)); + } + if(crls.length > 0) { + // [1] IMPLICIT CertificateRevocationLists OPTIONAL + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls)); + } + // SignerInfos + signedData.value[0].value.push( + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, + msg.signerInfos)); + + // ContentInfo + return asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(msg.type).getBytes()), + // [0] SignedData + signedData + ]); + }, + + /** + * Add (another) entity to list of signers. + * + * Note: If authenticatedAttributes are provided, then, per RFC 2315, + * they must include at least two attributes: content type and + * message digest. The message digest attribute value will be + * auto-calculated during signing and will be ignored if provided. + * + * Here's an example of providing these two attributes: + * + * forge.pkcs7.createSignedData(); + * p7.addSigner({ + * issuer: cert.issuer.attributes, + * serialNumber: cert.serialNumber, + * key: privateKey, + * digestAlgorithm: forge.pki.oids.sha1, + * authenticatedAttributes: [{ + * type: forge.pki.oids.contentType, + * value: forge.pki.oids.data + * }, { + * type: forge.pki.oids.messageDigest + * }] + * }); + * + * TODO: Support [subjectKeyIdentifier] as signer's ID. + * + * @param signer the signer information: + * key the signer's private key. + * [certificate] a certificate containing the public key + * associated with the signer's private key; use this option as + * an alternative to specifying signer.issuer and + * signer.serialNumber. + * [issuer] the issuer attributes (eg: cert.issuer.attributes). + * [serialNumber] the signer's certificate's serial number in + * hexadecimal (eg: cert.serialNumber). + * [digestAlgorithm] the message digest OID, as a string, to use + * (eg: forge.pki.oids.sha1). + * [authenticatedAttributes] an optional array of attributes + * to also sign along with the content. + */ + addSigner: function(signer) { + var issuer = signer.issuer; + var serialNumber = signer.serialNumber; + if(signer.certificate) { + var cert = signer.certificate; + if(typeof cert === 'string') { + cert = forge$3.pki.certificateFromPem(cert); + } + issuer = cert.issuer.attributes; + serialNumber = cert.serialNumber; + } + var key = signer.key; + if(!key) { + throw new Error( + 'Could not add PKCS#7 signer; no private key specified.'); + } + if(typeof key === 'string') { + key = forge$3.pki.privateKeyFromPem(key); + } + + // ensure OID known for digest algorithm + var digestAlgorithm = signer.digestAlgorithm || forge$3.pki.oids.sha1; + switch(digestAlgorithm) { + case forge$3.pki.oids.sha1: + case forge$3.pki.oids.sha256: + case forge$3.pki.oids.sha384: + case forge$3.pki.oids.sha512: + case forge$3.pki.oids.md5: + break; + default: + throw new Error( + 'Could not add PKCS#7 signer; unknown message digest algorithm: ' + + digestAlgorithm); + } + + // if authenticatedAttributes is present, then the attributes + // must contain at least PKCS #9 content-type and message-digest + var authenticatedAttributes = signer.authenticatedAttributes || []; + if(authenticatedAttributes.length > 0) { + var contentType = false; + var messageDigest = false; + for(var i = 0; i < authenticatedAttributes.length; ++i) { + var attr = authenticatedAttributes[i]; + if(!contentType && attr.type === forge$3.pki.oids.contentType) { + contentType = true; + if(messageDigest) { + break; + } + continue; + } + if(!messageDigest && attr.type === forge$3.pki.oids.messageDigest) { + messageDigest = true; + if(contentType) { + break; + } + continue; + } + } + + if(!contentType || !messageDigest) { + throw new Error('Invalid signer.authenticatedAttributes. If ' + + 'signer.authenticatedAttributes is specified, then it must ' + + 'contain at least two attributes, PKCS #9 content-type and ' + + 'PKCS #9 message-digest.'); + } + } + + msg.signers.push({ + key: key, + version: 1, + issuer: issuer, + serialNumber: serialNumber, + digestAlgorithm: digestAlgorithm, + signatureAlgorithm: forge$3.pki.oids.rsaEncryption, + signature: null, + authenticatedAttributes: authenticatedAttributes, + unauthenticatedAttributes: [] + }); + }, + + /** + * Signs the content. + * @param options Options to apply when signing: + * [detached] boolean. If signing should be done in detached mode. Defaults to false. + */ + sign: function(options) { + options = options || {}; + // auto-generate content info + if(typeof msg.content !== 'object' || msg.contentInfo === null) { + // use Data ContentInfo + msg.contentInfo = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(forge$3.pki.oids.data).getBytes()) + ]); + + // add actual content, if present + if('content' in msg) { + var content; + if(msg.content instanceof forge$3.util.ByteBuffer) { + content = msg.content.bytes(); + } else if(typeof msg.content === 'string') { + content = forge$3.util.encodeUtf8(msg.content); + } + + if (options.detached) { + msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); + } else { + msg.contentInfo.value.push( + // [0] EXPLICIT content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + content) + ])); + } + } + } + + // no signers, return early (degenerate case for certificate container) + if(msg.signers.length === 0) { + return; + } + + // generate digest algorithm identifiers + var mds = addDigestAlgorithmIds(); + + // generate signerInfos + addSignerInfos(mds); + }, + + verify: function() { + throw new Error('PKCS#7 signature verification not yet implemented.'); + }, + + /** + * Add a certificate. + * + * @param cert the certificate to add. + */ + addCertificate: function(cert) { + // convert from PEM + if(typeof cert === 'string') { + cert = forge$3.pki.certificateFromPem(cert); + } + msg.certificates.push(cert); + }, + + /** + * Add a certificate revokation list. + * + * @param crl the certificate revokation list to add. + */ + addCertificateRevokationList: function(crl) { + throw new Error('PKCS#7 CRL support not yet implemented.'); + } + }; + return msg; + + function addDigestAlgorithmIds() { + var mds = {}; + + for(var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + var oid = signer.digestAlgorithm; + if(!(oid in mds)) { + // content digest + mds[oid] = forge$3.md[forge$3.pki.oids[oid]].create(); + } + if(signer.authenticatedAttributes.length === 0) { + // no custom attributes to digest; use content message digest + signer.md = mds[oid]; + } else { + // custom attributes to be digested; use own message digest + // TODO: optimize to just copy message digest state if that + // feature is ever supported with message digests + signer.md = forge$3.md[forge$3.pki.oids[oid]].create(); + } + } + + // add unique digest algorithm identifiers + msg.digestAlgorithmIdentifiers = []; + for(var oid in mds) { + msg.digestAlgorithmIdentifiers.push( + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oid).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + } + + return mds; + } + + function addSignerInfos(mds) { + var content; + + if (msg.detachedContent) { + // Signature has been made in detached mode. + content = msg.detachedContent; + } else { + // Note: ContentInfo is a SEQUENCE with 2 values, second value is + // the content field and is optional for a ContentInfo but required here + // since signers are present + // get ContentInfo content + content = msg.contentInfo.value[1]; + // skip [0] EXPLICIT content wrapper + content = content.value[0]; + } + + if(!content) { + throw new Error( + 'Could not sign PKCS#7 message; there is no content to sign.'); + } + + // get ContentInfo content type + var contentType = asn1.derToOid(msg.contentInfo.value[0].value); + + // serialize content + var bytes = asn1.toDer(content); + + // skip identifier and length per RFC 2315 9.3 + // skip identifier (1 byte) + bytes.getByte(); + // read and discard length bytes + asn1.getBerValueLength(bytes); + bytes = bytes.getBytes(); + + // digest content DER value bytes + for(var oid in mds) { + mds[oid].start().update(bytes); + } + + // sign content + var signingTime = new Date(); + for(var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + + if(signer.authenticatedAttributes.length === 0) { + // if ContentInfo content type is not "Data", then + // authenticatedAttributes must be present per RFC 2315 + if(contentType !== forge$3.pki.oids.data) { + throw new Error( + 'Invalid signer; authenticatedAttributes must be present ' + + 'when the ContentInfo content type is not PKCS#7 Data.'); + } + } else { + // process authenticated attributes + // [0] IMPLICIT + signer.authenticatedAttributesAsn1 = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + + // per RFC 2315, attributes are to be digested using a SET container + // not the above [0] IMPLICIT container + var attrsAsn1 = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SET, true, []); + + for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { + var attr = signer.authenticatedAttributes[ai]; + if(attr.type === forge$3.pki.oids.messageDigest) { + // use content message digest as value + attr.value = mds[signer.digestAlgorithm].digest(); + } else if(attr.type === forge$3.pki.oids.signingTime) { + // auto-populate signing time if not already set + if(!attr.value) { + attr.value = signingTime; + } + } + + // convert to ASN.1 and push onto Attributes SET (for signing) and + // onto authenticatedAttributesAsn1 to complete SignedData ASN.1 + // TODO: optimize away duplication + attrsAsn1.value.push(_attributeToAsn1(attr)); + signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); + } + + // DER-serialize and digest SET OF attributes only + bytes = asn1.toDer(attrsAsn1).getBytes(); + signer.md.start().update(bytes); + } + + // sign digest + signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5'); + } + + // add signer info + msg.signerInfos = _signersToAsn1(msg.signers); + } +}; + +/** + * Creates an empty PKCS#7 message of type EncryptedData. + * + * @return the message. + */ +p7.createEncryptedData = function() { + var msg = null; + msg = { + type: forge$3.pki.oids.encryptedData, + version: 0, + encryptedContent: { + algorithm: forge$3.pki.oids['aes256-CBC'] + }, + + /** + * Reads an EncryptedData content block (in ASN.1 format) + * + * @param obj The ASN.1 representation of the EncryptedData content block + */ + fromAsn1: function(obj) { + // Validate EncryptedData content block and capture data. + _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); + }, + + /** + * Decrypt encrypted content + * + * @param key The (symmetric) key as a byte buffer + */ + decrypt: function(key) { + if(key !== undefined) { + msg.encryptedContent.key = key; + } + _decryptContent(msg); + } + }; + return msg; +}; + +/** + * Creates an empty PKCS#7 message of type EnvelopedData. + * + * @return the message. + */ +p7.createEnvelopedData = function() { + var msg = null; + msg = { + type: forge$3.pki.oids.envelopedData, + version: 0, + recipients: [], + encryptedContent: { + algorithm: forge$3.pki.oids['aes256-CBC'] + }, + + /** + * Reads an EnvelopedData content block (in ASN.1 format) + * + * @param obj the ASN.1 representation of the EnvelopedData content block. + */ + fromAsn1: function(obj) { + // validate EnvelopedData content block and capture data + var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); + msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); + }, + + toAsn1: function() { + // ContentInfo + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(msg.type).getBytes()), + // [0] EnvelopedData + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(msg.version).getBytes()), + // RecipientInfos + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, + _recipientsToAsn1(msg.recipients)), + // EncryptedContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, + _encryptedContentToAsn1(msg.encryptedContent)) + ]) + ]) + ]); + }, + + /** + * Find recipient by X.509 certificate's issuer. + * + * @param cert the certificate with the issuer to look for. + * + * @return the recipient object. + */ + findRecipient: function(cert) { + var sAttr = cert.issuer.attributes; + + for(var i = 0; i < msg.recipients.length; ++i) { + var r = msg.recipients[i]; + var rAttr = r.issuer; + + if(r.serialNumber !== cert.serialNumber) { + continue; + } + + if(rAttr.length !== sAttr.length) { + continue; + } + + var match = true; + for(var j = 0; j < sAttr.length; ++j) { + if(rAttr[j].type !== sAttr[j].type || + rAttr[j].value !== sAttr[j].value) { + match = false; + break; + } + } + + if(match) { + return r; + } + } + + return null; + }, + + /** + * Decrypt enveloped content + * + * @param recipient The recipient object related to the private key + * @param privKey The (RSA) private key object + */ + decrypt: function(recipient, privKey) { + if(msg.encryptedContent.key === undefined && recipient !== undefined && + privKey !== undefined) { + switch(recipient.encryptedContent.algorithm) { + case forge$3.pki.oids.rsaEncryption: + case forge$3.pki.oids.desCBC: + var key = privKey.decrypt(recipient.encryptedContent.content); + msg.encryptedContent.key = forge$3.util.createBuffer(key); + break; + + default: + throw new Error('Unsupported asymmetric cipher, ' + + 'OID ' + recipient.encryptedContent.algorithm); + } + } + + _decryptContent(msg); + }, + + /** + * Add (another) entity to list of recipients. + * + * @param cert The certificate of the entity to add. + */ + addRecipient: function(cert) { + msg.recipients.push({ + version: 0, + issuer: cert.issuer.attributes, + serialNumber: cert.serialNumber, + encryptedContent: { + // We simply assume rsaEncryption here, since forge.pki only + // supports RSA so far. If the PKI module supports other + // ciphers one day, we need to modify this one as well. + algorithm: forge$3.pki.oids.rsaEncryption, + key: cert.publicKey + } + }); + }, + + /** + * Encrypt enveloped content. + * + * This function supports two optional arguments, cipher and key, which + * can be used to influence symmetric encryption. Unless cipher is + * provided, the cipher specified in encryptedContent.algorithm is used + * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key + * is (re-)used. If that one's not set, a random key will be generated + * automatically. + * + * @param [key] The key to be used for symmetric encryption. + * @param [cipher] The OID of the symmetric cipher to use. + */ + encrypt: function(key, cipher) { + // Part 1: Symmetric encryption + if(msg.encryptedContent.content === undefined) { + cipher = cipher || msg.encryptedContent.algorithm; + key = key || msg.encryptedContent.key; + + var keyLen, ivLen, ciphFn; + switch(cipher) { + case forge$3.pki.oids['aes128-CBC']: + keyLen = 16; + ivLen = 16; + ciphFn = forge$3.aes.createEncryptionCipher; + break; + + case forge$3.pki.oids['aes192-CBC']: + keyLen = 24; + ivLen = 16; + ciphFn = forge$3.aes.createEncryptionCipher; + break; + + case forge$3.pki.oids['aes256-CBC']: + keyLen = 32; + ivLen = 16; + ciphFn = forge$3.aes.createEncryptionCipher; + break; + + case forge$3.pki.oids['des-EDE3-CBC']: + keyLen = 24; + ivLen = 8; + ciphFn = forge$3.des.createEncryptionCipher; + break; + + default: + throw new Error('Unsupported symmetric cipher, OID ' + cipher); + } + + if(key === undefined) { + key = forge$3.util.createBuffer(forge$3.random.getBytes(keyLen)); + } else if(key.length() != keyLen) { + throw new Error('Symmetric key has wrong length; ' + + 'got ' + key.length() + ' bytes, expected ' + keyLen + '.'); + } + + // Keep a copy of the key & IV in the object, so the caller can + // use it for whatever reason. + msg.encryptedContent.algorithm = cipher; + msg.encryptedContent.key = key; + msg.encryptedContent.parameter = forge$3.util.createBuffer( + forge$3.random.getBytes(ivLen)); + + var ciph = ciphFn(key); + ciph.start(msg.encryptedContent.parameter.copy()); + ciph.update(msg.content); + + // The finish function does PKCS#7 padding by default, therefore + // no action required by us. + if(!ciph.finish()) { + throw new Error('Symmetric encryption failed.'); + } + + msg.encryptedContent.content = ciph.output; + } + + // Part 2: asymmetric encryption for each recipient + for(var i = 0; i < msg.recipients.length; ++i) { + var recipient = msg.recipients[i]; + + // Nothing to do, encryption already done. + if(recipient.encryptedContent.content !== undefined) { + continue; + } + + switch(recipient.encryptedContent.algorithm) { + case forge$3.pki.oids.rsaEncryption: + recipient.encryptedContent.content = + recipient.encryptedContent.key.encrypt( + msg.encryptedContent.key.data); + break; + + default: + throw new Error('Unsupported asymmetric cipher, OID ' + + recipient.encryptedContent.algorithm); + } + } + } + }; + return msg; +}; + +/** + * Converts a single recipient from an ASN.1 object. + * + * @param obj the ASN.1 RecipientInfo. + * + * @return the recipient object. + */ +function _recipientFromAsn1(obj) { + // validate EnvelopedData content block and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 RecipientInfo. ' + + 'ASN.1 object is not an PKCS#7 RecipientInfo.'); + error.errors = errors; + throw error; + } + + return { + version: capture.version.charCodeAt(0), + issuer: forge$3.pki.RDNAttributesAsArray(capture.issuer), + serialNumber: forge$3.util.createBuffer(capture.serial).toHex(), + encryptedContent: { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: capture.encParameter.value, + content: capture.encKey + } + }; +} + +/** + * Converts a single recipient object to an ASN.1 object. + * + * @param obj the recipient object. + * + * @return the ASN.1 RecipientInfo. + */ +function _recipientToAsn1(obj) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(obj.version).getBytes()), + // IssuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Name + forge$3.pki.distinguishedNameToAsn1({attributes: obj.issuer}), + // Serial + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge$3.util.hexToBytes(obj.serialNumber)) + ]), + // KeyEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()), + // Parameter, force NULL, only RSA supported for now. + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // EncryptedKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + obj.encryptedContent.content) + ]); +} + +/** + * Map a set of RecipientInfo ASN.1 objects to recipient objects. + * + * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF). + * + * @return an array of recipient objects. + */ +function _recipientsFromAsn1(infos) { + var ret = []; + for(var i = 0; i < infos.length; ++i) { + ret.push(_recipientFromAsn1(infos[i])); + } + return ret; +} + +/** + * Map an array of recipient objects to ASN.1 RecipientInfo objects. + * + * @param recipients an array of recipientInfo objects. + * + * @return an array of ASN.1 RecipientInfos. + */ +function _recipientsToAsn1(recipients) { + var ret = []; + for(var i = 0; i < recipients.length; ++i) { + ret.push(_recipientToAsn1(recipients[i])); + } + return ret; +} + +/** + * Converts a single signerInfo object to an ASN.1 object. + * + * @param obj the signerInfo object. + * + * @return the ASN.1 representation of a SignerInfo. + */ +function _signerToAsn1(obj) { + // SignerInfo + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(obj.version).getBytes()), + // issuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // name + forge$3.pki.distinguishedNameToAsn1({attributes: obj.issuer}), + // serial + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge$3.util.hexToBytes(obj.serialNumber)) + ]), + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.digestAlgorithm).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ]); + + // authenticatedAttributes (OPTIONAL) + if(obj.authenticatedAttributesAsn1) { + // add ASN.1 previously generated during signing + rval.value.push(obj.authenticatedAttributesAsn1); + } + + // digestEncryptionAlgorithm + rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.signatureAlgorithm).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + + // encryptedDigest + rval.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature)); + + // unauthenticatedAttributes (OPTIONAL) + if(obj.unauthenticatedAttributes.length > 0) { + // [1] IMPLICIT + var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); + for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { + var attr = obj.unauthenticatedAttributes[i]; + attrsAsn1.values.push(_attributeToAsn1(attr)); + } + rval.value.push(attrsAsn1); + } + + return rval; +} + +/** + * Map an array of signer objects to ASN.1 objects. + * + * @param signers an array of signer objects. + * + * @return an array of ASN.1 SignerInfos. + */ +function _signersToAsn1(signers) { + var ret = []; + for(var i = 0; i < signers.length; ++i) { + ret.push(_signerToAsn1(signers[i])); + } + return ret; +} + +/** + * Convert an attribute object to an ASN.1 Attribute. + * + * @param attr the attribute object. + * + * @return the ASN.1 Attribute. + */ +function _attributeToAsn1(attr) { + var value; + + // TODO: generalize to support more attributes + if(attr.type === forge$3.pki.oids.contentType) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.value).getBytes()); + } else if(attr.type === forge$3.pki.oids.messageDigest) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + attr.value.bytes()); + } else if(attr.type === forge$3.pki.oids.signingTime) { + /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049 + (inclusive) MUST be encoded as UTCTime. Any dates with year values + before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,] + UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST + include seconds (i.e., times are YYMMDDHHMMSSZ), even where the + number of seconds is zero. Midnight (GMT) must be represented as + "YYMMDD000000Z". */ + // TODO: make these module-level constants + var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); + var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); + var date = attr.value; + if(typeof date === 'string') { + // try to parse date + var timestamp = Date.parse(date); + if(!isNaN(timestamp)) { + date = new Date(timestamp); + } else if(date.length === 13) { + // YYMMDDHHMMSSZ (13 chars for UTCTime) + date = asn1.utcTimeToDate(date); + } else { + // assume generalized time + date = asn1.generalizedTimeToDate(date); + } + } + + if(date >= jan_1_1950 && date < jan_1_2050) { + value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, + asn1.dateToUtcTime(date)); + } else { + value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, + asn1.dateToGeneralizedTime(date)); + } + } + + // TODO: expose as common API call + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.type).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + value + ]) + ]); +} + +/** + * Map messages encrypted content to ASN.1 objects. + * + * @param ec The encryptedContent object of the message. + * + * @return ASN.1 representation of the encryptedContent object (SEQUENCE). + */ +function _encryptedContentToAsn1(ec) { + return [ + // ContentType, always Data for the moment + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(forge$3.pki.oids.data).getBytes()), + // ContentEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(ec.algorithm).getBytes()), + // Parameters (IV) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + ec.parameter.getBytes()) + ]), + // [0] EncryptedContent + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + ec.content.getBytes()) + ]) + ]; +} + +/** + * Reads the "common part" of an PKCS#7 content block (in ASN.1 format) + * + * This function reads the "common part" of the PKCS#7 content blocks + * EncryptedData and EnvelopedData, i.e. version number and symmetrically + * encrypted content block. + * + * The result of the ASN.1 validate and capture process is returned + * to allow the caller to extract further data, e.g. the list of recipients + * in case of a EnvelopedData object. + * + * @param msg the PKCS#7 object to read the data to. + * @param obj the ASN.1 representation of the content block. + * @param validator the ASN.1 structure validator object to use. + * + * @return the value map captured by validator object. + */ +function _fromAsn1(msg, obj, validator) { + var capture = {}; + var errors = []; + if(!asn1.validate(obj, validator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 message. ' + + 'ASN.1 object is not a supported PKCS#7 message.'); + error.errors = error; + throw error; + } + + // Check contentType, so far we only support (raw) Data. + var contentType = asn1.derToOid(capture.contentType); + if(contentType !== forge$3.pki.oids.data) { + throw new Error('Unsupported PKCS#7 message. ' + + 'Only wrapped ContentType Data supported.'); + } + + if(capture.encryptedContent) { + var content = ''; + if(forge$3.util.isArray(capture.encryptedContent)) { + for(var i = 0; i < capture.encryptedContent.length; ++i) { + if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { + throw new Error('Malformed PKCS#7 message, expecting encrypted ' + + 'content constructed of only OCTET STRING objects.'); + } + content += capture.encryptedContent[i].value; + } + } else { + content = capture.encryptedContent; + } + msg.encryptedContent = { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: forge$3.util.createBuffer(capture.encParameter.value), + content: forge$3.util.createBuffer(content) + }; + } + + if(capture.content) { + var content = ''; + if(forge$3.util.isArray(capture.content)) { + for(var i = 0; i < capture.content.length; ++i) { + if(capture.content[i].type !== asn1.Type.OCTETSTRING) { + throw new Error('Malformed PKCS#7 message, expecting ' + + 'content constructed of only OCTET STRING objects.'); + } + content += capture.content[i].value; + } + } else { + content = capture.content; + } + msg.content = forge$3.util.createBuffer(content); + } + + msg.version = capture.version.charCodeAt(0); + msg.rawCapture = capture; + + return capture; +} + +/** + * Decrypt the symmetrically encrypted content block of the PKCS#7 message. + * + * Decryption is skipped in case the PKCS#7 message object already has a + * (decrypted) content attribute. The algorithm, key and cipher parameters + * (probably the iv) are taken from the encryptedContent attribute of the + * message object. + * + * @param The PKCS#7 message object. + */ +function _decryptContent(msg) { + if(msg.encryptedContent.key === undefined) { + throw new Error('Symmetric key not available.'); + } + + if(msg.content === undefined) { + var ciph; + + switch(msg.encryptedContent.algorithm) { + case forge$3.pki.oids['aes128-CBC']: + case forge$3.pki.oids['aes192-CBC']: + case forge$3.pki.oids['aes256-CBC']: + ciph = forge$3.aes.createDecryptionCipher(msg.encryptedContent.key); + break; + + case forge$3.pki.oids['desCBC']: + case forge$3.pki.oids['des-EDE3-CBC']: + ciph = forge$3.des.createDecryptionCipher(msg.encryptedContent.key); + break; + + default: + throw new Error('Unsupported symmetric cipher, OID ' + + msg.encryptedContent.algorithm); + } + ciph.start(msg.encryptedContent.parameter); + ciph.update(msg.encryptedContent.content); + + if(!ciph.finish()) { + throw new Error('Symmetric decryption failed.'); + } + + msg.content = ciph.output; + } +} + +/** + * Functions to output keys in SSH-friendly formats. + * + * This is part of the Forge project which may be used under the terms of + * either the BSD License or the GNU General Public License (GPL) Version 2. + * + * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE + * + * @author https://github.com/shellac + */ + +var forge$2 = forge$F; + + + + + + +var ssh = forge$2.ssh = forge$2.ssh || {}; + +/** + * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file. + * + * @param privateKey the key. + * @param passphrase a passphrase to protect the key (falsy for no encryption). + * @param comment a comment to include in the key file. + * + * @return the PPK file as a string. + */ +ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { + comment = comment || ''; + passphrase = passphrase || ''; + var algorithm = 'ssh-rsa'; + var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc'; + + var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\r\n'; + ppk += 'Encryption: ' + encryptionAlgorithm + '\r\n'; + ppk += 'Comment: ' + comment + '\r\n'; + + // public key into buffer for ppk + var pubbuffer = forge$2.util.createBuffer(); + _addStringToBuffer(pubbuffer, algorithm); + _addBigIntegerToBuffer(pubbuffer, privateKey.e); + _addBigIntegerToBuffer(pubbuffer, privateKey.n); + + // write public key + var pub = forge$2.util.encode64(pubbuffer.bytes(), 64); + var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \r\n + ppk += 'Public-Lines: ' + length + '\r\n'; + ppk += pub; + + // private key into a buffer + var privbuffer = forge$2.util.createBuffer(); + _addBigIntegerToBuffer(privbuffer, privateKey.d); + _addBigIntegerToBuffer(privbuffer, privateKey.p); + _addBigIntegerToBuffer(privbuffer, privateKey.q); + _addBigIntegerToBuffer(privbuffer, privateKey.qInv); + + // optionally encrypt the private key + var priv; + if(!passphrase) { + // use the unencrypted buffer + priv = forge$2.util.encode64(privbuffer.bytes(), 64); + } else { + // encrypt RSA key using passphrase + var encLen = privbuffer.length() + 16 - 1; + encLen -= encLen % 16; + + // pad private key with sha1-d data -- needs to be a multiple of 16 + var padding = _sha1(privbuffer.bytes()); + + padding.truncate(padding.length() - encLen + privbuffer.length()); + privbuffer.putBuffer(padding); + + var aeskey = forge$2.util.createBuffer(); + aeskey.putBuffer(_sha1('\x00\x00\x00\x00', passphrase)); + aeskey.putBuffer(_sha1('\x00\x00\x00\x01', passphrase)); + + // encrypt some bytes using CBC mode + // key is 40 bytes, so truncate *by* 8 bytes + var cipher = forge$2.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC'); + cipher.start(forge$2.util.createBuffer().fillWithByte(0, 16)); + cipher.update(privbuffer.copy()); + cipher.finish(); + var encrypted = cipher.output; + + // Note: this appears to differ from Putty -- is forge wrong, or putty? + // due to padding we finish as an exact multiple of 16 + encrypted.truncate(16); // all padding + + priv = forge$2.util.encode64(encrypted.bytes(), 64); + } + + // output private key + length = Math.floor(priv.length / 66) + 1; // 64 + \r\n + ppk += '\r\nPrivate-Lines: ' + length + '\r\n'; + ppk += priv; + + // MAC + var mackey = _sha1('putty-private-key-file-mac-key', passphrase); + + var macbuffer = forge$2.util.createBuffer(); + _addStringToBuffer(macbuffer, algorithm); + _addStringToBuffer(macbuffer, encryptionAlgorithm); + _addStringToBuffer(macbuffer, comment); + macbuffer.putInt32(pubbuffer.length()); + macbuffer.putBuffer(pubbuffer); + macbuffer.putInt32(privbuffer.length()); + macbuffer.putBuffer(privbuffer); + + var hmac = forge$2.hmac.create(); + hmac.start('sha1', mackey); + hmac.update(macbuffer.bytes()); + + ppk += '\r\nPrivate-MAC: ' + hmac.digest().toHex() + '\r\n'; + + return ppk; +}; + +/** + * Encodes a public RSA key as an OpenSSH file. + * + * @param key the key. + * @param comment a comment. + * + * @return the public key in OpenSSH format. + */ +ssh.publicKeyToOpenSSH = function(key, comment) { + var type = 'ssh-rsa'; + comment = comment || ''; + + var buffer = forge$2.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + + return type + ' ' + forge$2.util.encode64(buffer.bytes()) + ' ' + comment; +}; + +/** + * Encodes a private RSA key as an OpenSSH file. + * + * @param key the key. + * @param passphrase a passphrase to protect the key (falsy for no encryption). + * + * @return the public key in OpenSSH format. + */ +ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { + if(!passphrase) { + return forge$2.pki.privateKeyToPem(privateKey); + } + // OpenSSH private key is just a legacy format, it seems + return forge$2.pki.encryptRsaPrivateKey(privateKey, passphrase, + {legacy: true, algorithm: 'aes128'}); +}; + +/** + * Gets the SSH fingerprint for the given public key. + * + * @param options the options to use. + * [md] the message digest object to use (defaults to forge.md.md5). + * [encoding] an alternative output encoding, such as 'hex' + * (defaults to none, outputs a byte buffer). + * [delimiter] the delimiter to use between bytes for 'hex' encoded + * output, eg: ':' (defaults to none). + * + * @return the fingerprint as a byte buffer or other encoding based on options. + */ +ssh.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md = options.md || forge$2.md.md5.create(); + + var type = 'ssh-rsa'; + var buffer = forge$2.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + + // hash public key bytes + md.start(); + md.update(buffer.getBytes()); + var digest = md.digest(); + if(options.encoding === 'hex') { + var hex = digest.toHex(); + if(options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if(options.encoding === 'binary') { + return digest.getBytes(); + } else if(options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; +}; + +/** + * Adds len(val) then val to a buffer. + * + * @param buffer the buffer to add to. + * @param val a big integer. + */ +function _addBigIntegerToBuffer(buffer, val) { + var hexVal = val.toString(16); + // ensure 2s complement +ve + if(hexVal[0] >= '8') { + hexVal = '00' + hexVal; + } + var bytes = forge$2.util.hexToBytes(hexVal); + buffer.putInt32(bytes.length); + buffer.putBytes(bytes); +} + +/** + * Adds len(val) then val to a buffer. + * + * @param buffer the buffer to add to. + * @param val a string. + */ +function _addStringToBuffer(buffer, val) { + buffer.putInt32(val.length); + buffer.putString(val); +} + +/** + * Hashes the arguments into one value using SHA-1. + * + * @return the sha1 hash of the provided arguments. + */ +function _sha1() { + var sha = forge$2.md.sha1.create(); + var num = arguments.length; + for (var i = 0; i < num; ++i) { + sha.update(arguments[i]); + } + return sha.digest(); +} + +/** + * Support for concurrent task management and synchronization in web + * applications. + * + * @author Dave Longley + * @author David I. Lehn + * + * Copyright (c) 2009-2013 Digital Bazaar, Inc. + */ + +var forge$1 = forge$F; + + + + +// logging category +var cat = 'forge.task'; + +// track tasks for debugging +var sTasks = {}; +var sNextTaskId = 0; +// debug access +forge$1.debug.set(cat, 'tasks', sTasks); + +// a map of task type to task queue +var sTaskQueues = {}; +// debug access +forge$1.debug.set(cat, 'queues', sTaskQueues); + +// name for unnamed tasks +var sNoTaskName = '?'; + +// maximum number of doNext() recursions before a context swap occurs +// FIXME: might need to tweak this based on the browser +var sMaxRecursions = 30; + +// time slice for doing tasks before a context swap occurs +// FIXME: might need to tweak this based on the browser +var sTimeSlice = 20; + +/** + * Task states. + * + * READY: ready to start processing + * RUNNING: task or a subtask is running + * BLOCKED: task is waiting to acquire N permits to continue + * SLEEPING: task is sleeping for a period of time + * DONE: task is done + * ERROR: task has an error + */ +var READY = 'ready'; +var RUNNING = 'running'; +var BLOCKED = 'blocked'; +var SLEEPING = 'sleeping'; +var DONE = 'done'; +var ERROR = 'error'; + +/** + * Task actions. Used to control state transitions. + * + * STOP: stop processing + * START: start processing tasks + * BLOCK: block task from continuing until 1 or more permits are released + * UNBLOCK: release one or more permits + * SLEEP: sleep for a period of time + * WAKEUP: wakeup early from SLEEPING state + * CANCEL: cancel further tasks + * FAIL: a failure occured + */ +var STOP = 'stop'; +var START = 'start'; +var BLOCK = 'block'; +var UNBLOCK = 'unblock'; +var SLEEP = 'sleep'; +var WAKEUP = 'wakeup'; +var CANCEL = 'cancel'; +var FAIL = 'fail'; + +/** + * State transition table. + * + * nextState = sStateTable[currentState][action] + */ +var sStateTable = {}; + +sStateTable[READY] = {}; +sStateTable[READY][STOP] = READY; +sStateTable[READY][START] = RUNNING; +sStateTable[READY][CANCEL] = DONE; +sStateTable[READY][FAIL] = ERROR; + +sStateTable[RUNNING] = {}; +sStateTable[RUNNING][STOP] = READY; +sStateTable[RUNNING][START] = RUNNING; +sStateTable[RUNNING][BLOCK] = BLOCKED; +sStateTable[RUNNING][UNBLOCK] = RUNNING; +sStateTable[RUNNING][SLEEP] = SLEEPING; +sStateTable[RUNNING][WAKEUP] = RUNNING; +sStateTable[RUNNING][CANCEL] = DONE; +sStateTable[RUNNING][FAIL] = ERROR; + +sStateTable[BLOCKED] = {}; +sStateTable[BLOCKED][STOP] = BLOCKED; +sStateTable[BLOCKED][START] = BLOCKED; +sStateTable[BLOCKED][BLOCK] = BLOCKED; +sStateTable[BLOCKED][UNBLOCK] = BLOCKED; +sStateTable[BLOCKED][SLEEP] = BLOCKED; +sStateTable[BLOCKED][WAKEUP] = BLOCKED; +sStateTable[BLOCKED][CANCEL] = DONE; +sStateTable[BLOCKED][FAIL] = ERROR; + +sStateTable[SLEEPING] = {}; +sStateTable[SLEEPING][STOP] = SLEEPING; +sStateTable[SLEEPING][START] = SLEEPING; +sStateTable[SLEEPING][BLOCK] = SLEEPING; +sStateTable[SLEEPING][UNBLOCK] = SLEEPING; +sStateTable[SLEEPING][SLEEP] = SLEEPING; +sStateTable[SLEEPING][WAKEUP] = SLEEPING; +sStateTable[SLEEPING][CANCEL] = DONE; +sStateTable[SLEEPING][FAIL] = ERROR; + +sStateTable[DONE] = {}; +sStateTable[DONE][STOP] = DONE; +sStateTable[DONE][START] = DONE; +sStateTable[DONE][BLOCK] = DONE; +sStateTable[DONE][UNBLOCK] = DONE; +sStateTable[DONE][SLEEP] = DONE; +sStateTable[DONE][WAKEUP] = DONE; +sStateTable[DONE][CANCEL] = DONE; +sStateTable[DONE][FAIL] = ERROR; + +sStateTable[ERROR] = {}; +sStateTable[ERROR][STOP] = ERROR; +sStateTable[ERROR][START] = ERROR; +sStateTable[ERROR][BLOCK] = ERROR; +sStateTable[ERROR][UNBLOCK] = ERROR; +sStateTable[ERROR][SLEEP] = ERROR; +sStateTable[ERROR][WAKEUP] = ERROR; +sStateTable[ERROR][CANCEL] = ERROR; +sStateTable[ERROR][FAIL] = ERROR; + +/** + * Creates a new task. + * + * @param options options for this task + * run: the run function for the task (required) + * name: the run function for the task (optional) + * parent: parent of this task (optional) + * + * @return the empty task. + */ +var Task = function(options) { + // task id + this.id = -1; + + // task name + this.name = options.name || sNoTaskName; + + // task has no parent + this.parent = options.parent || null; + + // save run function + this.run = options.run; + + // create a queue of subtasks to run + this.subtasks = []; + + // error flag + this.error = false; + + // state of the task + this.state = READY; + + // number of times the task has been blocked (also the number + // of permits needed to be released to continue running) + this.blocks = 0; + + // timeout id when sleeping + this.timeoutId = null; + + // no swap time yet + this.swapTime = null; + + // no user data + this.userData = null; + + // initialize task + // FIXME: deal with overflow + this.id = sNextTaskId++; + sTasks[this.id] = this; +}; + +/** + * Logs debug information on this task and the system state. + */ +Task.prototype.debug = function(msg) { + msg = msg || ''; + forge$1.log.debug(cat, msg, + '[%s][%s] task:', this.id, this.name, this, + 'subtasks:', this.subtasks.length, + 'queue:', sTaskQueues); +}; + +/** + * Adds a subtask to run after task.doNext() or task.fail() is called. + * + * @param name human readable name for this task (optional). + * @param subrun a function to run that takes the current task as + * its first parameter. + * + * @return the current task (useful for chaining next() calls). + */ +Task.prototype.next = function(name, subrun) { + // juggle parameters if it looks like no name is given + if(typeof(name) === 'function') { + subrun = name; + + // inherit parent's name + name = this.name; + } + // create subtask, set parent to this task, propagate callbacks + var subtask = new Task({ + run: subrun, + name: name, + parent: this + }); + // start subtasks running + subtask.state = RUNNING; + subtask.type = this.type; + subtask.successCallback = this.successCallback || null; + subtask.failureCallback = this.failureCallback || null; + + // queue a new subtask + this.subtasks.push(subtask); + + return this; +}; + +/** + * Adds subtasks to run in parallel after task.doNext() or task.fail() + * is called. + * + * @param name human readable name for this task (optional). + * @param subrun functions to run that take the current task as + * their first parameter. + * + * @return the current task (useful for chaining next() calls). + */ +Task.prototype.parallel = function(name, subrun) { + // juggle parameters if it looks like no name is given + if(forge$1.util.isArray(name)) { + subrun = name; + + // inherit parent's name + name = this.name; + } + // Wrap parallel tasks in a regular task so they are started at the + // proper time. + return this.next(name, function(task) { + // block waiting for subtasks + var ptask = task; + ptask.block(subrun.length); + + // we pass the iterator from the loop below as a parameter + // to a function because it is otherwise included in the + // closure and changes as the loop changes -- causing i + // to always be set to its highest value + var startParallelTask = function(pname, pi) { + forge$1.task.start({ + type: pname, + run: function(task) { + subrun[pi](task); + }, + success: function(task) { + ptask.unblock(); + }, + failure: function(task) { + ptask.unblock(); + } + }); + }; + + for(var i = 0; i < subrun.length; i++) { + // Type must be unique so task starts in parallel: + // name + private string + task id + sub-task index + // start tasks in parallel and unblock when the finish + var pname = name + '__parallel-' + task.id + '-' + i; + var pi = i; + startParallelTask(pname, pi); + } + }); +}; + +/** + * Stops a running task. + */ +Task.prototype.stop = function() { + this.state = sStateTable[this.state][STOP]; +}; + +/** + * Starts running a task. + */ +Task.prototype.start = function() { + this.error = false; + this.state = sStateTable[this.state][START]; + + // try to restart + if(this.state === RUNNING) { + this.start = new Date(); + this.run(this); + runNext(this, 0); + } +}; + +/** + * Blocks a task until it one or more permits have been released. The + * task will not resume until the requested number of permits have + * been released with call(s) to unblock(). + * + * @param n number of permits to wait for(default: 1). + */ +Task.prototype.block = function(n) { + n = typeof(n) === 'undefined' ? 1 : n; + this.blocks += n; + if(this.blocks > 0) { + this.state = sStateTable[this.state][BLOCK]; + } +}; + +/** + * Releases a permit to unblock a task. If a task was blocked by + * requesting N permits via block(), then it will only continue + * running once enough permits have been released via unblock() calls. + * + * If multiple processes need to synchronize with a single task then + * use a condition variable (see forge.task.createCondition). It is + * an error to unblock a task more times than it has been blocked. + * + * @param n number of permits to release (default: 1). + * + * @return the current block count (task is unblocked when count is 0) + */ +Task.prototype.unblock = function(n) { + n = typeof(n) === 'undefined' ? 1 : n; + this.blocks -= n; + if(this.blocks === 0 && this.state !== DONE) { + this.state = RUNNING; + runNext(this, 0); + } + return this.blocks; +}; + +/** + * Sleep for a period of time before resuming tasks. + * + * @param n number of milliseconds to sleep (default: 0). + */ +Task.prototype.sleep = function(n) { + n = typeof(n) === 'undefined' ? 0 : n; + this.state = sStateTable[this.state][SLEEP]; + var self = this; + this.timeoutId = setTimeout(function() { + self.timeoutId = null; + self.state = RUNNING; + runNext(self, 0); + }, n); +}; + +/** + * Waits on a condition variable until notified. The next task will + * not be scheduled until notification. A condition variable can be + * created with forge.task.createCondition(). + * + * Once cond.notify() is called, the task will continue. + * + * @param cond the condition variable to wait on. + */ +Task.prototype.wait = function(cond) { + cond.wait(this); +}; + +/** + * If sleeping, wakeup and continue running tasks. + */ +Task.prototype.wakeup = function() { + if(this.state === SLEEPING) { + cancelTimeout(this.timeoutId); + this.timeoutId = null; + this.state = RUNNING; + runNext(this, 0); + } +}; + +/** + * Cancel all remaining subtasks of this task. + */ +Task.prototype.cancel = function() { + this.state = sStateTable[this.state][CANCEL]; + // remove permits needed + this.permitsNeeded = 0; + // cancel timeouts + if(this.timeoutId !== null) { + cancelTimeout(this.timeoutId); + this.timeoutId = null; + } + // remove subtasks + this.subtasks = []; +}; + +/** + * Finishes this task with failure and sets error flag. The entire + * task will be aborted unless the next task that should execute + * is passed as a parameter. This allows levels of subtasks to be + * skipped. For instance, to abort only this tasks's subtasks, then + * call fail(task.parent). To abort this task's subtasks and its + * parent's subtasks, call fail(task.parent.parent). To abort + * all tasks and simply call the task callback, call fail() or + * fail(null). + * + * The task callback (success or failure) will always, eventually, be + * called. + * + * @param next the task to continue at, or null to abort entirely. + */ +Task.prototype.fail = function(next) { + // set error flag + this.error = true; + + // finish task + finish(this, true); + + if(next) { + // propagate task info + next.error = this.error; + next.swapTime = this.swapTime; + next.userData = this.userData; + + // do next task as specified + runNext(next, 0); + } else { + if(this.parent !== null) { + // finish root task (ensures it is removed from task queue) + var parent = this.parent; + while(parent.parent !== null) { + // propagate task info + parent.error = this.error; + parent.swapTime = this.swapTime; + parent.userData = this.userData; + parent = parent.parent; + } + finish(parent, true); + } + + // call failure callback if one exists + if(this.failureCallback) { + this.failureCallback(this); + } + } +}; + +/** + * Asynchronously start a task. + * + * @param task the task to start. + */ +var start = function(task) { + task.error = false; + task.state = sStateTable[task.state][START]; + setTimeout(function() { + if(task.state === RUNNING) { + task.swapTime = +new Date(); + task.run(task); + runNext(task, 0); + } + }, 0); +}; + +/** + * Run the next subtask or finish this task. + * + * @param task the task to process. + * @param recurse the recursion count. + */ +var runNext = function(task, recurse) { + // get time since last context swap (ms), if enough time has passed set + // swap to true to indicate that doNext was performed asynchronously + // also, if recurse is too high do asynchronously + var swap = + (recurse > sMaxRecursions) || + (+new Date() - task.swapTime) > sTimeSlice; + + var doNext = function(recurse) { + recurse++; + if(task.state === RUNNING) { + if(swap) { + // update swap time + task.swapTime = +new Date(); + } + + if(task.subtasks.length > 0) { + // run next subtask + var subtask = task.subtasks.shift(); + subtask.error = task.error; + subtask.swapTime = task.swapTime; + subtask.userData = task.userData; + subtask.run(subtask); + if(!subtask.error) { + runNext(subtask, recurse); + } + } else { + finish(task); + + if(!task.error) { + // chain back up and run parent + if(task.parent !== null) { + // propagate task info + task.parent.error = task.error; + task.parent.swapTime = task.swapTime; + task.parent.userData = task.userData; + + // no subtasks left, call run next subtask on parent + runNext(task.parent, recurse); + } + } + } + } + }; + + if(swap) { + // we're swapping, so run asynchronously + setTimeout(doNext, 0); + } else { + // not swapping, so run synchronously + doNext(recurse); + } +}; + +/** + * Finishes a task and looks for the next task in the queue to start. + * + * @param task the task to finish. + * @param suppressCallbacks true to suppress callbacks. + */ +var finish = function(task, suppressCallbacks) { + // subtask is now done + task.state = DONE; + + delete sTasks[task.id]; + + // only do queue processing for root tasks + if(task.parent === null) { + // report error if queue is missing + if(!(task.type in sTaskQueues)) { + forge$1.log.error(cat, + '[%s][%s] task queue missing [%s]', + task.id, task.name, task.type); + } else if(sTaskQueues[task.type].length === 0) { + // report error if queue is empty + forge$1.log.error(cat, + '[%s][%s] task queue empty [%s]', + task.id, task.name, task.type); + } else if(sTaskQueues[task.type][0] !== task) { + // report error if this task isn't the first in the queue + forge$1.log.error(cat, + '[%s][%s] task not first in queue [%s]', + task.id, task.name, task.type); + } else { + // remove ourselves from the queue + sTaskQueues[task.type].shift(); + // clean up queue if it is empty + if(sTaskQueues[task.type].length === 0) { + /* Note: Only a task can delete a queue of its own type. This + is used as a way to synchronize tasks. If a queue for a certain + task type exists, then a task of that type is running. + */ + delete sTaskQueues[task.type]; + } else { + sTaskQueues[task.type][0].start(); + } + } + + if(!suppressCallbacks) { + // call final callback if one exists + if(task.error && task.failureCallback) { + task.failureCallback(task); + } else if(!task.error && task.successCallback) { + task.successCallback(task); + } + } + } +}; + +/* Tasks API */ +forge$1.task = forge$1.task || {}; + +/** + * Starts a new task that will run the passed function asynchronously. + * + * In order to finish the task, either task.doNext() or task.fail() + * *must* be called. + * + * The task must have a type (a string identifier) that can be used to + * synchronize it with other tasks of the same type. That type can also + * be used to cancel tasks that haven't started yet. + * + * To start a task, the following object must be provided as a parameter + * (each function takes a task object as its first parameter): + * + * { + * type: the type of task. + * run: the function to run to execute the task. + * success: a callback to call when the task succeeds (optional). + * failure: a callback to call when the task fails (optional). + * } + * + * @param options the object as described above. + */ +forge$1.task.start = function(options) { + // create a new task + var task = new Task({ + run: options.run, + name: options.name || sNoTaskName + }); + task.type = options.type; + task.successCallback = options.success || null; + task.failureCallback = options.failure || null; + + // append the task onto the appropriate queue + if(!(task.type in sTaskQueues)) { + // create the queue with the new task + sTaskQueues[task.type] = [task]; + start(task); + } else { + // push the task onto the queue, it will be run after a task + // with the same type completes + sTaskQueues[options.type].push(task); + } +}; + +/** + * Cancels all tasks of the given type that haven't started yet. + * + * @param type the type of task to cancel. + */ +forge$1.task.cancel = function(type) { + // find the task queue + if(type in sTaskQueues) { + // empty all but the current task from the queue + sTaskQueues[type] = [sTaskQueues[type][0]]; + } +}; + +/** + * Creates a condition variable to synchronize tasks. To make a task wait + * on the condition variable, call task.wait(condition). To notify all + * tasks that are waiting, call condition.notify(). + * + * @return the condition variable. + */ +forge$1.task.createCondition = function() { + var cond = { + // all tasks that are blocked + tasks: {} + }; + + /** + * Causes the given task to block until notify is called. If the task + * is already waiting on this condition then this is a no-op. + * + * @param task the task to cause to wait. + */ + cond.wait = function(task) { + // only block once + if(!(task.id in cond.tasks)) { + task.block(); + cond.tasks[task.id] = task; + } + }; + + /** + * Notifies all waiting tasks to wake up. + */ + cond.notify = function() { + // since unblock() will run the next task from here, make sure to + // clear the condition's blocked task list before unblocking + var tmp = cond.tasks; + cond.tasks = {}; + for(var id in tmp) { + tmp[id].unblock(); + } + }; + + return cond; +}; + +/** + * Node.js module for Forge. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ + +var lib = forge$F; + +var forge = lib; + +// a hexString is considered negative if it's most significant bit is 1 +// because serial numbers use ones' complement notation +// this RFC in section 4.1.2.2 requires serial numbers to be positive +// http://www.ietf.org/rfc/rfc5280.txt +function toPositiveHex(hexString){ + var mostSiginficativeHexAsInt = parseInt(hexString[0], 16); + if (mostSiginficativeHexAsInt < 8){ + return hexString; + } + + mostSiginficativeHexAsInt -= 8; + return mostSiginficativeHexAsInt.toString() + hexString.substring(1); +} + +function getAlgorithm(key) { + switch (key) { + case 'sha256': + return forge.md.sha256.create(); + default: + return forge.md.sha1.create(); + } +} + +/** + * + * @param {forge.pki.CertificateField[]} attrs Attributes used for subject and issuer. + * @param {object} options + * @param {number} [options.days=365] the number of days before expiration + * @param {number} [options.keySize=1024] the size for the private key in bits + * @param {object} [options.extensions] additional extensions for the certificate + * @param {string} [options.algorithm="sha1"] The signature algorithm sha256 or sha1 + * @param {boolean} [options.pkcs7=false] include PKCS#7 as part of the output + * @param {boolean} [options.clientCertificate=false] generate client cert signed by the original key + * @param {string} [options.clientCertificateCN="John Doe jdoe123"] client certificate's common name + * @param {function} [done] Optional callback, if not provided the generation is synchronous + * @returns + */ +var generate = selfsigned.generate = function generate(attrs, options, done) { + if (typeof attrs === 'function') { + done = attrs; + attrs = undefined; + } else if (typeof options === 'function') { + done = options; + options = {}; + } + + options = options || {}; + + var generatePem = function (keyPair) { + var cert = forge.pki.createCertificate(); + + cert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9))); // the serial number can be decimal or hex (if preceded by 0x) + + cert.validity.notBefore = new Date(); + cert.validity.notAfter = new Date(); + cert.validity.notAfter.setDate(cert.validity.notBefore.getDate() + (options.days || 365)); + + attrs = attrs || [{ + name: 'commonName', + value: 'example.org' + }, { + name: 'countryName', + value: 'US' + }, { + shortName: 'ST', + value: 'Virginia' + }, { + name: 'localityName', + value: 'Blacksburg' + }, { + name: 'organizationName', + value: 'Test' + }, { + shortName: 'OU', + value: 'Test' + }]; + + cert.setSubject(attrs); + cert.setIssuer(attrs); + + cert.publicKey = keyPair.publicKey; + + cert.setExtensions(options.extensions || [{ + name: 'basicConstraints', + cA: true + }, { + name: 'keyUsage', + keyCertSign: true, + digitalSignature: true, + nonRepudiation: true, + keyEncipherment: true, + dataEncipherment: true + }, { + name: 'subjectAltName', + altNames: [{ + type: 6, // URI + value: 'http://example.org/webid#me' + }] + }]); + + cert.sign(keyPair.privateKey, getAlgorithm(options && options.algorithm)); + + const fingerprint = forge.md.sha1 + .create() + .update(forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes()) + .digest() + .toHex() + .match(/.{2}/g) + .join(':'); + + var pem = { + private: forge.pki.privateKeyToPem(keyPair.privateKey), + public: forge.pki.publicKeyToPem(keyPair.publicKey), + cert: forge.pki.certificateToPem(cert), + fingerprint: fingerprint, + }; + + if (options && options.pkcs7) { + var p7 = forge.pkcs7.createSignedData(); + p7.addCertificate(cert); + pem.pkcs7 = forge.pkcs7.messageToPem(p7); + } + + if (options && options.clientCertificate) { + var clientkeys = forge.pki.rsa.generateKeyPair(1024); + var clientcert = forge.pki.createCertificate(); + clientcert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9))); + clientcert.validity.notBefore = new Date(); + clientcert.validity.notAfter = new Date(); + clientcert.validity.notAfter.setFullYear(clientcert.validity.notBefore.getFullYear() + 1); + + var clientAttrs = JSON.parse(JSON.stringify(attrs)); + + for(var i = 0; i < clientAttrs.length; i++) { + if(clientAttrs[i].name === 'commonName') { + if( options.clientCertificateCN ) + clientAttrs[i] = { name: 'commonName', value: options.clientCertificateCN }; + else + clientAttrs[i] = { name: 'commonName', value: 'John Doe jdoe123' }; + } + } + + clientcert.setSubject(clientAttrs); + + // Set the issuer to the parent key + clientcert.setIssuer(attrs); + + clientcert.publicKey = clientkeys.publicKey; + + // Sign client cert with root cert + clientcert.sign(keyPair.privateKey); + + pem.clientprivate = forge.pki.privateKeyToPem(clientkeys.privateKey); + pem.clientpublic = forge.pki.publicKeyToPem(clientkeys.publicKey); + pem.clientcert = forge.pki.certificateToPem(clientcert); + + if (options.pkcs7) { + var clientp7 = forge.pkcs7.createSignedData(); + clientp7.addCertificate(clientcert); + pem.clientpkcs7 = forge.pkcs7.messageToPem(clientp7); + } + } + + var caStore = forge.pki.createCaStore(); + caStore.addCertificate(cert); + + try { + forge.pki.verifyCertificateChain(caStore, [cert], + function (vfd, depth, chain) { + if (vfd !== true) { + throw new Error('Certificate could not be verified.'); + } + return true; + }); + } + catch(ex) { + throw new Error(ex); + } + + return pem; + }; + + var keySize = options.keySize || 1024; + + if (done) { // async scenario + return forge.pki.rsa.generateKeyPair({ bits: keySize }, function (err, keyPair) { + if (err) { return done(err); } + + try { + return done(null, generatePem(keyPair)); + } catch (ex) { + return done(ex); + } + }); + } + + var keyPair = options.keyPair ? { + privateKey: forge.pki.privateKeyFromPem(options.keyPair.privateKey), + publicKey: forge.pki.publicKeyFromPem(options.keyPair.publicKey) + } : forge.pki.rsa.generateKeyPair(keySize); + + return generatePem(keyPair); +}; + +var index = /*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), selfsigned, { + 'default': selfsigned, + generate: generate +}); + +exports.index = index; +//# sourceMappingURL=dep-0e948eb3.js.map diff --git a/node_modules/vite/dist/node/chunks/dep-0e948eb3.js.map b/node_modules/vite/dist/node/chunks/dep-0e948eb3.js.map new file mode 100644 index 0000000..d908189 --- /dev/null +++ b/node_modules/vite/dist/node/chunks/dep-0e948eb3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dep-0e948eb3.js","sources":["../../../../../node_modules/node-forge/lib/forge.js","../../../../../node_modules/node-forge/lib/baseN.js","../../../../../node_modules/node-forge/lib/util.js","../../../../../node_modules/node-forge/lib/cipher.js","../../../../../node_modules/node-forge/lib/cipherModes.js","../../../../../node_modules/node-forge/lib/aes.js","../../../../../node_modules/node-forge/lib/oids.js","../../../../../node_modules/node-forge/lib/asn1.js","../../../../../node_modules/node-forge/lib/md.js","../../../../../node_modules/node-forge/lib/hmac.js","../../../../../node_modules/node-forge/lib/md5.js","../../../../../node_modules/node-forge/lib/pem.js","../../../../../node_modules/node-forge/lib/des.js","../../../../../node_modules/node-forge/lib/pbkdf2.js","../../../../../node_modules/node-forge/lib/sha256.js","../../../../../node_modules/node-forge/lib/prng.js","../../../../../node_modules/node-forge/lib/random.js","../../../../../node_modules/node-forge/lib/rc2.js","../../../../../node_modules/node-forge/lib/jsbn.js","../../../../../node_modules/node-forge/lib/sha1.js","../../../../../node_modules/node-forge/lib/pkcs1.js","../../../../../node_modules/node-forge/lib/prime.js","../../../../../node_modules/node-forge/lib/rsa.js","../../../../../node_modules/node-forge/lib/pbe.js","../../../../../node_modules/node-forge/lib/pkcs7asn1.js","../../../../../node_modules/node-forge/lib/mgf1.js","../../../../../node_modules/node-forge/lib/mgf.js","../../../../../node_modules/node-forge/lib/pss.js","../../../../../node_modules/node-forge/lib/x509.js","../../../../../node_modules/node-forge/lib/pkcs12.js","../../../../../node_modules/node-forge/lib/pki.js","../../../../../node_modules/node-forge/lib/tls.js","../../../../../node_modules/node-forge/lib/aesCipherSuites.js","../../../../../node_modules/node-forge/lib/debug.js","../../../../../node_modules/node-forge/lib/sha512.js","../../../../../node_modules/node-forge/lib/asn1-validator.js","../../../../../node_modules/node-forge/lib/ed25519.js","../../../../../node_modules/node-forge/lib/kem.js","../../../../../node_modules/node-forge/lib/log.js","../../../../../node_modules/node-forge/lib/pkcs7.js","../../../../../node_modules/node-forge/lib/ssh.js","../../../../../node_modules/node-forge/lib/task.js","../../../../../node_modules/node-forge/lib/index.js","../../../../../node_modules/selfsigned/index.js"],"sourcesContent":["/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = {\n // default options\n options: {\n usePureJavaScript: false\n }\n};\n","/**\n * Base-N/Base-X encoding/decoding functions.\n *\n * Original implementation from base-x:\n * https://github.com/cryptocoinjs/base-x\n *\n * Which is MIT licensed:\n *\n * The MIT License (MIT)\n *\n * Copyright base-x contributors (c) 2016\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nvar api = {};\nmodule.exports = api;\n\n// baseN alphabet indexes\nvar _reverseAlphabets = {};\n\n/**\n * BaseN-encodes a Uint8Array using the given alphabet.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the baseN-encoded output string.\n */\napi.encode = function(input, alphabet, maxline) {\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n if(maxline !== undefined && typeof maxline !== 'number') {\n throw new TypeError('\"maxline\" must be a number.');\n }\n\n var output = '';\n\n if(!(input instanceof Uint8Array)) {\n // assume forge byte buffer\n output = _encodeWithByteBuffer(input, alphabet);\n } else {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length; ++i) {\n for(var j = 0, carry = input[i]; j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n // deal with leading zeros\n for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n }\n\n if(maxline) {\n var regex = new RegExp('.{1,' + maxline + '}', 'g');\n output = output.match(regex).join('\\r\\n');\n }\n\n return output;\n};\n\n/**\n * Decodes a baseN-encoded (using the given alphabet) string to a\n * Uint8Array.\n *\n * @param input the baseN-encoded input string.\n *\n * @return the Uint8Array.\n */\napi.decode = function(input, alphabet) {\n if(typeof input !== 'string') {\n throw new TypeError('\"input\" must be a string.');\n }\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n\n var table = _reverseAlphabets[alphabet];\n if(!table) {\n // compute reverse alphabet\n table = _reverseAlphabets[alphabet] = [];\n for(var i = 0; i < alphabet.length; ++i) {\n table[alphabet.charCodeAt(i)] = i;\n }\n }\n\n // remove whitespace characters\n input = input.replace(/\\s/g, '');\n\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var bytes = [0];\n for(var i = 0; i < input.length; i++) {\n var value = table[input.charCodeAt(i)];\n if(value === undefined) {\n return;\n }\n\n for(var j = 0, carry = value; j < bytes.length; ++j) {\n carry += bytes[j] * base;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n\n while(carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // deal with leading zeros\n for(var k = 0; input[k] === first && k < input.length - 1; ++k) {\n bytes.push(0);\n }\n\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(bytes.reverse());\n }\n\n return new Uint8Array(bytes.reverse());\n};\n\nfunction _encodeWithByteBuffer(input, alphabet) {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length(); ++i) {\n for(var j = 0, carry = input.at(i); j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n var output = '';\n\n // deal with leading zeros\n for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n\n return output;\n}\n","/**\n * Utility functions for web applications.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2018 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nvar baseN = require('./baseN');\n\n/* Utilities API */\nvar util = module.exports = forge.util = forge.util || {};\n\n// define setImmediate and nextTick\n(function() {\n // use native nextTick (unless we're in webpack)\n // webpack (or better node-libs-browser polyfill) sets process.browser.\n // this way we can detect webpack properly\n if(typeof process !== 'undefined' && process.nextTick && !process.browser) {\n util.nextTick = process.nextTick;\n if(typeof setImmediate === 'function') {\n util.setImmediate = setImmediate;\n } else {\n // polyfill setImmediate with nextTick, older versions of node\n // (those w/o setImmediate) won't totally starve IO\n util.setImmediate = util.nextTick;\n }\n return;\n }\n\n // polyfill nextTick with native setImmediate\n if(typeof setImmediate === 'function') {\n util.setImmediate = function() { return setImmediate.apply(undefined, arguments); };\n util.nextTick = function(callback) {\n return setImmediate(callback);\n };\n return;\n }\n\n /* Note: A polyfill upgrade pattern is used here to allow combining\n polyfills. For example, MutationObserver is fast, but blocks UI updates,\n so it needs to allow UI updates periodically, so it falls back on\n postMessage or setTimeout. */\n\n // polyfill with setTimeout\n util.setImmediate = function(callback) {\n setTimeout(callback, 0);\n };\n\n // upgrade polyfill to use postMessage\n if(typeof window !== 'undefined' &&\n typeof window.postMessage === 'function') {\n var msg = 'forge.setImmediate';\n var callbacks = [];\n util.setImmediate = function(callback) {\n callbacks.push(callback);\n // only send message when one hasn't been sent in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n window.postMessage(msg, '*');\n }\n };\n function handler(event) {\n if(event.source === window && event.data === msg) {\n event.stopPropagation();\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }\n }\n window.addEventListener('message', handler, true);\n }\n\n // upgrade polyfill to use MutationObserver\n if(typeof MutationObserver !== 'undefined') {\n // polyfill with MutationObserver\n var now = Date.now();\n var attr = true;\n var div = document.createElement('div');\n var callbacks = [];\n new MutationObserver(function() {\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }).observe(div, {attributes: true});\n var oldSetImmediate = util.setImmediate;\n util.setImmediate = function(callback) {\n if(Date.now() - now > 15) {\n now = Date.now();\n oldSetImmediate(callback);\n } else {\n callbacks.push(callback);\n // only trigger observer when it hasn't been triggered in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n div.setAttribute('a', attr = !attr);\n }\n }\n };\n }\n\n util.nextTick = util.setImmediate;\n})();\n\n// check if running under Node.js\nutil.isNodejs =\n typeof process !== 'undefined' && process.versions && process.versions.node;\n\n\n// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while\n// it will point to `window` in the main thread.\n// To remain compatible with older browsers, we fall back to 'window' if 'self'\n// is not available.\nutil.globalScope = (function() {\n if(util.isNodejs) {\n return global;\n }\n\n return typeof self === 'undefined' ? window : self;\n})();\n\n// define isArray\nutil.isArray = Array.isArray || function(x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n};\n\n// define isArrayBuffer\nutil.isArrayBuffer = function(x) {\n return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;\n};\n\n// define isArrayBufferView\nutil.isArrayBufferView = function(x) {\n return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined;\n};\n\n/**\n * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for\n * algorithms where bit manipulation, JavaScript limitations, and/or algorithm\n * design only allow for byte operations of a limited size.\n *\n * @param n number of bits.\n *\n * Throw Error if n invalid.\n */\nfunction _checkBitsParam(n) {\n if(!(n === 8 || n === 16 || n === 24 || n === 32)) {\n throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);\n }\n}\n\n// TODO: set ByteBuffer to best available backing\nutil.ByteBuffer = ByteStringBuffer;\n\n/** Buffer w/BinaryString backing */\n\n/**\n * Constructor for a binary string backed byte buffer.\n *\n * @param [b] the bytes to wrap (either encoded as string, one byte per\n * character, or as an ArrayBuffer or Typed Array).\n */\nfunction ByteStringBuffer(b) {\n // TODO: update to match DataBuffer API\n\n // the data in this buffer\n this.data = '';\n // the pointer for reading from this buffer\n this.read = 0;\n\n if(typeof b === 'string') {\n this.data = b;\n } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) {\n if(typeof Buffer !== 'undefined' && b instanceof Buffer) {\n this.data = b.toString('binary');\n } else {\n // convert native buffer to forge buffer\n // FIXME: support native buffers internally instead\n var arr = new Uint8Array(b);\n try {\n this.data = String.fromCharCode.apply(null, arr);\n } catch(e) {\n for(var i = 0; i < arr.length; ++i) {\n this.putByte(arr[i]);\n }\n }\n }\n } else if(b instanceof ByteStringBuffer ||\n (typeof b === 'object' && typeof b.data === 'string' &&\n typeof b.read === 'number')) {\n // copy existing buffer\n this.data = b.data;\n this.read = b.read;\n }\n\n // used for v8 optimization\n this._constructedStringLength = 0;\n}\nutil.ByteStringBuffer = ByteStringBuffer;\n\n/* Note: This is an optimization for V8-based browsers. When V8 concatenates\n a string, the strings are only joined logically using a \"cons string\" or\n \"constructed/concatenated string\". These containers keep references to one\n another and can result in very large memory usage. For example, if a 2MB\n string is constructed by concatenating 4 bytes together at a time, the\n memory usage will be ~44MB; so ~22x increase. The strings are only joined\n together when an operation requiring their joining takes place, such as\n substr(). This function is called when adding data to this buffer to ensure\n these types of strings are periodically joined to reduce the memory\n footprint. */\nvar _MAX_CONSTRUCTED_STRING_LENGTH = 4096;\nutil.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {\n this._constructedStringLength += x;\n if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {\n // this substr() should cause the constructed string to join\n this.data.substr(0, 1);\n this._constructedStringLength = 0;\n }\n};\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.ByteStringBuffer.prototype.length = function() {\n return this.data.length - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.ByteStringBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putByte = function(b) {\n return this.putBytes(String.fromCharCode(b));\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.fillWithByte = function(b, n) {\n b = String.fromCharCode(b);\n var d = this.data;\n while(n > 0) {\n if(n & 1) {\n d += b;\n }\n n >>>= 1;\n if(n > 0) {\n b += b;\n }\n }\n this.data = d;\n this._optimizeConstructedString(n);\n return this;\n};\n\n/**\n * Puts bytes in this buffer.\n *\n * @param bytes the bytes (as a binary encoded string) to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBytes = function(bytes) {\n this.data += bytes;\n this._optimizeConstructedString(bytes.length);\n return this;\n};\n\n/**\n * Puts a UTF-16 encoded string into this buffer.\n *\n * @param str the string to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putString = function(str) {\n return this.putBytes(util.encodeUtf8(str));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 24 & 0xFF));\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n var bytes = '';\n do {\n n -= 8;\n bytes += String.fromCharCode((i >> n) & 0xFF);\n } while(n > 0);\n return this.putBytes(bytes);\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putSignedInt = function(i, n) {\n // putInt checks n\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBuffer = function(buffer) {\n return this.putBytes(buffer.getBytes());\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.getByte = function() {\n return this.data.charCodeAt(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 8 ^\n this.data.charCodeAt(this.read + 1));\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 16 ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 24 ^\n this.data.charCodeAt(this.read + 1) << 16 ^\n this.data.charCodeAt(this.read + 2) << 8 ^\n this.data.charCodeAt(this.read + 3));\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16 ^\n this.data.charCodeAt(this.read + 3) << 24);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by ceil(n/8).\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.charCodeAt(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer. Note that the resulting string is binary encoded (in node.js this\n * encoding is referred to as `binary`, it is *not* `utf8`).\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.ByteStringBuffer.prototype.getBytes = function(count) {\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.ByteStringBuffer.prototype.bytes = function(count) {\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.at = function(i) {\n return this.data.charCodeAt(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.setAt = function(i, b) {\n this.data = this.data.substr(0, this.read + i) +\n String.fromCharCode(b) +\n this.data.substr(this.read + i + 1);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.ByteStringBuffer.prototype.last = function() {\n return this.data.charCodeAt(this.data.length - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.ByteStringBuffer.prototype.copy = function() {\n var c = util.createBuffer(this.data);\n c.read = this.read;\n return c;\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.compact = function() {\n if(this.read > 0) {\n this.data = this.data.slice(this.read);\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.clear = function() {\n this.data = '';\n this.read = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.truncate = function(count) {\n var len = Math.max(0, this.length() - count);\n this.data = this.data.substr(this.read, len);\n this.read = 0;\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.ByteStringBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.length; ++i) {\n var b = this.data.charCodeAt(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a UTF-16 string (standard JavaScript string).\n *\n * @return a UTF-16 string.\n */\nutil.ByteStringBuffer.prototype.toString = function() {\n return util.decodeUtf8(this.bytes());\n};\n\n/** End Buffer w/BinaryString backing */\n\n/** Buffer w/UInt8Array backing */\n\n/**\n * FIXME: Experimental. Do not use yet.\n *\n * Constructor for an ArrayBuffer-backed byte buffer.\n *\n * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a\n * TypedArray.\n *\n * If a string is given, its encoding should be provided as an option,\n * otherwise it will default to 'binary'. A 'binary' string is encoded such\n * that each character is one byte in length and size.\n *\n * If an ArrayBuffer, DataView, or TypedArray is given, it will be used\n * *directly* without any copying. Note that, if a write to the buffer requires\n * more space, the buffer will allocate a new backing ArrayBuffer to\n * accommodate. The starting read and write offsets for the buffer may be\n * given as options.\n *\n * @param [b] the initial bytes for this buffer.\n * @param options the options to use:\n * [readOffset] the starting read offset to use (default: 0).\n * [writeOffset] the starting write offset to use (default: the\n * length of the first parameter).\n * [growSize] the minimum amount, in bytes, to grow the buffer by to\n * accommodate writes (default: 1024).\n * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the\n * first parameter, if it is a string (default: 'binary').\n */\nfunction DataBuffer(b, options) {\n // default options\n options = options || {};\n\n // pointers for read from/write to buffer\n this.read = options.readOffset || 0;\n this.growSize = options.growSize || 1024;\n\n var isArrayBuffer = util.isArrayBuffer(b);\n var isArrayBufferView = util.isArrayBufferView(b);\n if(isArrayBuffer || isArrayBufferView) {\n // use ArrayBuffer directly\n if(isArrayBuffer) {\n this.data = new DataView(b);\n } else {\n // TODO: adjust read/write offset based on the type of view\n // or specify that this must be done in the options ... that the\n // offsets are byte-based\n this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);\n }\n this.write = ('writeOffset' in options ?\n options.writeOffset : this.data.byteLength);\n return;\n }\n\n // initialize to empty array buffer and add any given bytes using putBytes\n this.data = new DataView(new ArrayBuffer(0));\n this.write = 0;\n\n if(b !== null && b !== undefined) {\n this.putBytes(b);\n }\n\n if('writeOffset' in options) {\n this.write = options.writeOffset;\n }\n}\nutil.DataBuffer = DataBuffer;\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.DataBuffer.prototype.length = function() {\n return this.write - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.DataBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Ensures this buffer has enough empty space to accommodate the given number\n * of bytes. An optional parameter may be given that indicates a minimum\n * amount to grow the buffer if necessary. If the parameter is not given,\n * the buffer will be grown by some previously-specified default amount\n * or heuristic.\n *\n * @param amount the number of bytes to accommodate.\n * @param [growSize] the minimum amount, in bytes, to grow the buffer by if\n * necessary.\n */\nutil.DataBuffer.prototype.accommodate = function(amount, growSize) {\n if(this.length() >= amount) {\n return this;\n }\n growSize = Math.max(growSize || this.growSize, amount);\n\n // grow buffer\n var src = new Uint8Array(\n this.data.buffer, this.data.byteOffset, this.data.byteLength);\n var dst = new Uint8Array(this.length() + growSize);\n dst.set(src);\n this.data = new DataView(dst.buffer);\n\n return this;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putByte = function(b) {\n this.accommodate(1);\n this.data.setUint8(this.write++, b);\n return this;\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.fillWithByte = function(b, n) {\n this.accommodate(n);\n for(var i = 0; i < n; ++i) {\n this.data.setUint8(b);\n }\n return this;\n};\n\n/**\n * Puts bytes in this buffer. The bytes may be given as a string, an\n * ArrayBuffer, a DataView, or a TypedArray.\n *\n * @param bytes the bytes to put.\n * @param [encoding] the encoding for the first parameter ('binary', 'utf8',\n * 'utf16', 'hex'), if it is a string (default: 'binary').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBytes = function(bytes, encoding) {\n if(util.isArrayBufferView(bytes)) {\n var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n var len = src.byteLength - src.byteOffset;\n this.accommodate(len);\n var dst = new Uint8Array(this.data.buffer, this.write);\n dst.set(src);\n this.write += len;\n return this;\n }\n\n if(util.isArrayBuffer(bytes)) {\n var src = new Uint8Array(bytes);\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(this.data.buffer);\n dst.set(src, this.write);\n this.write += src.byteLength;\n return this;\n }\n\n // bytes is a util.DataBuffer or equivalent\n if(bytes instanceof util.DataBuffer ||\n (typeof bytes === 'object' &&\n typeof bytes.read === 'number' && typeof bytes.write === 'number' &&\n util.isArrayBufferView(bytes.data))) {\n var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(bytes.data.byteLength, this.write);\n dst.set(src);\n this.write += src.byteLength;\n return this;\n }\n\n if(bytes instanceof util.ByteStringBuffer) {\n // copy binary string and process as the same as a string parameter below\n bytes = bytes.data;\n encoding = 'binary';\n }\n\n // string conversion\n encoding = encoding || 'binary';\n if(typeof bytes === 'string') {\n var view;\n\n // decode from string\n if(encoding === 'hex') {\n this.accommodate(Math.ceil(bytes.length / 2));\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.hex.decode(bytes, view, this.write);\n return this;\n }\n if(encoding === 'base64') {\n this.accommodate(Math.ceil(bytes.length / 4) * 3);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.base64.decode(bytes, view, this.write);\n return this;\n }\n\n // encode text as UTF-8 bytes\n if(encoding === 'utf8') {\n // encode as UTF-8 then decode string as raw binary\n bytes = util.encodeUtf8(bytes);\n encoding = 'binary';\n }\n\n // decode string as raw binary\n if(encoding === 'binary' || encoding === 'raw') {\n // one byte per character\n this.accommodate(bytes.length);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.raw.decode(view);\n return this;\n }\n\n // encode text as UTF-16 bytes\n if(encoding === 'utf16') {\n // two bytes per character\n this.accommodate(bytes.length * 2);\n view = new Uint16Array(this.data.buffer, this.write);\n this.write += util.text.utf16.encode(view);\n return this;\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n }\n\n throw Error('Invalid parameter: ' + bytes);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBuffer = function(buffer) {\n this.putBytes(buffer);\n buffer.clear();\n return this;\n};\n\n/**\n * Puts a string into this buffer.\n *\n * @param str the string to put.\n * @param [encoding] the encoding for the string (default: 'utf16').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putString = function(str) {\n return this.putBytes(str, 'utf16');\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16 = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24 = function(i) {\n this.accommodate(3);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32 = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16Le = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i, true);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24Le = function(i) {\n this.accommodate(3);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32Le = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i, true);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n do {\n n -= 8;\n this.data.setInt8(this.write++, (i >> n) & 0xFF);\n } while(n > 0);\n return this;\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putSignedInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.getByte = function() {\n return this.data.getInt8(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16 = function() {\n var rval = this.data.getInt16(this.read);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.getInt16(this.read) << 8 ^\n this.data.getInt8(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32 = function() {\n var rval = this.data.getInt32(this.read);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16Le = function() {\n var rval = this.data.getInt16(this.read, true);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.getInt8(this.read) ^\n this.data.getInt16(this.read + 1, true) << 8);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32Le = function() {\n var rval = this.data.getInt32(this.read, true);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.getInt8(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer.\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.DataBuffer.prototype.getBytes = function(count) {\n // TODO: deprecate this method, it is poorly named and\n // this.toString('binary') replaces it\n // add a toTypedArray()/toArrayBuffer() function\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.DataBuffer.prototype.bytes = function(count) {\n // TODO: deprecate this method, it is poorly named, add \"getString()\"\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.at = function(i) {\n return this.data.getUint8(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.setAt = function(i, b) {\n this.data.setUint8(i, b);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.DataBuffer.prototype.last = function() {\n return this.data.getUint8(this.write - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.DataBuffer.prototype.copy = function() {\n return new util.DataBuffer(this);\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.compact = function() {\n if(this.read > 0) {\n var src = new Uint8Array(this.data.buffer, this.read);\n var dst = new Uint8Array(src.byteLength);\n dst.set(src);\n this.data = new DataView(dst);\n this.write -= this.read;\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.clear = function() {\n this.data = new DataView(new ArrayBuffer(0));\n this.read = this.write = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.truncate = function(count) {\n this.write = Math.max(0, this.length() - count);\n this.read = Math.min(this.read, this.write);\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.DataBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.byteLength; ++i) {\n var b = this.data.getUint8(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a string, using the given encoding. If no\n * encoding is given, 'utf8' (UTF-8) is used.\n *\n * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',\n * 'base64' (default: 'utf8').\n *\n * @return a string representation of the bytes in this buffer.\n */\nutil.DataBuffer.prototype.toString = function(encoding) {\n var view = new Uint8Array(this.data, this.read, this.length());\n encoding = encoding || 'utf8';\n\n // encode to string\n if(encoding === 'binary' || encoding === 'raw') {\n return util.binary.raw.encode(view);\n }\n if(encoding === 'hex') {\n return util.binary.hex.encode(view);\n }\n if(encoding === 'base64') {\n return util.binary.base64.encode(view);\n }\n\n // decode to text\n if(encoding === 'utf8') {\n return util.text.utf8.decode(view);\n }\n if(encoding === 'utf16') {\n return util.text.utf16.decode(view);\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n};\n\n/** End Buffer w/UInt8Array backing */\n\n/**\n * Creates a buffer that stores bytes. A value may be given to populate the\n * buffer with data. This value can either be string of encoded bytes or a\n * regular string of characters. When passing a string of binary encoded\n * bytes, the encoding `raw` should be given. This is also the default. When\n * passing a string of characters, the encoding `utf8` should be given.\n *\n * @param [input] a string with encoded bytes to store in the buffer.\n * @param [encoding] (default: 'raw', other: 'utf8').\n */\nutil.createBuffer = function(input, encoding) {\n // TODO: deprecate, use new ByteBuffer() instead\n encoding = encoding || 'raw';\n if(input !== undefined && encoding === 'utf8') {\n input = util.encodeUtf8(input);\n }\n return new util.ByteBuffer(input);\n};\n\n/**\n * Fills a string with a particular value. If you want the string to be a byte\n * string, pass in String.fromCharCode(theByte).\n *\n * @param c the character to fill the string with, use String.fromCharCode\n * to fill the string with a byte value.\n * @param n the number of characters of value c to fill with.\n *\n * @return the filled string.\n */\nutil.fillString = function(c, n) {\n var s = '';\n while(n > 0) {\n if(n & 1) {\n s += c;\n }\n n >>>= 1;\n if(n > 0) {\n c += c;\n }\n }\n return s;\n};\n\n/**\n * Performs a per byte XOR between two byte strings and returns the result as a\n * string of bytes.\n *\n * @param s1 first string of bytes.\n * @param s2 second string of bytes.\n * @param n the number of bytes to XOR.\n *\n * @return the XOR'd result.\n */\nutil.xorBytes = function(s1, s2, n) {\n var s3 = '';\n var b = '';\n var t = '';\n var i = 0;\n var c = 0;\n for(; n > 0; --n, ++i) {\n b = s1.charCodeAt(i) ^ s2.charCodeAt(i);\n if(c >= 10) {\n s3 += t;\n t = '';\n c = 0;\n }\n t += String.fromCharCode(b);\n ++c;\n }\n s3 += t;\n return s3;\n};\n\n/**\n * Converts a hex string into a 'binary' encoded string of bytes.\n *\n * @param hex the hexadecimal string to convert.\n *\n * @return the binary-encoded string of bytes.\n */\nutil.hexToBytes = function(hex) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.decode instead.\"\n var rval = '';\n var i = 0;\n if(hex.length & 1 == 1) {\n // odd number of characters, convert first character alone\n i = 1;\n rval += String.fromCharCode(parseInt(hex[0], 16));\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n }\n return rval;\n};\n\n/**\n * Converts a 'binary' encoded string of bytes to hex.\n *\n * @param bytes the byte string to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.bytesToHex = function(bytes) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.encode instead.\"\n return util.createBuffer(bytes).toHex();\n};\n\n/**\n * Converts an 32-bit integer to 4-big-endian byte string.\n *\n * @param i the integer.\n *\n * @return the byte string.\n */\nutil.int32ToBytes = function(i) {\n return (\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n// base64 characters, reverse mapping\nvar _base64 =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nvar _base64Idx = [\n/*43 -43 = 0*/\n/*'+', 1, 2, 3,'/' */\n 62, -1, -1, -1, 63,\n\n/*'0','1','2','3','4','5','6','7','8','9' */\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n\n/*15, 16, 17,'=', 19, 20, 21 */\n -1, -1, -1, 64, -1, -1, -1,\n\n/*65 - 43 = 22*/\n/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n\n/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n\n/*91 - 43 = 48 */\n/*48, 49, 50, 51, 52, 53 */\n -1, -1, -1, -1, -1, -1,\n\n/*97 - 43 = 54*/\n/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,\n\n/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n];\n\n// base58 characters (Bitcoin alphabet)\nvar _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Base64 encodes a 'binary' encoded string of bytes.\n *\n * @param input the binary encoded string of bytes to base64-encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output.\n */\nutil.encode64 = function(input, maxline) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.encode instead.\"\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.length) {\n chr1 = input.charCodeAt(i++);\n chr2 = input.charCodeAt(i++);\n chr3 = input.charCodeAt(i++);\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Base64 decodes a string into a 'binary' encoded string of bytes.\n *\n * @param input the base64-encoded input.\n *\n * @return the binary encoded string.\n */\nutil.decode64 = function(input) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.decode instead.\"\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n var output = '';\n var enc1, enc2, enc3, enc4;\n var i = 0;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));\n if(enc4 !== 64) {\n // decoded 3 bytes\n output += String.fromCharCode(((enc3 & 3) << 6) | enc4);\n }\n }\n }\n\n return output;\n};\n\n/**\n * Encodes the given string of characters (a standard JavaScript\n * string) as a binary encoded string where the bytes represent\n * a UTF-8 encoded string of characters. Non-ASCII characters will be\n * encoded as multiple bytes according to UTF-8.\n *\n * @param str a standard string of characters to encode.\n *\n * @return the binary encoded string.\n */\nutil.encodeUtf8 = function(str) {\n return unescape(encodeURIComponent(str));\n};\n\n/**\n * Decodes a binary encoded string that contains bytes that\n * represent a UTF-8 encoded string of characters -- into a\n * string of characters (a standard JavaScript string).\n *\n * @param str the binary encoded string to decode.\n *\n * @return the resulting standard string of characters.\n */\nutil.decodeUtf8 = function(str) {\n return decodeURIComponent(escape(str));\n};\n\n// binary encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.binary = {\n raw: {},\n hex: {},\n base64: {},\n base58: {},\n baseN : {\n encode: baseN.encode,\n decode: baseN.decode\n }\n};\n\n/**\n * Encodes a Uint8Array as a binary-encoded string. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param bytes the Uint8Array to encode.\n *\n * @return the binary-encoded string.\n */\nutil.binary.raw.encode = function(bytes) {\n return String.fromCharCode.apply(null, bytes);\n};\n\n/**\n * Decodes a binary-encoded string to a Uint8Array. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param str the binary-encoded string to decode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.raw.decode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or\n * ByteBuffer as a string of hexadecimal characters.\n *\n * @param bytes the bytes to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.binary.hex.encode = util.bytesToHex;\n\n/**\n * Decodes a hex-encoded string to a Uint8Array.\n *\n * @param hex the hexadecimal string to convert.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.hex.decode = function(hex, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(hex.length / 2));\n }\n offset = offset || 0;\n var i = 0, j = offset;\n if(hex.length & 1) {\n // odd number of characters, convert first character alone\n i = 1;\n out[j++] = parseInt(hex[0], 16);\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n out[j++] = parseInt(hex.substr(i, 2), 16);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Base64-encodes a Uint8Array.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output string.\n */\nutil.binary.base64.encode = function(input, maxline) {\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.byteLength) {\n chr1 = input[i++];\n chr2 = input[i++];\n chr3 = input[i++];\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Decodes a base64-encoded string to a Uint8Array.\n *\n * @param input the base64-encoded input string.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.base64.decode = function(input, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(input.length / 4) * 3);\n }\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n offset = offset || 0;\n var enc1, enc2, enc3, enc4;\n var i = 0, j = offset;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n out[j++] = (enc1 << 2) | (enc2 >> 4);\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);\n if(enc4 !== 64) {\n // decoded 3 bytes\n out[j++] = ((enc3 & 3) << 6) | enc4;\n }\n }\n }\n\n // make sure result is the exact decoded length\n return output ? (j - offset) : out.subarray(0, j);\n};\n\n// add support for base58 encoding/decoding with Bitcoin alphabet\nutil.binary.base58.encode = function(input, maxline) {\n return util.binary.baseN.encode(input, _base58, maxline);\n};\nutil.binary.base58.decode = function(input, maxline) {\n return util.binary.baseN.decode(input, _base58, maxline);\n};\n\n// text encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.text = {\n utf8: {},\n utf16: {}\n};\n\n/**\n * Encodes the given string as UTF-8 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf8.encode = function(str, output, offset) {\n str = util.encodeUtf8(str);\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-8 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf8.decode = function(bytes) {\n return util.decodeUtf8(String.fromCharCode.apply(null, bytes));\n};\n\n/**\n * Encodes the given string as UTF-16 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf16.encode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length * 2);\n }\n var view = new Uint16Array(out.buffer);\n offset = offset || 0;\n var j = offset;\n var k = offset;\n for(var i = 0; i < str.length; ++i) {\n view[k++] = str.charCodeAt(i);\n j += 2;\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-16 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf16.decode = function(bytes) {\n return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));\n};\n\n/**\n * Deflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true to return only raw deflate data, false to include zlib\n * header and trailer.\n *\n * @return the deflated data as a string.\n */\nutil.deflate = function(api, bytes, raw) {\n bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);\n\n // strip zlib header and trailer if necessary\n if(raw) {\n // zlib header is 2 bytes (CMF,FLG) where FLG indicates that\n // there is a 4-byte DICT (alder-32) block before the data if\n // its 5th bit is set\n var start = 2;\n var flg = bytes.charCodeAt(1);\n if(flg & 0x20) {\n start = 6;\n }\n // zlib trailer is 4 bytes of adler-32\n bytes = bytes.substring(start, bytes.length - 4);\n }\n\n return bytes;\n};\n\n/**\n * Inflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true if the incoming data has no zlib header or trailer and is\n * raw DEFLATE data.\n *\n * @return the inflated data as a string, null on error.\n */\nutil.inflate = function(api, bytes, raw) {\n // TODO: add zlib header and trailer if necessary/possible\n var rval = api.inflate(util.encode64(bytes)).rval;\n return (rval === null) ? null : util.decode64(rval);\n};\n\n/**\n * Sets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param obj the storage object, null to remove.\n */\nvar _setStorageObject = function(api, id, obj) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n var rval;\n if(obj === null) {\n rval = api.removeItem(id);\n } else {\n // json-encode and base64-encode object\n obj = util.encode64(JSON.stringify(obj));\n rval = api.setItem(id, obj);\n }\n\n // handle potential flash error\n if(typeof(rval) !== 'undefined' && rval.rval !== true) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n};\n\n/**\n * Gets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n *\n * @return the storage object entry or null if none exists.\n */\nvar _getStorageObject = function(api, id) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n // get the existing entry\n var rval = api.getItem(id);\n\n /* Note: We check api.init because we can't do (api == localStorage)\n on IE because of \"Class doesn't support Automation\" exception. Only\n the flash api has an init method so this works too, but we need a\n better solution in the future. */\n\n // flash returns item wrapped in an object, handle special case\n if(api.init) {\n if(rval.rval === null) {\n if(rval.error) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n // no error, but also no item\n rval = null;\n } else {\n rval = rval.rval;\n }\n }\n\n // handle decoding\n if(rval !== null) {\n // base64-decode and json-decode data\n rval = JSON.parse(util.decode64(rval));\n }\n\n return rval;\n};\n\n/**\n * Stores an item in local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n */\nvar _setItem = function(api, id, key, data) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj === null) {\n // create a new storage object\n obj = {};\n }\n // update key\n obj[key] = data;\n\n // set storage object\n _setStorageObject(api, id, obj);\n};\n\n/**\n * Gets an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n *\n * @return the item.\n */\nvar _getItem = function(api, id, key) {\n // get storage object\n var rval = _getStorageObject(api, id);\n if(rval !== null) {\n // return data at key\n rval = (key in rval) ? rval[key] : null;\n }\n\n return rval;\n};\n\n/**\n * Removes an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n */\nvar _removeItem = function(api, id, key) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj !== null && key in obj) {\n // remove key\n delete obj[key];\n\n // see if entry has no keys remaining\n var empty = true;\n for(var prop in obj) {\n empty = false;\n break;\n }\n if(empty) {\n // remove entry entirely if no keys are left\n obj = null;\n }\n\n // set storage object\n _setStorageObject(api, id, obj);\n }\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n */\nvar _clearItems = function(api, id) {\n _setStorageObject(api, id, null);\n};\n\n/**\n * Calls a storage function.\n *\n * @param func the function to call.\n * @param args the arguments for the function.\n * @param location the location argument.\n *\n * @return the return value from the function.\n */\nvar _callStorageFunction = function(func, args, location) {\n var rval = null;\n\n // default storage types\n if(typeof(location) === 'undefined') {\n location = ['web', 'flash'];\n }\n\n // apply storage types in order of preference\n var type;\n var done = false;\n var exception = null;\n for(var idx in location) {\n type = location[idx];\n try {\n if(type === 'flash' || type === 'both') {\n if(args[0] === null) {\n throw new Error('Flash local storage not available.');\n }\n rval = func.apply(this, args);\n done = (type === 'flash');\n }\n if(type === 'web' || type === 'both') {\n args[0] = localStorage;\n rval = func.apply(this, args);\n done = true;\n }\n } catch(ex) {\n exception = ex;\n }\n if(done) {\n break;\n }\n }\n\n if(!done) {\n throw exception;\n }\n\n return rval;\n};\n\n/**\n * Stores an item on local disk.\n *\n * The available types of local storage include 'flash', 'web', and 'both'.\n *\n * The type 'flash' refers to flash local storage (SharedObject). In order\n * to use flash local storage, the 'api' parameter must be valid. The type\n * 'web' refers to WebStorage, if supported by the browser. The type 'both'\n * refers to storing using both 'flash' and 'web', not just one or the\n * other.\n *\n * The location array should list the storage types to use in order of\n * preference:\n *\n * ['flash']: flash only storage\n * ['web']: web only storage\n * ['both']: try to store in both\n * ['flash','web']: store in flash first, but if not available, 'web'\n * ['web','flash']: store in web first, but if not available, 'flash'\n *\n * The location array defaults to: ['web', 'flash']\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n * @param location an array with the preferred types of storage to use.\n */\nutil.setItem = function(api, id, key, data, location) {\n _callStorageFunction(_setItem, arguments, location);\n};\n\n/**\n * Gets an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n *\n * @return the item.\n */\nutil.getItem = function(api, id, key, location) {\n return _callStorageFunction(_getItem, arguments, location);\n};\n\n/**\n * Removes an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n */\nutil.removeItem = function(api, id, key, location) {\n _callStorageFunction(_removeItem, arguments, location);\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface if flash is available.\n * @param id the storage ID to use.\n * @param location an array with the preferred types of storage to use.\n */\nutil.clearItems = function(api, id, location) {\n _callStorageFunction(_clearItems, arguments, location);\n};\n\n/**\n * Parses the scheme, host, and port from an http(s) url.\n *\n * @param str the url string.\n *\n * @return the parsed url object or null if the url is invalid.\n */\nutil.parseUrl = function(str) {\n // FIXME: this regex looks a bit broken\n var regex = /^(https?):\\/\\/([^:&^\\/]*):?(\\d*)(.*)$/g;\n regex.lastIndex = 0;\n var m = regex.exec(str);\n var url = (m === null) ? null : {\n full: str,\n scheme: m[1],\n host: m[2],\n port: m[3],\n path: m[4]\n };\n if(url) {\n url.fullHost = url.host;\n if(url.port) {\n if(url.port !== 80 && url.scheme === 'http') {\n url.fullHost += ':' + url.port;\n } else if(url.port !== 443 && url.scheme === 'https') {\n url.fullHost += ':' + url.port;\n }\n } else if(url.scheme === 'http') {\n url.port = 80;\n } else if(url.scheme === 'https') {\n url.port = 443;\n }\n url.full = url.scheme + '://' + url.fullHost;\n }\n return url;\n};\n\n/* Storage for query variables */\nvar _queryVariables = null;\n\n/**\n * Returns the window location query variables. Query is parsed on the first\n * call and the same object is returned on subsequent calls. The mapping\n * is from keys to an array of values. Parameters without values will have\n * an object key set but no value added to the value array. Values are\n * unescaped.\n *\n * ...?k1=v1&k2=v2:\n * {\n * \"k1\": [\"v1\"],\n * \"k2\": [\"v2\"]\n * }\n *\n * ...?k1=v1&k1=v2:\n * {\n * \"k1\": [\"v1\", \"v2\"]\n * }\n *\n * ...?k1=v1&k2:\n * {\n * \"k1\": [\"v1\"],\n * \"k2\": []\n * }\n *\n * ...?k1=v1&k1:\n * {\n * \"k1\": [\"v1\"]\n * }\n *\n * ...?k1&k1:\n * {\n * \"k1\": []\n * }\n *\n * @param query the query string to parse (optional, default to cached\n * results from parsing window location search query).\n *\n * @return object mapping keys to variables.\n */\nutil.getQueryVariables = function(query) {\n var parse = function(q) {\n var rval = {};\n var kvpairs = q.split('&');\n for(var i = 0; i < kvpairs.length; i++) {\n var pos = kvpairs[i].indexOf('=');\n var key;\n var val;\n if(pos > 0) {\n key = kvpairs[i].substring(0, pos);\n val = kvpairs[i].substring(pos + 1);\n } else {\n key = kvpairs[i];\n val = null;\n }\n if(!(key in rval)) {\n rval[key] = [];\n }\n // disallow overriding object prototype keys\n if(!(key in Object.prototype) && val !== null) {\n rval[key].push(unescape(val));\n }\n }\n return rval;\n };\n\n var rval;\n if(typeof(query) === 'undefined') {\n // set cached variables if needed\n if(_queryVariables === null) {\n if(typeof(window) !== 'undefined' && window.location && window.location.search) {\n // parse window search query\n _queryVariables = parse(window.location.search.substring(1));\n } else {\n // no query variables available\n _queryVariables = {};\n }\n }\n rval = _queryVariables;\n } else {\n // parse given query\n rval = parse(query);\n }\n return rval;\n};\n\n/**\n * Parses a fragment into a path and query. This method will take a URI\n * fragment and break it up as if it were the main URI. For example:\n * /bar/baz?a=1&b=2\n * results in:\n * {\n * path: [\"bar\", \"baz\"],\n * query: {\"k1\": [\"v1\"], \"k2\": [\"v2\"]}\n * }\n *\n * @return object with a path array and query object.\n */\nutil.parseFragment = function(fragment) {\n // default to whole fragment\n var fp = fragment;\n var fq = '';\n // split into path and query if possible at the first '?'\n var pos = fragment.indexOf('?');\n if(pos > 0) {\n fp = fragment.substring(0, pos);\n fq = fragment.substring(pos + 1);\n }\n // split path based on '/' and ignore first element if empty\n var path = fp.split('/');\n if(path.length > 0 && path[0] === '') {\n path.shift();\n }\n // convert query into object\n var query = (fq === '') ? {} : util.getQueryVariables(fq);\n\n return {\n pathString: fp,\n queryString: fq,\n path: path,\n query: query\n };\n};\n\n/**\n * Makes a request out of a URI-like request string. This is intended to\n * be used where a fragment id (after a URI '#') is parsed as a URI with\n * path and query parts. The string should have a path beginning and\n * delimited by '/' and optional query parameters following a '?'. The\n * query should be a standard URL set of key value pairs delimited by\n * '&'. For backwards compatibility the initial '/' on the path is not\n * required. The request object has the following API, (fully described\n * in the method code):\n * {\n * path: .\n * query: ,\n * getPath(i): get part or all of the split path array,\n * getQuery(k, i): get part or all of a query key array,\n * getQueryLast(k, _default): get last element of a query key array.\n * }\n *\n * @return object with request parameters.\n */\nutil.makeRequest = function(reqString) {\n var frag = util.parseFragment(reqString);\n var req = {\n // full path string\n path: frag.pathString,\n // full query string\n query: frag.queryString,\n /**\n * Get path or element in path.\n *\n * @param i optional path index.\n *\n * @return path or part of path if i provided.\n */\n getPath: function(i) {\n return (typeof(i) === 'undefined') ? frag.path : frag.path[i];\n },\n /**\n * Get query, values for a key, or value for a key index.\n *\n * @param k optional query key.\n * @param i optional query key index.\n *\n * @return query, values for a key, or value for a key index.\n */\n getQuery: function(k, i) {\n var rval;\n if(typeof(k) === 'undefined') {\n rval = frag.query;\n } else {\n rval = frag.query[k];\n if(rval && typeof(i) !== 'undefined') {\n rval = rval[i];\n }\n }\n return rval;\n },\n getQueryLast: function(k, _default) {\n var rval;\n var vals = req.getQuery(k);\n if(vals) {\n rval = vals[vals.length - 1];\n } else {\n rval = _default;\n }\n return rval;\n }\n };\n return req;\n};\n\n/**\n * Makes a URI out of a path, an object with query parameters, and a\n * fragment. Uses jQuery.param() internally for query string creation.\n * If the path is an array, it will be joined with '/'.\n *\n * @param path string path or array of strings.\n * @param query object with query parameters. (optional)\n * @param fragment fragment string. (optional)\n *\n * @return string object with request parameters.\n */\nutil.makeLink = function(path, query, fragment) {\n // join path parts if needed\n path = jQuery.isArray(path) ? path.join('/') : path;\n\n var qstr = jQuery.param(query || {});\n fragment = fragment || '';\n return path +\n ((qstr.length > 0) ? ('?' + qstr) : '') +\n ((fragment.length > 0) ? ('#' + fragment) : '');\n};\n\n/**\n * Check if an object is empty.\n *\n * Taken from:\n * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937\n *\n * @param object the object to check.\n */\nutil.isEmpty = function(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Format with simple printf-style interpolation.\n *\n * %%: literal '%'\n * %s,%o: convert next argument into a string.\n *\n * @param format the string to format.\n * @param ... arguments to interpolate into the format string.\n */\nutil.format = function(format) {\n var re = /%./g;\n // current match\n var match;\n // current part\n var part;\n // current arg index\n var argi = 0;\n // collected parts to recombine later\n var parts = [];\n // last index found\n var last = 0;\n // loop while matches remain\n while((match = re.exec(format))) {\n part = format.substring(last, re.lastIndex - 2);\n // don't add empty strings (ie, parts between %s%s)\n if(part.length > 0) {\n parts.push(part);\n }\n last = re.lastIndex;\n // switch on % code\n var code = match[0][1];\n switch(code) {\n case 's':\n case 'o':\n // check if enough arguments were given\n if(argi < arguments.length) {\n parts.push(arguments[argi++ + 1]);\n } else {\n parts.push('');\n }\n break;\n // FIXME: do proper formating for numbers, etc\n //case 'f':\n //case 'd':\n case '%':\n parts.push('%');\n break;\n default:\n parts.push('<%' + code + '?>');\n }\n }\n // add trailing part of format string\n parts.push(format.substring(last));\n return parts.join('');\n};\n\n/**\n * Formats a number.\n *\n * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/\n */\nutil.formatNumber = function(number, decimals, dec_point, thousands_sep) {\n // http://kevin.vanzonneveld.net\n // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n // + bugfix by: Michael White (http://crestidg.com)\n // + bugfix by: Benjamin Lupton\n // + bugfix by: Allan Jensen (http://www.winternet.no)\n // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // * example 1: number_format(1234.5678, 2, '.', '');\n // * returns 1: 1234.57\n\n var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;\n var d = dec_point === undefined ? ',' : dec_point;\n var t = thousands_sep === undefined ?\n '.' : thousands_sep, s = n < 0 ? '-' : '';\n var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';\n var j = (i.length > 3) ? i.length % 3 : 0;\n return s + (j ? i.substr(0, j) + t : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, '$1' + t) +\n (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');\n};\n\n/**\n * Formats a byte size.\n *\n * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/\n */\nutil.formatSize = function(size) {\n if(size >= 1073741824) {\n size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';\n } else if(size >= 1048576) {\n size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';\n } else if(size >= 1024) {\n size = util.formatNumber(size / 1024, 0) + ' KiB';\n } else {\n size = util.formatNumber(size, 0) + ' bytes';\n }\n return size;\n};\n\n/**\n * Converts an IPv4 or IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv4 or IPv6 address to convert.\n *\n * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't\n * be parsed.\n */\nutil.bytesFromIP = function(ip) {\n if(ip.indexOf('.') !== -1) {\n return util.bytesFromIPv4(ip);\n }\n if(ip.indexOf(':') !== -1) {\n return util.bytesFromIPv6(ip);\n }\n return null;\n};\n\n/**\n * Converts an IPv4 string representation into bytes (in network order).\n *\n * @param ip the IPv4 address to convert.\n *\n * @return the 4-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv4 = function(ip) {\n ip = ip.split('.');\n if(ip.length !== 4) {\n return null;\n }\n var b = util.createBuffer();\n for(var i = 0; i < ip.length; ++i) {\n var num = parseInt(ip[i], 10);\n if(isNaN(num)) {\n return null;\n }\n b.putByte(num);\n }\n return b.getBytes();\n};\n\n/**\n * Converts an IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv6 address to convert.\n *\n * @return the 16-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv6 = function(ip) {\n var blanks = 0;\n ip = ip.split(':').filter(function(e) {\n if(e.length === 0) ++blanks;\n return true;\n });\n var zeros = (8 - ip.length + blanks) * 2;\n var b = util.createBuffer();\n for(var i = 0; i < 8; ++i) {\n if(!ip[i] || ip[i].length === 0) {\n b.fillWithByte(0, zeros);\n zeros = 0;\n continue;\n }\n var bytes = util.hexToBytes(ip[i]);\n if(bytes.length < 2) {\n b.putByte(0);\n }\n b.putBytes(bytes);\n }\n return b.getBytes();\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation or 16-bytes into\n * an IPv6 string representation. The bytes must be in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,\n * respectively, are given, otherwise null.\n */\nutil.bytesToIP = function(bytes) {\n if(bytes.length === 4) {\n return util.bytesToIPv4(bytes);\n }\n if(bytes.length === 16) {\n return util.bytesToIPv6(bytes);\n }\n return null;\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv4 = function(bytes) {\n if(bytes.length !== 4) {\n return null;\n }\n var ip = [];\n for(var i = 0; i < bytes.length; ++i) {\n ip.push(bytes.charCodeAt(i));\n }\n return ip.join('.');\n};\n\n/**\n * Converts 16-bytes into an IPv16 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv16 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv6 = function(bytes) {\n if(bytes.length !== 16) {\n return null;\n }\n var ip = [];\n var zeroGroups = [];\n var zeroMaxGroup = 0;\n for(var i = 0; i < bytes.length; i += 2) {\n var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);\n // canonicalize zero representation\n while(hex[0] === '0' && hex !== '0') {\n hex = hex.substr(1);\n }\n if(hex === '0') {\n var last = zeroGroups[zeroGroups.length - 1];\n var idx = ip.length;\n if(!last || idx !== last.end + 1) {\n zeroGroups.push({start: idx, end: idx});\n } else {\n last.end = idx;\n if((last.end - last.start) >\n (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {\n zeroMaxGroup = zeroGroups.length - 1;\n }\n }\n }\n ip.push(hex);\n }\n if(zeroGroups.length > 0) {\n var group = zeroGroups[zeroMaxGroup];\n // only shorten group of length > 0\n if(group.end - group.start > 0) {\n ip.splice(group.start, group.end - group.start + 1, '');\n if(group.start === 0) {\n ip.unshift('');\n }\n if(group.end === 7) {\n ip.push('');\n }\n }\n }\n return ip.join(':');\n};\n\n/**\n * Estimates the number of processes that can be run concurrently. If\n * creating Web Workers, keep in mind that the main JavaScript process needs\n * its own core.\n *\n * @param options the options to use:\n * update true to force an update (not use the cached value).\n * @param callback(err, max) called once the operation completes.\n */\nutil.estimateCores = function(options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n if('cores' in util && !options.update) {\n return callback(null, util.cores);\n }\n if(typeof navigator !== 'undefined' &&\n 'hardwareConcurrency' in navigator &&\n navigator.hardwareConcurrency > 0) {\n util.cores = navigator.hardwareConcurrency;\n return callback(null, util.cores);\n }\n if(typeof Worker === 'undefined') {\n // workers not available\n util.cores = 1;\n return callback(null, util.cores);\n }\n if(typeof Blob === 'undefined') {\n // can't estimate, default to 2\n util.cores = 2;\n return callback(null, util.cores);\n }\n\n // create worker concurrency estimation code as blob\n var blobUrl = URL.createObjectURL(new Blob(['(',\n function() {\n self.addEventListener('message', function(e) {\n // run worker for 4 ms\n var st = Date.now();\n var et = st + 4;\n while(Date.now() < et);\n self.postMessage({st: st, et: et});\n });\n }.toString(),\n ')()'], {type: 'application/javascript'}));\n\n // take 5 samples using 16 workers\n sample([], 5, 16);\n\n function sample(max, samples, numWorkers) {\n if(samples === 0) {\n // get overlap average\n var avg = Math.floor(max.reduce(function(avg, x) {\n return avg + x;\n }, 0) / max.length);\n util.cores = Math.max(1, avg);\n URL.revokeObjectURL(blobUrl);\n return callback(null, util.cores);\n }\n map(numWorkers, function(err, results) {\n max.push(reduce(numWorkers, results));\n sample(max, samples - 1, numWorkers);\n });\n }\n\n function map(numWorkers, callback) {\n var workers = [];\n var results = [];\n for(var i = 0; i < numWorkers; ++i) {\n var worker = new Worker(blobUrl);\n worker.addEventListener('message', function(e) {\n results.push(e.data);\n if(results.length === numWorkers) {\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].terminate();\n }\n callback(null, results);\n }\n });\n workers.push(worker);\n }\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].postMessage(i);\n }\n }\n\n function reduce(numWorkers, results) {\n // find overlapping time windows\n var overlaps = [];\n for(var n = 0; n < numWorkers; ++n) {\n var r1 = results[n];\n var overlap = overlaps[n] = [];\n for(var i = 0; i < numWorkers; ++i) {\n if(n === i) {\n continue;\n }\n var r2 = results[i];\n if((r1.st > r2.st && r1.st < r2.et) ||\n (r2.st > r1.st && r2.st < r1.et)) {\n overlap.push(i);\n }\n }\n }\n // get maximum overlaps ... don't include overlapping worker itself\n // as the main JS process was also being scheduled during the work and\n // would have to be subtracted from the estimate anyway\n return overlaps.reduce(function(max, overlap) {\n return Math.max(max, overlap.length);\n }, 0);\n }\n};\n","/**\n * Cipher base API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nmodule.exports = forge.cipher = forge.cipher || {};\n\n// registered algorithms\nforge.cipher.algorithms = forge.cipher.algorithms || {};\n\n/**\n * Creates a cipher object that can be used to encrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createCipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: false\n });\n};\n\n/**\n * Creates a decipher object that can be used to decrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createDecipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: true\n });\n};\n\n/**\n * Registers an algorithm by name. If the name was already registered, the\n * algorithm API object will be overwritten.\n *\n * @param name the name of the algorithm.\n * @param algorithm the algorithm API object.\n */\nforge.cipher.registerAlgorithm = function(name, algorithm) {\n name = name.toUpperCase();\n forge.cipher.algorithms[name] = algorithm;\n};\n\n/**\n * Gets a registered algorithm by name.\n *\n * @param name the name of the algorithm.\n *\n * @return the algorithm, if found, null if not.\n */\nforge.cipher.getAlgorithm = function(name) {\n name = name.toUpperCase();\n if(name in forge.cipher.algorithms) {\n return forge.cipher.algorithms[name];\n }\n return null;\n};\n\nvar BlockCipher = forge.cipher.BlockCipher = function(options) {\n this.algorithm = options.algorithm;\n this.mode = this.algorithm.mode;\n this.blockSize = this.mode.blockSize;\n this._finish = false;\n this._input = null;\n this.output = null;\n this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;\n this._decrypt = options.decrypt;\n this.algorithm.initialize(options);\n};\n\n/**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array\n * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in\n * bytes, then it must be Nb (16) bytes in length. If the IV is given in as\n * 32-bit integers, then it must be 4 integers long.\n *\n * Note: an IV is not required or used in ECB mode.\n *\n * For GCM-mode, the IV must be given as a binary-encoded string of bytes or\n * a byte buffer. The number of bytes should be 12 (96 bits) as recommended\n * by NIST SP-800-38D but another length may be given.\n *\n * @param options the options to use:\n * iv the initialization vector to use as a binary-encoded string of\n * bytes, null to reuse the last ciphered block from a previous\n * update() (this \"residue\" method is for legacy support only).\n * additionalData additional authentication data as a binary-encoded\n * string of bytes, for 'GCM' mode, (default: none).\n * tagLength desired length of authentication tag, in bits, for\n * 'GCM' mode (0-128, default: 128).\n * tag the authentication tag to check if decrypting, as a\n * binary-encoded string of bytes.\n * output the output the buffer to write to, null to create one.\n */\nBlockCipher.prototype.start = function(options) {\n options = options || {};\n var opts = {};\n for(var key in options) {\n opts[key] = options[key];\n }\n opts.decrypt = this._decrypt;\n this._finish = false;\n this._input = forge.util.createBuffer();\n this.output = options.output || forge.util.createBuffer();\n this.mode.start(opts);\n};\n\n/**\n * Updates the next block according to the cipher mode.\n *\n * @param input the buffer to read from.\n */\nBlockCipher.prototype.update = function(input) {\n if(input) {\n // input given, so empty it into the input buffer\n this._input.putBuffer(input);\n }\n\n // do cipher operation until it needs more input and not finished\n while(!this._op.call(this.mode, this._input, this.output, this._finish) &&\n !this._finish) {}\n\n // free consumed memory from input buffer\n this._input.compact();\n};\n\n/**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use in CBC mode, null for default,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\nBlockCipher.prototype.finish = function(pad) {\n // backwards-compatibility w/deprecated padding API\n // Note: will overwrite padding functions even after another start() call\n if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {\n this.mode.pad = function(input) {\n return pad(this.blockSize, input, false);\n };\n this.mode.unpad = function(output) {\n return pad(this.blockSize, output, true);\n };\n }\n\n // build options for padding and afterFinish functions\n var options = {};\n options.decrypt = this._decrypt;\n\n // get # of bytes that won't fill a block\n options.overflow = this._input.length() % this.blockSize;\n\n if(!this._decrypt && this.mode.pad) {\n if(!this.mode.pad(this._input, options)) {\n return false;\n }\n }\n\n // do final update\n this._finish = true;\n this.update();\n\n if(this._decrypt && this.mode.unpad) {\n if(!this.mode.unpad(this.output, options)) {\n return false;\n }\n }\n\n if(this.mode.afterFinish) {\n if(!this.mode.afterFinish(this.output, options)) {\n return false;\n }\n }\n\n return true;\n};\n","/**\n * Supported cipher modes.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.cipher = forge.cipher || {};\n\n// supported cipher modes\nvar modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};\n\n/** Electronic codebook (ECB) (Don't use this; it's not secure) **/\n\nmodes.ecb = function(options) {\n options = options || {};\n this.name = 'ECB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.ecb.prototype.start = function(options) {};\n\nmodes.ecb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.ecb.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher-block Chaining (CBC) **/\n\nmodes.cbc = function(options) {\n options = options || {};\n this.name = 'CBC';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.cbc.prototype.start = function(options) {\n // Note: legacy support for using IV residue (has security flaws)\n // if IV is null, reuse block from previous processing\n if(options.iv === null) {\n // must have a previous block\n if(!this._prev) {\n throw new Error('Invalid IV parameter.');\n }\n this._iv = this._prev.slice(0);\n } else if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n } else {\n // save IV as \"previous\" block\n this._iv = transformIV(options.iv, this.blockSize);\n this._prev = this._iv.slice(0);\n }\n};\n\nmodes.cbc.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n // CBC XOR's IV (or previous block) with plaintext\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._prev[i] ^ input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output, save previous block\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n this._prev = this._outBlock;\n};\n\nmodes.cbc.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output, save previous ciphered block\n // CBC XOR's IV (or previous block) with ciphertext\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._prev[i] ^ this._outBlock[i]);\n }\n this._prev = this._inBlock.slice(0);\n};\n\nmodes.cbc.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.cbc.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher feedback (CFB) **/\n\nmodes.cfb = function(options) {\n options = options || {};\n this.name = 'CFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32() ^ this._outBlock[i];\n output.putInt32(this._inBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];\n this._partialOutput.putInt32(this._partialBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n output.putInt32(this._inBlock[i] ^ this._outBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32();\n this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\n/** Output feedback (OFB) **/\n\nmodes.ofb = function(options) {\n options = options || {};\n this.name = 'OFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(input.length() === 0) {\n return true;\n }\n\n // encrypt block (OFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output and update next input\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n this._inBlock[i] = this._outBlock[i];\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._outBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;\n\n/** Counter (CTR) **/\n\nmodes.ctr = function(options) {\n options = options || {};\n this.name = 'CTR';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CTR always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // block complete, increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;\n\n/** Galois/Counter Mode (GCM) **/\n\nmodes.gcm = function(options) {\n options = options || {};\n this.name = 'GCM';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n\n // R is actually this value concatenated with 120 more zero bits, but\n // we only XOR against R so the other zeros have no effect -- we just\n // apply this value to the first integer in a block\n this._R = 0xE1000000;\n};\n\nmodes.gcm.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // ensure IV is a byte buffer\n var iv = forge.util.createBuffer(options.iv);\n\n // no ciphered data processed yet\n this._cipherLength = 0;\n\n // default additional data is none\n var additionalData;\n if('additionalData' in options) {\n additionalData = forge.util.createBuffer(options.additionalData);\n } else {\n additionalData = forge.util.createBuffer();\n }\n\n // default tag length is 128 bits\n if('tagLength' in options) {\n this._tagLength = options.tagLength;\n } else {\n this._tagLength = 128;\n }\n\n // if tag is given, ensure tag matches tag length\n this._tag = null;\n if(options.decrypt) {\n // save tag to check later\n this._tag = forge.util.createBuffer(options.tag).getBytes();\n if(this._tag.length !== (this._tagLength / 8)) {\n throw new Error('Authentication tag does not match tag length.');\n }\n }\n\n // create tmp storage for hash calculation\n this._hashBlock = new Array(this._ints);\n\n // no tag generated yet\n this.tag = null;\n\n // generate hash subkey\n // (apply block cipher to \"zero\" block)\n this._hashSubkey = new Array(this._ints);\n this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);\n\n // generate table M\n // use 4-bit tables (32 component decomposition of a 16 byte value)\n // 8-bit tables take more space and are known to have security\n // vulnerabilities (in native implementations)\n this.componentBits = 4;\n this._m = this.generateHashTable(this._hashSubkey, this.componentBits);\n\n // Note: support IV length different from 96 bits? (only supporting\n // 96 bits is recommended by NIST SP-800-38D)\n // generate J_0\n var ivLength = iv.length();\n if(ivLength === 12) {\n // 96-bit IV\n this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];\n } else {\n // IV is NOT 96-bits\n this._j0 = [0, 0, 0, 0];\n while(iv.length() > 0) {\n this._j0 = this.ghash(\n this._hashSubkey, this._j0,\n [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);\n }\n this._j0 = this.ghash(\n this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));\n }\n\n // generate ICB (initial counter block)\n this._inBlock = this._j0.slice(0);\n inc32(this._inBlock);\n this._partialBytes = 0;\n\n // consume authentication data\n additionalData = forge.util.createBuffer(additionalData);\n // save additional data length as a BE 64-bit number\n this._aDataLength = from64To32(additionalData.length() * 8);\n // pad additional data to 128 bit (16 byte) block size\n var overflow = additionalData.length() % this.blockSize;\n if(overflow) {\n additionalData.fillWithByte(0, this.blockSize - overflow);\n }\n this._s = [0, 0, 0, 0];\n while(additionalData.length() > 0) {\n this._s = this.ghash(this._hashSubkey, this._s, [\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32()\n ]);\n }\n};\n\nmodes.gcm.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^= input.getInt32());\n }\n this._cipherLength += this.blockSize;\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes <= 0 || finish) {\n // handle overflow prior to hashing\n if(finish) {\n // get block overflow\n var overflow = inputLength % this.blockSize;\n this._cipherLength += overflow;\n // truncate for hash function\n this._partialOutput.truncate(this.blockSize - overflow);\n } else {\n this._cipherLength += this.blockSize;\n }\n\n // get output block for hashing\n for(var i = 0; i < this._ints; ++i) {\n this._outBlock[i] = this._partialOutput.getInt32();\n }\n this._partialOutput.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n // block still incomplete, restore input buffer, get partial output,\n // and return early\n input.read -= this.blockSize;\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // update hash block S\n this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.gcm.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength < this.blockSize && !(finish && inputLength > 0)) {\n return true;\n }\n\n // encrypt block (GCM always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n\n // update hash block S\n this._hashBlock[0] = input.getInt32();\n this._hashBlock[1] = input.getInt32();\n this._hashBlock[2] = input.getInt32();\n this._hashBlock[3] = input.getInt32();\n this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);\n\n // XOR hash input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);\n }\n\n // increment cipher data length\n if(inputLength < this.blockSize) {\n this._cipherLength += inputLength % this.blockSize;\n } else {\n this._cipherLength += this.blockSize;\n }\n};\n\nmodes.gcm.prototype.afterFinish = function(output, options) {\n var rval = true;\n\n // handle overflow\n if(options.decrypt && options.overflow) {\n output.truncate(this.blockSize - options.overflow);\n }\n\n // handle authentication tag\n this.tag = forge.util.createBuffer();\n\n // concatenate additional data length with cipher length\n var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));\n\n // include lengths in hash\n this._s = this.ghash(this._hashSubkey, this._s, lengths);\n\n // do GCTR(J_0, S)\n var tag = [];\n this.cipher.encrypt(this._j0, tag);\n for(var i = 0; i < this._ints; ++i) {\n this.tag.putInt32(this._s[i] ^ tag[i]);\n }\n\n // trim tag to length\n this.tag.truncate(this.tag.length() % (this._tagLength / 8));\n\n // check authentication tag\n if(options.decrypt && this.tag.bytes() !== this._tag) {\n rval = false;\n }\n\n return rval;\n};\n\n/**\n * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois\n * field multiplication. The field, GF(2^128), is defined by the polynomial:\n *\n * x^128 + x^7 + x^2 + x + 1\n *\n * Which is represented in little-endian binary form as: 11100001 (0xe1). When\n * the value of a coefficient is 1, a bit is set. The value R, is the\n * concatenation of this value and 120 zero bits, yielding a 128-bit value\n * which matches the block size.\n *\n * This function will multiply two elements (vectors of bytes), X and Y, in\n * the field GF(2^128). The result is initialized to zero. For each bit of\n * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)\n * by the current value of Y. For each bit, the value of Y will be raised by\n * a power of x (multiplied by the polynomial x). This can be achieved by\n * shifting Y once to the right. If the current value of Y, prior to being\n * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.\n * Otherwise, we must divide by R after shifting to find the remainder.\n *\n * @param x the first block to multiply by the second.\n * @param y the second block to multiply by the first.\n *\n * @return the block result of the multiplication.\n */\nmodes.gcm.prototype.multiply = function(x, y) {\n var z_i = [0, 0, 0, 0];\n var v_i = y.slice(0);\n\n // calculate Z_128 (block has 128 bits)\n for(var i = 0; i < 128; ++i) {\n // if x_i is 0, Z_{i+1} = Z_i (unchanged)\n // else Z_{i+1} = Z_i ^ V_i\n // get x_i by finding 32-bit int position, then left shift 1 by remainder\n var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));\n if(x_i) {\n z_i[0] ^= v_i[0];\n z_i[1] ^= v_i[1];\n z_i[2] ^= v_i[2];\n z_i[3] ^= v_i[3];\n }\n\n // if LSB(V_i) is 1, V_i = V_i >> 1\n // else V_i = (V_i >> 1) ^ R\n this.pow(v_i, v_i);\n }\n\n return z_i;\n};\n\nmodes.gcm.prototype.pow = function(x, out) {\n // if LSB(x) is 1, x = x >>> 1\n // else x = (x >>> 1) ^ R\n var lsb = x[3] & 1;\n\n // always do x >>> 1:\n // starting with the rightmost integer, shift each integer to the right\n // one bit, pulling in the bit from the integer to the left as its top\n // most bit (do this for the last 3 integers)\n for(var i = 3; i > 0; --i) {\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);\n }\n // shift the first integer normally\n out[0] = x[0] >>> 1;\n\n // if lsb was not set, then polynomial had a degree of 127 and doesn't\n // need to divided; otherwise, XOR with R to find the remainder; we only\n // need to XOR the first integer since R technically ends w/120 zero bits\n if(lsb) {\n out[0] ^= this._R;\n }\n};\n\nmodes.gcm.prototype.tableMultiply = function(x) {\n // assumes 4-bit tables are used\n var z = [0, 0, 0, 0];\n for(var i = 0; i < 32; ++i) {\n var idx = (i / 8) | 0;\n var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;\n var ah = this._m[i][x_i];\n z[0] ^= ah[0];\n z[1] ^= ah[1];\n z[2] ^= ah[2];\n z[3] ^= ah[3];\n }\n return z;\n};\n\n/**\n * A continuing version of the GHASH algorithm that operates on a single\n * block. The hash block, last hash value (Ym) and the new block to hash\n * are given.\n *\n * @param h the hash block.\n * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.\n * @param x the block to hash.\n *\n * @return the hashed value (Ym).\n */\nmodes.gcm.prototype.ghash = function(h, y, x) {\n y[0] ^= x[0];\n y[1] ^= x[1];\n y[2] ^= x[2];\n y[3] ^= x[3];\n return this.tableMultiply(y);\n //return this.multiply(y, h);\n};\n\n/**\n * Precomputes a table for multiplying against the hash subkey. This\n * mechanism provides a substantial speed increase over multiplication\n * performed without a table. The table-based multiplication this table is\n * for solves X * H by multiplying each component of X by H and then\n * composing the results together using XOR.\n *\n * This function can be used to generate tables with different bit sizes\n * for the components, however, this implementation assumes there are\n * 32 components of X (which is a 16 byte vector), therefore each component\n * takes 4-bits (so the table is constructed with bits=4).\n *\n * @param h the hash subkey.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateHashTable = function(h, bits) {\n // TODO: There are further optimizations that would use only the\n // first table M_0 (or some variant) along with a remainder table;\n // this can be explored in the future\n var multiplier = 8 / bits;\n var perInt = 4 * multiplier;\n var size = 16 * multiplier;\n var m = new Array(size);\n for(var i = 0; i < size; ++i) {\n var tmp = [0, 0, 0, 0];\n var idx = (i / perInt) | 0;\n var shft = ((perInt - 1 - (i % perInt)) * bits);\n tmp[idx] = (1 << (bits - 1)) << shft;\n m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);\n }\n return m;\n};\n\n/**\n * Generates a table for multiplying against the hash subkey for one\n * particular component (out of all possible component values).\n *\n * @param mid the pre-multiplied value for the middle key of the table.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateSubHashTable = function(mid, bits) {\n // compute the table quickly by minimizing the number of\n // POW operations -- they only need to be performed for powers of 2,\n // all other entries can be composed from those powers using XOR\n var size = 1 << bits;\n var half = size >>> 1;\n var m = new Array(size);\n m[half] = mid.slice(0);\n var i = half >>> 1;\n while(i > 0) {\n // raise m0[2 * i] and store in m0[i]\n this.pow(m[2 * i], m[i] = []);\n i >>= 1;\n }\n i = 2;\n while(i < half) {\n for(var j = 1; j < i; ++j) {\n var m_i = m[i];\n var m_j = m[j];\n m[i + j] = [\n m_i[0] ^ m_j[0],\n m_i[1] ^ m_j[1],\n m_i[2] ^ m_j[2],\n m_i[3] ^ m_j[3]\n ];\n }\n i *= 2;\n }\n m[0] = [0, 0, 0, 0];\n /* Note: We could avoid storing these by doing composition during multiply\n calculate top half using composition by speed is preferred. */\n for(i = half + 1; i < size; ++i) {\n var c = m[i ^ half];\n m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];\n }\n return m;\n};\n\n/** Utility functions */\n\nfunction transformIV(iv, blockSize) {\n if(typeof iv === 'string') {\n // convert iv string into byte buffer\n iv = forge.util.createBuffer(iv);\n }\n\n if(forge.util.isArray(iv) && iv.length > 4) {\n // convert iv byte array into byte buffer\n var tmp = iv;\n iv = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n iv.putByte(tmp[i]);\n }\n }\n\n if(iv.length() < blockSize) {\n throw new Error(\n 'Invalid IV length; got ' + iv.length() +\n ' bytes and expected ' + blockSize + ' bytes.');\n }\n\n if(!forge.util.isArray(iv)) {\n // convert iv byte buffer into 32-bit integer array\n var ints = [];\n var blocks = blockSize / 4;\n for(var i = 0; i < blocks; ++i) {\n ints.push(iv.getInt32());\n }\n iv = ints;\n }\n\n return iv;\n}\n\nfunction inc32(block) {\n // increment last 32 bits of block only\n block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;\n}\n\nfunction from64To32(num) {\n // convert 64-bit number to two BE Int32s\n return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];\n}\n","/**\n * Advanced Encryption Standard (AES) implementation.\n *\n * This implementation is based on the public domain library 'jscrypto' which\n * was written by:\n *\n * Emily Stark (estark@stanford.edu)\n * Mike Hamburg (mhamburg@stanford.edu)\n * Dan Boneh (dabo@cs.stanford.edu)\n *\n * Parts of this code are based on the OpenSSL implementation of AES:\n * http://www.openssl.org\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* AES API */\nmodule.exports = forge.aes = forge.aes || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new AES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the AES algorithm object.\n */\nforge.aes.Algorithm = function(name, mode) {\n if(!init) {\n initialize();\n }\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 16,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this AES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.aes.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = options.key;\n var tmp;\n\n /* Note: The key may be a string of bytes, an array of bytes, a byte\n buffer, or an array of 32-bit integers. If the key is in bytes, then\n it must be 16, 24, or 32 bytes in length. If it is in 32-bit\n integers, it must be 4, 6, or 8 integers long. */\n\n if(typeof key === 'string' &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key) &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key integer array into byte buffer\n tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // convert key byte buffer into 32-bit integer array\n if(!forge.util.isArray(key)) {\n tmp = key;\n key = [];\n\n // key lengths of 16, 24, 32 bytes allowed\n var len = tmp.length();\n if(len === 16 || len === 24 || len === 32) {\n len = len >>> 2;\n for(var i = 0; i < len; ++i) {\n key.push(tmp.getInt32());\n }\n }\n }\n\n // key must be an array of 32-bit integers by now\n if(!forge.util.isArray(key) ||\n !(key.length === 4 || key.length === 6 || key.length === 8)) {\n throw new Error('Invalid key parameter.');\n }\n\n // encryption operation is always used for these modes\n var mode = this.mode.name;\n var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);\n\n // do key expansion\n this._w = _expandKey(key, options.decrypt && !encryptOp);\n this._init = true;\n};\n\n/**\n * Expands a key. Typically only used for testing.\n *\n * @param key the symmetric key to expand, as an array of 32-bit words.\n * @param decrypt true to expand for decryption, false for encryption.\n *\n * @return the expanded key.\n */\nforge.aes._expandKey = function(key, decrypt) {\n if(!init) {\n initialize();\n }\n return _expandKey(key, decrypt);\n};\n\n/**\n * Updates a single block. Typically only used for testing.\n *\n * @param w the expanded key to use.\n * @param input an array of block-size 32-bit words.\n * @param output an array of block-size 32-bit words.\n * @param decrypt true to decrypt, false to encrypt.\n */\nforge.aes._updateBlock = _updateBlock;\n\n/** Register AES algorithms **/\n\nregisterAlgorithm('AES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('AES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('AES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('AES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('AES-CTR', forge.cipher.modes.ctr);\nregisterAlgorithm('AES-GCM', forge.cipher.modes.gcm);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.aes.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** AES implementation **/\n\nvar init = false; // not yet initialized\nvar Nb = 4; // number of words comprising the state (AES = 4)\nvar sbox; // non-linear substitution table used in key expansion\nvar isbox; // inversion of sbox\nvar rcon; // round constant word array\nvar mix; // mix-columns table\nvar imix; // inverse mix-columns table\n\n/**\n * Performs initialization, ie: precomputes tables to optimize for speed.\n *\n * One way to understand how AES works is to imagine that 'addition' and\n * 'multiplication' are interfaces that require certain mathematical\n * properties to hold true (ie: they are associative) but they might have\n * different implementations and produce different kinds of results ...\n * provided that their mathematical properties remain true. AES defines\n * its own methods of addition and multiplication but keeps some important\n * properties the same, ie: associativity and distributivity. The\n * explanation below tries to shed some light on how AES defines addition\n * and multiplication of bytes and 32-bit words in order to perform its\n * encryption and decryption algorithms.\n *\n * The basics:\n *\n * The AES algorithm views bytes as binary representations of polynomials\n * that have either 1 or 0 as the coefficients. It defines the addition\n * or subtraction of two bytes as the XOR operation. It also defines the\n * multiplication of two bytes as a finite field referred to as GF(2^8)\n * (Note: 'GF' means \"Galois Field\" which is a field that contains a finite\n * number of elements so GF(2^8) has 256 elements).\n *\n * This means that any two bytes can be represented as binary polynomials;\n * when they multiplied together and modularly reduced by an irreducible\n * polynomial of the 8th degree, the results are the field GF(2^8). The\n * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.\n * This multiplication is associative with 0x01 as the identity:\n *\n * (b * 0x01 = GF(b, 0x01) = b).\n *\n * The operation GF(b, 0x02) can be performed at the byte level by left\n * shifting b once and then XOR'ing it (to perform the modular reduction)\n * with 0x11b if b is >= 128. Repeated application of the multiplication\n * of 0x02 can be used to implement the multiplication of any two bytes.\n *\n * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can\n * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these\n * factors can each be multiplied by 0x57 and then added together. To do\n * the multiplication, values for 0x57 multiplied by each of these 3 factors\n * can be precomputed and stored in a table. To add them, the values from\n * the table are XOR'd together.\n *\n * AES also defines addition and multiplication of words, that is 4-byte\n * numbers represented as polynomials of 3 degrees where the coefficients\n * are the values of the bytes.\n *\n * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.\n *\n * Addition is performed by XOR'ing like powers of x. Multiplication\n * is performed in two steps, the first is an algebriac expansion as\n * you would do normally (where addition is XOR). But the result is\n * a polynomial larger than 3 degrees and thus it cannot fit in a word. So\n * next the result is modularly reduced by an AES-specific polynomial of\n * degree 4 which will always produce a polynomial of less than 4 degrees\n * such that it will fit in a word. In AES, this polynomial is x^4 + 1.\n *\n * The modular product of two polynomials 'a' and 'b' is thus:\n *\n * d(x) = d3x^3 + d2x^2 + d1x + d0\n * with\n * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)\n * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)\n * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)\n * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)\n *\n * As a matrix:\n *\n * [d0] = [a0 a3 a2 a1][b0]\n * [d1] [a1 a0 a3 a2][b1]\n * [d2] [a2 a1 a0 a3][b2]\n * [d3] [a3 a2 a1 a0][b3]\n *\n * Special polynomials defined by AES (0x02 == {02}):\n * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}\n * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.\n *\n * These polynomials are used in the MixColumns() and InverseMixColumns()\n * operations, respectively, to cause each element in the state to affect\n * the output (referred to as diffusing).\n *\n * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the\n * polynomial x3.\n *\n * The ShiftRows() method modifies the last 3 rows in the state (where\n * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.\n * The 1st byte in the second row is moved to the end of the row. The 1st\n * and 2nd bytes in the third row are moved to the end of the row. The 1st,\n * 2nd, and 3rd bytes are moved in the fourth row.\n *\n * More details on how AES arithmetic works:\n *\n * In the polynomial representation of binary numbers, XOR performs addition\n * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)\n * corresponds with the multiplication of polynomials modulo an irreducible\n * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply\n * polynomial 'a' with polynomial 'b' and then do a modular reduction by\n * an AES-specific irreducible polynomial of degree 8.\n *\n * A polynomial is irreducible if its only divisors are one and itself. For\n * the AES algorithm, this irreducible polynomial is:\n *\n * m(x) = x^8 + x^4 + x^3 + x + 1,\n *\n * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:\n * 100011011 = 283 = 0x11b.\n *\n * For example, GF(0x57, 0x83) = 0xc1 because\n *\n * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1\n * 0x85 = 131 = 10000101 = x^7 + x + 1\n *\n * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)\n * = x^13 + x^11 + x^9 + x^8 + x^7 +\n * x^7 + x^5 + x^3 + x^2 + x +\n * x^6 + x^4 + x^2 + x + 1\n * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y\n * y modulo (x^8 + x^4 + x^3 + x + 1)\n * = x^7 + x^6 + 1.\n *\n * The modular reduction by m(x) guarantees the result will be a binary\n * polynomial of less than degree 8, so that it can fit in a byte.\n *\n * The operation to multiply a binary polynomial b with x (the polynomial\n * x in binary representation is 00000010) is:\n *\n * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1\n *\n * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the\n * most significant bit is 0 in b) then the result is already reduced. If\n * it is 1, then we can reduce it by subtracting m(x) via an XOR.\n *\n * It follows that multiplication by x (00000010 or 0x02) can be implemented\n * by performing a left shift followed by a conditional bitwise XOR with\n * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by\n * higher powers of x can be implemented by repeated application of xtime().\n *\n * By adding intermediate results, multiplication by any constant can be\n * implemented. For instance:\n *\n * GF(0x57, 0x13) = 0xfe because:\n *\n * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)\n *\n * Note: We XOR with 0x11b instead of 0x1b because in javascript our\n * datatype for b can be larger than 1 byte, so a left shift will not\n * automatically eliminate bits that overflow a byte ... by XOR'ing the\n * overflow bit with 1 (the extra one from 0x11b) we zero it out.\n *\n * GF(0x57, 0x02) = xtime(0x57) = 0xae\n * GF(0x57, 0x04) = xtime(0xae) = 0x47\n * GF(0x57, 0x08) = xtime(0x47) = 0x8e\n * GF(0x57, 0x10) = xtime(0x8e) = 0x07\n *\n * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))\n *\n * And by the distributive property (since XOR is addition and GF() is\n * multiplication):\n *\n * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)\n * = 0x57 ^ 0xae ^ 0x07\n * = 0xfe.\n */\nfunction initialize() {\n init = true;\n\n /* Populate the Rcon table. These are the values given by\n [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)\n in the field of GF(2^8), where i starts at 1.\n\n rcon[0] = [0x00, 0x00, 0x00, 0x00]\n rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1\n rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2\n ...\n rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B\n rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36\n\n We only store the first byte because it is the only one used.\n */\n rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];\n\n // compute xtime table which maps i onto GF(i, 0x02)\n var xtime = new Array(256);\n for(var i = 0; i < 128; ++i) {\n xtime[i] = i << 1;\n xtime[i + 128] = (i + 128) << 1 ^ 0x11B;\n }\n\n // compute all other tables\n sbox = new Array(256);\n isbox = new Array(256);\n mix = new Array(4);\n imix = new Array(4);\n for(var i = 0; i < 4; ++i) {\n mix[i] = new Array(256);\n imix[i] = new Array(256);\n }\n var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;\n for(var i = 0; i < 256; ++i) {\n /* We need to generate the SubBytes() sbox and isbox tables so that\n we can perform byte substitutions. This requires us to traverse\n all of the elements in GF, find their multiplicative inverses,\n and apply to each the following affine transformation:\n\n bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^\n b(i + 7) mod 8 ^ ci\n for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the\n ith bit of a byte c with the value {63} or {01100011}.\n\n It is possible to traverse every possible value in a Galois field\n using what is referred to as a 'generator'. There are many\n generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully\n traverse GF we iterate 255 times, multiplying by our generator\n each time.\n\n On each iteration we can determine the multiplicative inverse for\n the current element.\n\n Suppose there is an element in GF 'e'. For a given generator 'g',\n e = g^x. The multiplicative inverse of e is g^(255 - x). It turns\n out that if use the inverse of a generator as another generator\n it will produce all of the corresponding multiplicative inverses\n at the same time. For this reason, we choose 5 as our inverse\n generator because it only requires 2 multiplies and 1 add and its\n inverse, 82, requires relatively few operations as well.\n\n In order to apply the affine transformation, the multiplicative\n inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a\n bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and\n 'x'. Then 's' is left shifted and the high bit of 's' is made the\n low bit. The resulting value is stored in 's'. Then 'x' is XOR'd\n with 's' and stored in 'x'. On each subsequent iteration the same\n operation is performed. When 4 iterations are complete, 'x' is\n XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.\n For example:\n\n s = 01000001\n x = 01000001\n\n iteration 1: s = 10000010, x ^= s\n iteration 2: s = 00000101, x ^= s\n iteration 3: s = 00001010, x ^= s\n iteration 4: s = 00010100, x ^= s\n x ^= 0x63\n\n This can be done with a loop where s = (s << 1) | (s >> 7). However,\n it can also be done by using a single 16-bit (in this case 32-bit)\n number 'sx'. Since XOR is an associative operation, we can set 'sx'\n to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.\n The most significant bits will flow into the high 8 bit positions\n and be correctly XOR'd with one another. All that remains will be\n to cycle the high 8 bits by XOR'ing them all with the lower 8 bits\n afterwards.\n\n At the same time we're populating sbox and isbox we can precompute\n the multiplication we'll need to do to do MixColumns() later.\n */\n\n // apply affine transformation\n sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);\n sx = (sx >> 8) ^ (sx & 255) ^ 0x63;\n\n // update tables\n sbox[e] = sx;\n isbox[sx] = e;\n\n /* Mixing columns is done using matrix multiplication. The columns\n that are to be mixed are each a single word in the current state.\n The state has Nb columns (4 columns). Therefore each column is a\n 4 byte word. So to mix the columns in a single column 'c' where\n its rows are r0, r1, r2, and r3, we use the following matrix\n multiplication:\n\n [2 3 1 1]*[r0,c]=[r'0,c]\n [1 2 3 1] [r1,c] [r'1,c]\n [1 1 2 3] [r2,c] [r'2,c]\n [3 1 1 2] [r3,c] [r'3,c]\n\n r0, r1, r2, and r3 are each 1 byte of one of the words in the\n state (a column). To do matrix multiplication for each mixed\n column c' we multiply the corresponding row from the left matrix\n with the corresponding column from the right matrix. In total, we\n get 4 equations:\n\n r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c\n r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c\n r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c\n r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c\n\n As usual, the multiplication is as previously defined and the\n addition is XOR. In order to optimize mixing columns we can store\n the multiplication results in tables. If you think of the whole\n column as a word (it might help to visualize by mentally rotating\n the equations above by counterclockwise 90 degrees) then you can\n see that it would be useful to map the multiplications performed on\n each byte (r0, r1, r2, r3) onto a word as well. For instance, we\n could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the\n highest 8 bits and 3*r0 in the lowest 8 bits (with the other two\n respectively in the middle). This means that a table can be\n constructed that uses r0 as an index to the word. We can do the\n same with r1, r2, and r3, creating a total of 4 tables.\n\n To construct a full c', we can just look up each byte of c in\n their respective tables and XOR the results together.\n\n Also, to build each table we only have to calculate the word\n for 2,1,1,3 for every byte ... which we can do on each iteration\n of this loop since we will iterate over every byte. After we have\n calculated 2,1,1,3 we can get the results for the other tables\n by cycling the byte at the end to the beginning. For instance\n we can take the result of table 2,1,1,3 and produce table 3,2,1,1\n by moving the right most byte to the left most position just like\n how you can imagine the 3 moved out of 2,1,1,3 and to the front\n to produce 3,2,1,1.\n\n There is another optimization in that the same multiples of\n the current element we need in order to advance our generator\n to the next iteration can be reused in performing the 2,1,1,3\n calculation. We also calculate the inverse mix column tables,\n with e,9,d,b being the inverse of 2,1,1,3.\n\n When we're done, and we need to actually mix columns, the first\n byte of each state word should be put through mix[0] (2,1,1,3),\n the second through mix[1] (3,2,1,1) and so forth. Then they should\n be XOR'd together to produce the fully mixed column.\n */\n\n // calculate mix and imix table values\n sx2 = xtime[sx];\n e2 = xtime[e];\n e4 = xtime[e2];\n e8 = xtime[e4];\n me =\n (sx2 << 24) ^ // 2\n (sx << 16) ^ // 1\n (sx << 8) ^ // 1\n (sx ^ sx2); // 3\n ime =\n (e2 ^ e4 ^ e8) << 24 ^ // E (14)\n (e ^ e8) << 16 ^ // 9\n (e ^ e4 ^ e8) << 8 ^ // D (13)\n (e ^ e2 ^ e8); // B (11)\n // produce each of the mix tables by rotating the 2,1,1,3 value\n for(var n = 0; n < 4; ++n) {\n mix[n][e] = me;\n imix[n][sx] = ime;\n // cycle the right most byte to the left most position\n // ie: 2,1,1,3 becomes 3,2,1,1\n me = me << 24 | me >>> 8;\n ime = ime << 24 | ime >>> 8;\n }\n\n // get next element and inverse\n if(e === 0) {\n // 1 is the inverse of 1\n e = ei = 1;\n } else {\n // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)\n // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)\n e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];\n ei ^= xtime[xtime[ei]];\n }\n }\n}\n\n/**\n * Generates a key schedule using the AES key expansion algorithm.\n *\n * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion\n * routine to generate a key schedule. The Key Expansion generates a total\n * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,\n * and each of the Nr rounds requires Nb words of key data. The resulting\n * key schedule consists of a linear array of 4-byte words, denoted [wi ],\n * with i in the range 0 <= i < Nb(Nr + 1).\n *\n * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)\n * AES-128 (Nb=4, Nk=4, Nr=10)\n * AES-192 (Nb=4, Nk=6, Nr=12)\n * AES-256 (Nb=4, Nk=8, Nr=14)\n * Note: Nr=Nk+6.\n *\n * Nb is the number of columns (32-bit words) comprising the State (or\n * number of bytes in a block). For AES, Nb=4.\n *\n * @param key the key to schedule (as an array of 32-bit words).\n * @param decrypt true to modify the key schedule to decrypt, false not to.\n *\n * @return the generated key schedule.\n */\nfunction _expandKey(key, decrypt) {\n // copy the key's words to initialize the key schedule\n var w = key.slice(0);\n\n /* RotWord() will rotate a word, moving the first byte to the last\n byte's position (shifting the other bytes left).\n\n We will be getting the value of Rcon at i / Nk. 'i' will iterate\n from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in\n a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from\n 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will\n increase by 1. We use a counter iNk to keep track of this.\n */\n\n // go through the rounds expanding the key\n var temp, iNk = 1;\n var Nk = w.length;\n var Nr1 = Nk + 6 + 1;\n var end = Nb * Nr1;\n for(var i = Nk; i < end; ++i) {\n temp = w[i - 1];\n if(i % Nk === 0) {\n // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]\n temp =\n sbox[temp >>> 16 & 255] << 24 ^\n sbox[temp >>> 8 & 255] << 16 ^\n sbox[temp & 255] << 8 ^\n sbox[temp >>> 24] ^ (rcon[iNk] << 24);\n iNk++;\n } else if(Nk > 6 && (i % Nk === 4)) {\n // temp = SubWord(temp)\n temp =\n sbox[temp >>> 24] << 24 ^\n sbox[temp >>> 16 & 255] << 16 ^\n sbox[temp >>> 8 & 255] << 8 ^\n sbox[temp & 255];\n }\n w[i] = w[i - Nk] ^ temp;\n }\n\n /* When we are updating a cipher block we always use the code path for\n encryption whether we are decrypting or not (to shorten code and\n simplify the generation of look up tables). However, because there\n are differences in the decryption algorithm, other than just swapping\n in different look up tables, we must transform our key schedule to\n account for these changes:\n\n 1. The decryption algorithm gets its key rounds in reverse order.\n 2. The decryption algorithm adds the round key before mixing columns\n instead of afterwards.\n\n We don't need to modify our key schedule to handle the first case,\n we can just traverse the key schedule in reverse order when decrypting.\n\n The second case requires a little work.\n\n The tables we built for performing rounds will take an input and then\n perform SubBytes() and MixColumns() or, for the decrypt version,\n InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires\n us to AddRoundKey() before InvMixColumns(). This means we'll need to\n apply some transformations to the round key to inverse-mix its columns\n so they'll be correct for moving AddRoundKey() to after the state has\n had its columns inverse-mixed.\n\n To inverse-mix the columns of the state when we're decrypting we use a\n lookup table that will apply InvSubBytes() and InvMixColumns() at the\n same time. However, the round key's bytes are not inverse-substituted\n in the decryption algorithm. To get around this problem, we can first\n substitute the bytes in the round key so that when we apply the\n transformation via the InvSubBytes()+InvMixColumns() table, it will\n undo our substitution leaving us with the original value that we\n want -- and then inverse-mix that value.\n\n This change will correctly alter our key schedule so that we can XOR\n each round key with our already transformed decryption state. This\n allows us to use the same code path as the encryption algorithm.\n\n We make one more change to the decryption key. Since the decryption\n algorithm runs in reverse from the encryption algorithm, we reverse\n the order of the round keys to avoid having to iterate over the key\n schedule backwards when running the encryption algorithm later in\n decryption mode. In addition to reversing the order of the round keys,\n we also swap each round key's 2nd and 4th rows. See the comments\n section where rounds are performed for more details about why this is\n done. These changes are done inline with the other substitution\n described above.\n */\n if(decrypt) {\n var tmp;\n var m0 = imix[0];\n var m1 = imix[1];\n var m2 = imix[2];\n var m3 = imix[3];\n var wnew = w.slice(0);\n end = w.length;\n for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {\n // do not sub the first or last round key (round keys are Nb\n // words) as no column mixing is performed before they are added,\n // but do change the key order\n if(i === 0 || i === (end - Nb)) {\n wnew[i] = w[wi];\n wnew[i + 1] = w[wi + 3];\n wnew[i + 2] = w[wi + 2];\n wnew[i + 3] = w[wi + 1];\n } else {\n // substitute each round key byte because the inverse-mix\n // table will inverse-substitute it (effectively cancel the\n // substitution because round key bytes aren't sub'd in\n // decryption mode) and swap indexes 3 and 1\n for(var n = 0; n < Nb; ++n) {\n tmp = w[wi + n];\n wnew[i + (3&-n)] =\n m0[sbox[tmp >>> 24]] ^\n m1[sbox[tmp >>> 16 & 255]] ^\n m2[sbox[tmp >>> 8 & 255]] ^\n m3[sbox[tmp & 255]];\n }\n }\n }\n w = wnew;\n }\n\n return w;\n}\n\n/**\n * Updates a single block (16 bytes) using AES. The update will either\n * encrypt or decrypt the block.\n *\n * @param w the key schedule.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(w, input, output, decrypt) {\n /*\n Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[0, Nb-1])\n for round = 1 step 1 to Nr-1\n SubBytes(state)\n ShiftRows(state)\n MixColumns(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n end for\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n out = state\n end\n\n InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n for round = Nr-1 step -1 downto 1\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n InvMixColumns(state)\n end for\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n out = state\n end\n */\n\n // Encrypt: AddRoundKey(state, w[0, Nb-1])\n // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n var Nr = w.length / 4 - 1;\n var m0, m1, m2, m3, sub;\n if(decrypt) {\n m0 = imix[0];\n m1 = imix[1];\n m2 = imix[2];\n m3 = imix[3];\n sub = isbox;\n } else {\n m0 = mix[0];\n m1 = mix[1];\n m2 = mix[2];\n m3 = mix[3];\n sub = sbox;\n }\n var a, b, c, d, a2, b2, c2;\n a = input[0] ^ w[0];\n b = input[decrypt ? 3 : 1] ^ w[1];\n c = input[2] ^ w[2];\n d = input[decrypt ? 1 : 3] ^ w[3];\n var i = 3;\n\n /* In order to share code we follow the encryption algorithm when both\n encrypting and decrypting. To account for the changes required in the\n decryption algorithm, we use different lookup tables when decrypting\n and use a modified key schedule to account for the difference in the\n order of transformations applied when performing rounds. We also get\n key rounds in reverse order (relative to encryption). */\n for(var round = 1; round < Nr; ++round) {\n /* As described above, we'll be using table lookups to perform the\n column mixing. Each column is stored as a word in the state (the\n array 'input' has one column as a word at each index). In order to\n mix a column, we perform these transformations on each row in c,\n which is 1 byte in each word. The new column for c0 is c'0:\n\n m0 m1 m2 m3\n r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0\n r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0\n r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0\n r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0\n\n So using mix tables where c0 is a word with r0 being its upper\n 8 bits and r3 being its lower 8 bits:\n\n m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]\n ...\n m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]\n\n Therefore to mix the columns in each word in the state we\n do the following (& 255 omitted for brevity):\n c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n\n However, before mixing, the algorithm requires us to perform\n ShiftRows(). The ShiftRows() transformation cyclically shifts the\n last 3 rows of the state over different offsets. The first row\n (r = 0) is not shifted.\n\n s'_r,c = s_r,(c + shift(r, Nb) mod Nb\n for 0 < r < 4 and 0 <= c < Nb and\n shift(1, 4) = 1\n shift(2, 4) = 2\n shift(3, 4) = 3.\n\n This causes the first byte in r = 1 to be moved to the end of\n the row, the first 2 bytes in r = 2 to be moved to the end of\n the row, the first 3 bytes in r = 3 to be moved to the end of\n the row:\n\n r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]\n r2: [c0 c1 c2 c3] [c2 c3 c0 c1]\n r3: [c0 c1 c2 c3] [c3 c0 c1 c2]\n\n We can make these substitutions inline with our column mixing to\n generate an updated set of equations to produce each word in the\n state (note the columns have changed positions):\n\n c0 c1 c2 c3 => c0 c1 c2 c3\n c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)\n c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)\n c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)\n\n Therefore:\n\n c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3\n c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3\n\n c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0\n c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0\n\n ... and so forth for c'2 and c'3. The important distinction is\n that the columns are cycling, with c0 being used with the m0\n map when calculating c0, but c1 being used with the m0 map when\n calculating c1 ... and so forth.\n\n When performing the inverse we transform the mirror image and\n skip the bottom row, instead of the top one, and move upwards:\n\n c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption\n c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)\n c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption\n c3 c2 c1 c0 c3 c2 c1 c0\n\n If you compare the resulting matrices for ShiftRows()+MixColumns()\n and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are\n different (in encrypt mode vs. decrypt mode). So in order to use\n the same code to handle both encryption and decryption, we will\n need to do some mapping.\n\n If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be\n a row number in the state, then the resulting matrix in encryption\n mode for applying the above transformations would be:\n\n r1: a b c d\n r2: b c d a\n r3: c d a b\n r4: d a b c\n\n If we did the same in decryption mode we would get:\n\n r1: a d c b\n r2: b a d c\n r3: c b a d\n r4: d c b a\n\n If instead we swap d and b (set b=c3 and d=c1), then we get:\n\n r1: a b c d\n r2: d a b c\n r3: c d a b\n r4: b c d a\n\n Now the 1st and 3rd rows are the same as the encryption matrix. All\n we need to do then to make the mapping exactly the same is to swap\n the 2nd and 4th rows when in decryption mode. To do this without\n having to do it on each iteration, we swapped the 2nd and 4th rows\n in the decryption key schedule. We also have to do the swap above\n when we first pull in the input and when we set the final output. */\n a2 =\n m0[a >>> 24] ^\n m1[b >>> 16 & 255] ^\n m2[c >>> 8 & 255] ^\n m3[d & 255] ^ w[++i];\n b2 =\n m0[b >>> 24] ^\n m1[c >>> 16 & 255] ^\n m2[d >>> 8 & 255] ^\n m3[a & 255] ^ w[++i];\n c2 =\n m0[c >>> 24] ^\n m1[d >>> 16 & 255] ^\n m2[a >>> 8 & 255] ^\n m3[b & 255] ^ w[++i];\n d =\n m0[d >>> 24] ^\n m1[a >>> 16 & 255] ^\n m2[b >>> 8 & 255] ^\n m3[c & 255] ^ w[++i];\n a = a2;\n b = b2;\n c = c2;\n }\n\n /*\n Encrypt:\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n\n Decrypt:\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n */\n // Note: rows are shifted inline\n output[0] =\n (sub[a >>> 24] << 24) ^\n (sub[b >>> 16 & 255] << 16) ^\n (sub[c >>> 8 & 255] << 8) ^\n (sub[d & 255]) ^ w[++i];\n output[decrypt ? 3 : 1] =\n (sub[b >>> 24] << 24) ^\n (sub[c >>> 16 & 255] << 16) ^\n (sub[d >>> 8 & 255] << 8) ^\n (sub[a & 255]) ^ w[++i];\n output[2] =\n (sub[c >>> 24] << 24) ^\n (sub[d >>> 16 & 255] << 16) ^\n (sub[a >>> 8 & 255] << 8) ^\n (sub[b & 255]) ^ w[++i];\n output[decrypt ? 1 : 3] =\n (sub[d >>> 24] << 24) ^\n (sub[a >>> 16 & 255] << 16) ^\n (sub[b >>> 8 & 255] << 8) ^\n (sub[c & 255]) ^ w[++i];\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('AES-', key);\n * forge.cipher.createDecipher('AES-', key);\n *\n * Creates a deprecated AES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key and iv may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param options the options to use.\n * key the symmetric key to use.\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'AES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * Object IDs for ASN.1.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nforge.pki = forge.pki || {};\nvar oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {};\n\n// set id to name mapping and name to id mapping\nfunction _IN(id, name) {\n oids[id] = name;\n oids[name] = id;\n}\n// set id to name mapping only\nfunction _I_(id, name) {\n oids[id] = name;\n}\n\n// algorithm OIDs\n_IN('1.2.840.113549.1.1.1', 'rsaEncryption');\n// Note: md2 & md4 not implemented\n//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');\n//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');\n_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');\n_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');\n_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');\n_IN('1.2.840.113549.1.1.8', 'mgf1');\n_IN('1.2.840.113549.1.1.9', 'pSpecified');\n_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');\n_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');\n_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');\n_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');\n// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519\n_IN('1.3.101.112', 'EdDSA25519');\n\n_IN('1.2.840.10040.4.3', 'dsa-with-sha1');\n\n_IN('1.3.14.3.2.7', 'desCBC');\n\n_IN('1.3.14.3.2.26', 'sha1');\n_IN('2.16.840.1.101.3.4.2.1', 'sha256');\n_IN('2.16.840.1.101.3.4.2.2', 'sha384');\n_IN('2.16.840.1.101.3.4.2.3', 'sha512');\n_IN('1.2.840.113549.2.5', 'md5');\n\n// pkcs#7 content types\n_IN('1.2.840.113549.1.7.1', 'data');\n_IN('1.2.840.113549.1.7.2', 'signedData');\n_IN('1.2.840.113549.1.7.3', 'envelopedData');\n_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');\n_IN('1.2.840.113549.1.7.5', 'digestedData');\n_IN('1.2.840.113549.1.7.6', 'encryptedData');\n\n// pkcs#9 oids\n_IN('1.2.840.113549.1.9.1', 'emailAddress');\n_IN('1.2.840.113549.1.9.2', 'unstructuredName');\n_IN('1.2.840.113549.1.9.3', 'contentType');\n_IN('1.2.840.113549.1.9.4', 'messageDigest');\n_IN('1.2.840.113549.1.9.5', 'signingTime');\n_IN('1.2.840.113549.1.9.6', 'counterSignature');\n_IN('1.2.840.113549.1.9.7', 'challengePassword');\n_IN('1.2.840.113549.1.9.8', 'unstructuredAddress');\n_IN('1.2.840.113549.1.9.14', 'extensionRequest');\n\n_IN('1.2.840.113549.1.9.20', 'friendlyName');\n_IN('1.2.840.113549.1.9.21', 'localKeyId');\n_IN('1.2.840.113549.1.9.22.1', 'x509Certificate');\n\n// pkcs#12 safe bags\n_IN('1.2.840.113549.1.12.10.1.1', 'keyBag');\n_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');\n_IN('1.2.840.113549.1.12.10.1.3', 'certBag');\n_IN('1.2.840.113549.1.12.10.1.4', 'crlBag');\n_IN('1.2.840.113549.1.12.10.1.5', 'secretBag');\n_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');\n\n// password-based-encryption for pkcs#12\n_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');\n_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');\n\n_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');\n_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');\n_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');\n_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');\n\n// hmac OIDs\n_IN('1.2.840.113549.2.7', 'hmacWithSHA1');\n_IN('1.2.840.113549.2.8', 'hmacWithSHA224');\n_IN('1.2.840.113549.2.9', 'hmacWithSHA256');\n_IN('1.2.840.113549.2.10', 'hmacWithSHA384');\n_IN('1.2.840.113549.2.11', 'hmacWithSHA512');\n\n// symmetric key algorithm oids\n_IN('1.2.840.113549.3.7', 'des-EDE3-CBC');\n_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');\n_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');\n_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');\n\n// certificate issuer/subject OIDs\n_IN('2.5.4.3', 'commonName');\n_IN('2.5.4.5', 'serialName');\n_IN('2.5.4.6', 'countryName');\n_IN('2.5.4.7', 'localityName');\n_IN('2.5.4.8', 'stateOrProvinceName');\n_IN('2.5.4.9', 'streetAddress');\n_IN('2.5.4.10', 'organizationName');\n_IN('2.5.4.11', 'organizationalUnitName');\n_IN('2.5.4.13', 'description');\n_IN('2.5.4.15', 'businessCategory');\n_IN('2.5.4.17', 'postalCode');\n_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');\n_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');\n\n// X.509 extension OIDs\n_IN('2.16.840.1.113730.1.1', 'nsCertType');\n_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used\n_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35\n_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15\n_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32\n_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15\n_I_('2.5.29.5', 'policyMapping'); // deprecated use .33\n_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30\n_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17\n_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18\n_I_('2.5.29.9', 'subjectDirectoryAttributes');\n_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19\n_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30\n_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36\n_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19\n_IN('2.5.29.14', 'subjectKeyIdentifier');\n_IN('2.5.29.15', 'keyUsage');\n_I_('2.5.29.16', 'privateKeyUsagePeriod');\n_IN('2.5.29.17', 'subjectAltName');\n_IN('2.5.29.18', 'issuerAltName');\n_IN('2.5.29.19', 'basicConstraints');\n_I_('2.5.29.20', 'cRLNumber');\n_I_('2.5.29.21', 'cRLReason');\n_I_('2.5.29.22', 'expirationDate');\n_I_('2.5.29.23', 'instructionCode');\n_I_('2.5.29.24', 'invalidityDate');\n_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31\n_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28\n_I_('2.5.29.27', 'deltaCRLIndicator');\n_I_('2.5.29.28', 'issuingDistributionPoint');\n_I_('2.5.29.29', 'certificateIssuer');\n_I_('2.5.29.30', 'nameConstraints');\n_IN('2.5.29.31', 'cRLDistributionPoints');\n_IN('2.5.29.32', 'certificatePolicies');\n_I_('2.5.29.33', 'policyMappings');\n_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36\n_IN('2.5.29.35', 'authorityKeyIdentifier');\n_I_('2.5.29.36', 'policyConstraints');\n_IN('2.5.29.37', 'extKeyUsage');\n_I_('2.5.29.46', 'freshestCRL');\n_I_('2.5.29.54', 'inhibitAnyPolicy');\n\n// extKeyUsage purposes\n_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');\n_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');\n_IN('1.3.6.1.5.5.7.3.1', 'serverAuth');\n_IN('1.3.6.1.5.5.7.3.2', 'clientAuth');\n_IN('1.3.6.1.5.5.7.3.3', 'codeSigning');\n_IN('1.3.6.1.5.5.7.3.4', 'emailProtection');\n_IN('1.3.6.1.5.5.7.3.8', 'timeStamping');\n","/**\n * Javascript implementation of Abstract Syntax Notation Number One.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n *\n * An API for storing data using the Abstract Syntax Notation Number One\n * format using DER (Distinguished Encoding Rules) encoding. This encoding is\n * commonly used to store data for PKI, i.e. X.509 Certificates, and this\n * implementation exists for that purpose.\n *\n * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract\n * syntax of information without restricting the way the information is encoded\n * for transmission. It provides a standard that allows for open systems\n * communication. ASN.1 defines the syntax of information data and a number of\n * simple data types as well as a notation for describing them and specifying\n * values for them.\n *\n * The RSA algorithm creates public and private keys that are often stored in\n * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This\n * class provides the most basic functionality required to store and load DSA\n * keys that are encoded according to ASN.1.\n *\n * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)\n * and DER (Distinguished Encoding Rules). DER is just a subset of BER that\n * has stricter requirements for how data must be encoded.\n *\n * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)\n * and a byte array for the value of this ASN1 structure which may be data or a\n * list of ASN.1 structures.\n *\n * Each ASN.1 structure using BER is (Tag-Length-Value):\n *\n * | byte 0 | bytes X | bytes Y |\n * |--------|---------|----------\n * | tag | length | value |\n *\n * ASN.1 allows for tags to be of \"High-tag-number form\" which allows a tag to\n * be two or more octets, but that is not supported by this class. A tag is\n * only 1 byte. Bits 1-5 give the tag number (ie the data type within a\n * particular 'class'), 6 indicates whether or not the ASN.1 value is\n * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If\n * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,\n * then the class is APPLICATION. If only bit 8 is set, then the class is\n * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.\n * The tag numbers for the data types for the class UNIVERSAL are listed below:\n *\n * UNIVERSAL 0 Reserved for use by the encoding rules\n * UNIVERSAL 1 Boolean type\n * UNIVERSAL 2 Integer type\n * UNIVERSAL 3 Bitstring type\n * UNIVERSAL 4 Octetstring type\n * UNIVERSAL 5 Null type\n * UNIVERSAL 6 Object identifier type\n * UNIVERSAL 7 Object descriptor type\n * UNIVERSAL 8 External type and Instance-of type\n * UNIVERSAL 9 Real type\n * UNIVERSAL 10 Enumerated type\n * UNIVERSAL 11 Embedded-pdv type\n * UNIVERSAL 12 UTF8String type\n * UNIVERSAL 13 Relative object identifier type\n * UNIVERSAL 14-15 Reserved for future editions\n * UNIVERSAL 16 Sequence and Sequence-of types\n * UNIVERSAL 17 Set and Set-of types\n * UNIVERSAL 18-22, 25-30 Character string types\n * UNIVERSAL 23-24 Time types\n *\n * The length of an ASN.1 structure is specified after the tag identifier.\n * There is a definite form and an indefinite form. The indefinite form may\n * be used if the encoding is constructed and not all immediately available.\n * The indefinite form is encoded using a length byte with only the 8th bit\n * set. The end of the constructed object is marked using end-of-contents\n * octets (two zero bytes).\n *\n * The definite form looks like this:\n *\n * The length may take up 1 or more bytes, it depends on the length of the\n * value of the ASN.1 structure. DER encoding requires that if the ASN.1\n * structure has a value that has a length greater than 127, more than 1 byte\n * will be used to store its length, otherwise just one byte will be used.\n * This is strict.\n *\n * In the case that the length of the ASN.1 value is less than 127, 1 octet\n * (byte) is used to store the \"short form\" length. The 8th bit has a value of\n * 0 indicating the length is \"short form\" and not \"long form\" and bits 7-1\n * give the length of the data. (The 8th bit is the left-most, most significant\n * bit: also known as big endian or network format).\n *\n * In the case that the length of the ASN.1 value is greater than 127, 2 to\n * 127 octets (bytes) are used to store the \"long form\" length. The first\n * byte's 8th bit is set to 1 to indicate the length is \"long form.\" Bits 7-1\n * give the number of additional octets. All following octets are in base 256\n * with the most significant digit first (typical big-endian binary unsigned\n * integer storage). So, for instance, if the length of a value was 257, the\n * first byte would be set to:\n *\n * 10000010 = 130 = 0x82.\n *\n * This indicates there are 2 octets (base 256) for the length. The second and\n * third bytes (the octets just mentioned) would store the length in base 256:\n *\n * octet 2: 00000001 = 1 * 256^1 = 256\n * octet 3: 00000001 = 1 * 256^0 = 1\n * total = 257\n *\n * The algorithm for converting a js integer value of 257 to base-256 is:\n *\n * var value = 257;\n * var bytes = [];\n * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first\n * bytes[1] = value & 0xFF; // least significant byte last\n *\n * On the ASN.1 UNIVERSAL Object Identifier (OID) type:\n *\n * An OID can be written like: \"value1.value2.value3...valueN\"\n *\n * The DER encoding rules:\n *\n * The first byte has the value 40 * value1 + value2.\n * The following bytes, if any, encode the remaining values. Each value is\n * encoded in base 128, most significant digit first (big endian), with as\n * few digits as possible, and the most significant bit of each byte set\n * to 1 except the last in each value's encoding. For example: Given the\n * OID \"1.2.840.113549\", its DER encoding is (remember each byte except the\n * last one in each encoding is OR'd with 0x80):\n *\n * byte 1: 40 * 1 + 2 = 42 = 0x2A.\n * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648\n * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D\n *\n * The final value is: 0x2A864886F70D.\n * The full OID (including ASN.1 tag and length of 6 bytes) is:\n * 0x06062A864886F70D\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./oids');\n\n/* ASN.1 API */\nvar asn1 = module.exports = forge.asn1 = forge.asn1 || {};\n\n/**\n * ASN.1 classes.\n */\nasn1.Class = {\n UNIVERSAL: 0x00,\n APPLICATION: 0x40,\n CONTEXT_SPECIFIC: 0x80,\n PRIVATE: 0xC0\n};\n\n/**\n * ASN.1 types. Not all types are supported by this implementation, only\n * those necessary to implement a simple PKI are implemented.\n */\nasn1.Type = {\n NONE: 0,\n BOOLEAN: 1,\n INTEGER: 2,\n BITSTRING: 3,\n OCTETSTRING: 4,\n NULL: 5,\n OID: 6,\n ODESC: 7,\n EXTERNAL: 8,\n REAL: 9,\n ENUMERATED: 10,\n EMBEDDED: 11,\n UTF8: 12,\n ROID: 13,\n SEQUENCE: 16,\n SET: 17,\n PRINTABLESTRING: 19,\n IA5STRING: 22,\n UTCTIME: 23,\n GENERALIZEDTIME: 24,\n BMPSTRING: 30\n};\n\n/**\n * Creates a new asn1 object.\n *\n * @param tagClass the tag class for the object.\n * @param type the data type (tag number) for the object.\n * @param constructed true if the asn1 object is in constructed form.\n * @param value the value for the object, if it is not constructed.\n * @param [options] the options to use:\n * [bitStringContents] the plain BIT STRING content including padding\n * byte.\n *\n * @return the asn1 object.\n */\nasn1.create = function(tagClass, type, constructed, value, options) {\n /* An asn1 object has a tagClass, a type, a constructed flag, and a\n value. The value's type depends on the constructed flag. If\n constructed, it will contain a list of other asn1 objects. If not,\n it will contain the ASN.1 value as an array of bytes formatted\n according to the ASN.1 data type. */\n\n // remove undefined values\n if(forge.util.isArray(value)) {\n var tmp = [];\n for(var i = 0; i < value.length; ++i) {\n if(value[i] !== undefined) {\n tmp.push(value[i]);\n }\n }\n value = tmp;\n }\n\n var obj = {\n tagClass: tagClass,\n type: type,\n constructed: constructed,\n composed: constructed || forge.util.isArray(value),\n value: value\n };\n if(options && 'bitStringContents' in options) {\n // TODO: copy byte buffer if it's a buffer not a string\n obj.bitStringContents = options.bitStringContents;\n // TODO: add readonly flag to avoid this overhead\n // save copy to detect changes\n obj.original = asn1.copy(obj);\n }\n return obj;\n};\n\n/**\n * Copies an asn1 object.\n *\n * @param obj the asn1 object.\n * @param [options] copy options:\n * [excludeBitStringContents] true to not copy bitStringContents\n *\n * @return the a copy of the asn1 object.\n */\nasn1.copy = function(obj, options) {\n var copy;\n\n if(forge.util.isArray(obj)) {\n copy = [];\n for(var i = 0; i < obj.length; ++i) {\n copy.push(asn1.copy(obj[i], options));\n }\n return copy;\n }\n\n if(typeof obj === 'string') {\n // TODO: copy byte buffer if it's a buffer not a string\n return obj;\n }\n\n copy = {\n tagClass: obj.tagClass,\n type: obj.type,\n constructed: obj.constructed,\n composed: obj.composed,\n value: asn1.copy(obj.value, options)\n };\n if(options && !options.excludeBitStringContents) {\n // TODO: copy byte buffer if it's a buffer not a string\n copy.bitStringContents = obj.bitStringContents;\n }\n return copy;\n};\n\n/**\n * Compares asn1 objects for equality.\n *\n * Note this function does not run in constant time.\n *\n * @param obj1 the first asn1 object.\n * @param obj2 the second asn1 object.\n * @param [options] compare options:\n * [includeBitStringContents] true to compare bitStringContents\n *\n * @return true if the asn1 objects are equal.\n */\nasn1.equals = function(obj1, obj2, options) {\n if(forge.util.isArray(obj1)) {\n if(!forge.util.isArray(obj2)) {\n return false;\n }\n if(obj1.length !== obj2.length) {\n return false;\n }\n for(var i = 0; i < obj1.length; ++i) {\n if(!asn1.equals(obj1[i], obj2[i])) {\n return false;\n }\n }\n return true;\n }\n\n if(typeof obj1 !== typeof obj2) {\n return false;\n }\n\n if(typeof obj1 === 'string') {\n return obj1 === obj2;\n }\n\n var equal = obj1.tagClass === obj2.tagClass &&\n obj1.type === obj2.type &&\n obj1.constructed === obj2.constructed &&\n obj1.composed === obj2.composed &&\n asn1.equals(obj1.value, obj2.value);\n if(options && options.includeBitStringContents) {\n equal = equal && (obj1.bitStringContents === obj2.bitStringContents);\n }\n\n return equal;\n};\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param b the BER-encoded ASN.1 byte buffer, starting with the first\n * length byte.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nasn1.getBerValueLength = function(b) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n var b2 = b.getByte();\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n length = b.getInt((b2 & 0x7F) << 3);\n }\n return length;\n};\n\n/**\n * Check if the byte buffer has enough bytes. Throws an Error if not.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n * @param n the number of bytes the buffer must have.\n */\nfunction _checkBufferLength(bytes, remaining, n) {\n if(n > remaining) {\n var error = new Error('Too few bytes to parse DER.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = n;\n throw error;\n }\n}\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nvar _getValueLength = function(bytes, remaining) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n // fromDer already checked that this byte exists\n var b2 = bytes.getByte();\n remaining--;\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n var longFormBytes = b2 & 0x7F;\n _checkBufferLength(bytes, remaining, longFormBytes);\n length = bytes.getInt(longFormBytes << 3);\n }\n // FIXME: this will only happen for 32 bit getInt with high bit set\n if(length < 0) {\n throw new Error('Negative length: ' + length);\n }\n return length;\n};\n\n/**\n * Parses an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * @param [options] object with options or boolean strict flag\n * [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * [decodeBitStrings] true to attempt to decode the content of\n * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that\n * without schema support to understand the data context this can\n * erroneously decode values that happen to be valid ASN.1. This\n * flag will be deprecated or removed as soon as schema support is\n * available. (default: true)\n *\n * @return the parsed asn1 object.\n */\nasn1.fromDer = function(bytes, options) {\n if(options === undefined) {\n options = {\n strict: true,\n decodeBitStrings: true\n };\n }\n if(typeof options === 'boolean') {\n options = {\n strict: options,\n decodeBitStrings: true\n };\n }\n if(!('strict' in options)) {\n options.strict = true;\n }\n if(!('decodeBitStrings' in options)) {\n options.decodeBitStrings = true;\n }\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n return _fromDer(bytes, bytes.length(), 0, options);\n};\n\n/**\n * Internal function to parse an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the number of bytes remaining for this chunk.\n * @param depth the current parsing depth.\n * @param options object with same options as fromDer().\n *\n * @return the parsed asn1 object.\n */\nfunction _fromDer(bytes, remaining, depth, options) {\n // temporary storage for consumption calculations\n var start;\n\n // minimum length for ASN.1 DER structure is 2\n _checkBufferLength(bytes, remaining, 2);\n\n // get the first byte\n var b1 = bytes.getByte();\n // consumed one byte\n remaining--;\n\n // get the tag class\n var tagClass = (b1 & 0xC0);\n\n // get the type (bits 1-5)\n var type = b1 & 0x1F;\n\n // get the variable value length and adjust remaining bytes\n start = bytes.length();\n var length = _getValueLength(bytes, remaining);\n remaining -= start - bytes.length();\n\n // ensure there are enough bytes to get the value\n if(length !== undefined && length > remaining) {\n if(options.strict) {\n var error = new Error('Too few bytes to read ASN.1 value.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = length;\n throw error;\n }\n // Note: be lenient with truncated values and use remaining state bytes\n length = remaining;\n }\n\n // value storage\n var value;\n // possible BIT STRING contents storage\n var bitStringContents;\n\n // constructed flag is bit 6 (32 = 0x20) of the first byte\n var constructed = ((b1 & 0x20) === 0x20);\n if(constructed) {\n // parse child asn1 objects from the value\n value = [];\n if(length === undefined) {\n // asn1 object of indefinite length, read until end tag\n for(;;) {\n _checkBufferLength(bytes, remaining, 2);\n if(bytes.bytes(2) === String.fromCharCode(0, 0)) {\n bytes.getBytes(2);\n remaining -= 2;\n break;\n }\n start = bytes.length();\n value.push(_fromDer(bytes, remaining, depth + 1, options));\n remaining -= start - bytes.length();\n }\n } else {\n // parsing asn1 object of definite length\n while(length > 0) {\n start = bytes.length();\n value.push(_fromDer(bytes, length, depth + 1, options));\n remaining -= start - bytes.length();\n length -= start - bytes.length();\n }\n }\n }\n\n // if a BIT STRING, save the contents including padding\n if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&\n type === asn1.Type.BITSTRING) {\n bitStringContents = bytes.bytes(length);\n }\n\n // determine if a non-constructed value should be decoded as a composed\n // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)\n // can be used this way.\n if(value === undefined && options.decodeBitStrings &&\n tagClass === asn1.Class.UNIVERSAL &&\n // FIXME: OCTET STRINGs not yet supported here\n // .. other parts of forge expect to decode OCTET STRINGs manually\n (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&\n length > 1) {\n // save read position\n var savedRead = bytes.read;\n var savedRemaining = remaining;\n var unused = 0;\n if(type === asn1.Type.BITSTRING) {\n /* The first octet gives the number of bits by which the length of the\n bit string is less than the next multiple of eight (this is called\n the \"number of unused bits\").\n\n The second and following octets give the value of the bit string\n converted to an octet string. */\n _checkBufferLength(bytes, remaining, 1);\n unused = bytes.getByte();\n remaining--;\n }\n // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs\n if(unused === 0) {\n try {\n // attempt to parse child asn1 object from the value\n // (stored in array to signal composed value)\n start = bytes.length();\n var subOptions = {\n // enforce strict mode to avoid parsing ASN.1 from plain data\n verbose: options.verbose,\n strict: true,\n decodeBitStrings: true\n };\n var composed = _fromDer(bytes, remaining, depth + 1, subOptions);\n var used = start - bytes.length();\n remaining -= used;\n if(type == asn1.Type.BITSTRING) {\n used++;\n }\n\n // if the data all decoded and the class indicates UNIVERSAL or\n // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object\n var tc = composed.tagClass;\n if(used === length &&\n (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {\n value = [composed];\n }\n } catch(ex) {\n }\n }\n if(value === undefined) {\n // restore read position\n bytes.read = savedRead;\n remaining = savedRemaining;\n }\n }\n\n if(value === undefined) {\n // asn1 not constructed or composed, get raw value\n // TODO: do DER to OID conversion and vice-versa in .toDer?\n\n if(length === undefined) {\n if(options.strict) {\n throw new Error('Non-constructed ASN.1 object of indefinite length.');\n }\n // be lenient and use remaining state bytes\n length = remaining;\n }\n\n if(type === asn1.Type.BMPSTRING) {\n value = '';\n for(; length > 0; length -= 2) {\n _checkBufferLength(bytes, remaining, 2);\n value += String.fromCharCode(bytes.getInt16());\n remaining -= 2;\n }\n } else {\n value = bytes.getBytes(length);\n }\n }\n\n // add BIT STRING contents if available\n var asn1Options = bitStringContents === undefined ? null : {\n bitStringContents: bitStringContents\n };\n\n // create and return asn1 object\n return asn1.create(tagClass, type, constructed, value, asn1Options);\n}\n\n/**\n * Converts the given asn1 object to a buffer of bytes in DER format.\n *\n * @param asn1 the asn1 object to convert to bytes.\n *\n * @return the buffer of bytes.\n */\nasn1.toDer = function(obj) {\n var bytes = forge.util.createBuffer();\n\n // build the first byte\n var b1 = obj.tagClass | obj.type;\n\n // for storing the ASN.1 value\n var value = forge.util.createBuffer();\n\n // use BIT STRING contents if available and data not changed\n var useBitStringContents = false;\n if('bitStringContents' in obj) {\n useBitStringContents = true;\n if(obj.original) {\n useBitStringContents = asn1.equals(obj, obj.original);\n }\n }\n\n if(useBitStringContents) {\n value.putBytes(obj.bitStringContents);\n } else if(obj.composed) {\n // if composed, use each child asn1 object's DER bytes as value\n // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed\n // from other asn1 objects\n if(obj.constructed) {\n b1 |= 0x20;\n } else {\n // type is a bit string, add unused bits of 0x00\n value.putByte(0x00);\n }\n\n // add all of the child DER bytes together\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n value.putBuffer(asn1.toDer(obj.value[i]));\n }\n }\n } else {\n // use asn1.value directly\n if(obj.type === asn1.Type.BMPSTRING) {\n for(var i = 0; i < obj.value.length; ++i) {\n value.putInt16(obj.value.charCodeAt(i));\n }\n } else {\n // ensure integer is minimally-encoded\n // TODO: should all leading bytes be stripped vs just one?\n // .. ex '00 00 01' => '01'?\n if(obj.type === asn1.Type.INTEGER &&\n obj.value.length > 1 &&\n // leading 0x00 for positive integer\n ((obj.value.charCodeAt(0) === 0 &&\n (obj.value.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (obj.value.charCodeAt(0) === 0xFF &&\n (obj.value.charCodeAt(1) & 0x80) === 0x80))) {\n value.putBytes(obj.value.substr(1));\n } else {\n value.putBytes(obj.value);\n }\n }\n }\n\n // add tag byte\n bytes.putByte(b1);\n\n // use \"short form\" encoding\n if(value.length() <= 127) {\n // one byte describes the length\n // bit 8 = 0 and bits 7-1 = length\n bytes.putByte(value.length() & 0x7F);\n } else {\n // use \"long form\" encoding\n // 2 to 127 bytes describe the length\n // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes\n // other bytes: length in base 256, big-endian\n var len = value.length();\n var lenBytes = '';\n do {\n lenBytes += String.fromCharCode(len & 0xFF);\n len = len >>> 8;\n } while(len > 0);\n\n // set first byte to # bytes used to store the length and turn on\n // bit 8 to indicate long-form length is used\n bytes.putByte(lenBytes.length | 0x80);\n\n // concatenate length bytes in reverse since they were generated\n // little endian and we need big endian\n for(var i = lenBytes.length - 1; i >= 0; --i) {\n bytes.putByte(lenBytes.charCodeAt(i));\n }\n }\n\n // concatenate value bytes\n bytes.putBuffer(value);\n return bytes;\n};\n\n/**\n * Converts an OID dot-separated string to a byte buffer. The byte buffer\n * contains only the DER-encoded value, not any tag or length bytes.\n *\n * @param oid the OID dot-separated string.\n *\n * @return the byte buffer.\n */\nasn1.oidToDer = function(oid) {\n // split OID into individual values\n var values = oid.split('.');\n var bytes = forge.util.createBuffer();\n\n // first byte is 40 * value1 + value2\n bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var last, valueBytes, value, b;\n for(var i = 2; i < values.length; ++i) {\n // produce value bytes in reverse because we don't know how many\n // bytes it will take to store the value\n last = true;\n valueBytes = [];\n value = parseInt(values[i], 10);\n do {\n b = value & 0x7F;\n value = value >>> 7;\n // if value is not last, then turn on 8th bit\n if(!last) {\n b |= 0x80;\n }\n valueBytes.push(b);\n last = false;\n } while(value > 0);\n\n // add value bytes in reverse (needs to be in big endian)\n for(var n = valueBytes.length - 1; n >= 0; --n) {\n bytes.putByte(valueBytes[n]);\n }\n }\n\n return bytes;\n};\n\n/**\n * Converts a DER-encoded byte buffer to an OID dot-separated string. The\n * byte buffer should contain only the DER-encoded value, not any tag or\n * length bytes.\n *\n * @param bytes the byte buffer.\n *\n * @return the OID dot-separated string.\n */\nasn1.derToOid = function(bytes) {\n var oid;\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n // first byte is 40 * value1 + value2\n var b = bytes.getByte();\n oid = Math.floor(b / 40) + '.' + (b % 40);\n\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var value = 0;\n while(bytes.length() > 0) {\n b = bytes.getByte();\n value = value << 7;\n // not the last byte for the value\n if(b & 0x80) {\n value += b & 0x7F;\n } else {\n // last byte\n oid += '.' + (value + b);\n value = 0;\n }\n }\n\n return oid;\n};\n\n/**\n * Converts a UTCTime value to a date.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Parsing that structure hasn't been implemented yet.\n *\n * @param utc the UTCTime value to convert.\n *\n * @return the date.\n */\nasn1.utcTimeToDate = function(utc) {\n /* The following formats can be used:\n\n YYMMDDhhmmZ\n YYMMDDhhmm+hh'mm'\n YYMMDDhhmm-hh'mm'\n YYMMDDhhmmssZ\n YYMMDDhhmmss+hh'mm'\n YYMMDDhhmmss-hh'mm'\n\n Where:\n\n YY is the least significant two digits of the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n // if YY >= 50 use 19xx, if YY < 50 use 20xx\n var year = parseInt(utc.substr(0, 2), 10);\n year = (year >= 50) ? 1900 + year : 2000 + year;\n var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(utc.substr(4, 2), 10);\n var hh = parseInt(utc.substr(6, 2), 10);\n var mm = parseInt(utc.substr(8, 2), 10);\n var ss = 0;\n\n // not just YYMMDDhhmmZ\n if(utc.length > 11) {\n // get character after minutes\n var c = utc.charAt(10);\n var end = 10;\n\n // see if seconds are present\n if(c !== '+' && c !== '-') {\n // get seconds\n ss = parseInt(utc.substr(10, 2), 10);\n end += 2;\n }\n }\n\n // update date\n date.setUTCFullYear(year, MM, DD);\n date.setUTCHours(hh, mm, ss, 0);\n\n if(end) {\n // get +/- after end of time\n c = utc.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(utc.substr(end + 1, 2), 10);\n var mmoffset = parseInt(utc.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n var offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n date.setTime(+date - offset);\n } else {\n date.setTime(+date + offset);\n }\n }\n }\n\n return date;\n};\n\n/**\n * Converts a GeneralizedTime value to a date.\n *\n * @param gentime the GeneralizedTime value to convert.\n *\n * @return the date.\n */\nasn1.generalizedTimeToDate = function(gentime) {\n /* The following formats can be used:\n\n YYYYMMDDHHMMSS\n YYYYMMDDHHMMSS.fff\n YYYYMMDDHHMMSSZ\n YYYYMMDDHHMMSS.fffZ\n YYYYMMDDHHMMSS+hh'mm'\n YYYYMMDDHHMMSS.fff+hh'mm'\n YYYYMMDDHHMMSS-hh'mm'\n YYYYMMDDHHMMSS.fff-hh'mm'\n\n Where:\n\n YYYY is the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n .fff is the second fraction, accurate to three decimal places\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n var YYYY = parseInt(gentime.substr(0, 4), 10);\n var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(gentime.substr(6, 2), 10);\n var hh = parseInt(gentime.substr(8, 2), 10);\n var mm = parseInt(gentime.substr(10, 2), 10);\n var ss = parseInt(gentime.substr(12, 2), 10);\n var fff = 0;\n var offset = 0;\n var isUTC = false;\n\n if(gentime.charAt(gentime.length - 1) === 'Z') {\n isUTC = true;\n }\n\n var end = gentime.length - 5, c = gentime.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);\n var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n offset *= -1;\n }\n\n isUTC = true;\n }\n\n // check for second fraction\n if(gentime.charAt(14) === '.') {\n fff = parseFloat(gentime.substr(14), 10) * 1000;\n }\n\n if(isUTC) {\n date.setUTCFullYear(YYYY, MM, DD);\n date.setUTCHours(hh, mm, ss, fff);\n\n // apply offset\n date.setTime(+date + offset);\n } else {\n date.setFullYear(YYYY, MM, DD);\n date.setHours(hh, mm, ss, fff);\n }\n\n return date;\n};\n\n/**\n * Converts a date to a UTCTime value.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Converting to a GeneralizedTime hasn't been\n * implemented yet.\n *\n * @param date the date to convert.\n *\n * @return the UTCTime value.\n */\nasn1.dateToUtcTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYMMDDhhmmssZ\n var format = [];\n format.push(('' + date.getUTCFullYear()).substr(2));\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a date to a GeneralizedTime value.\n *\n * @param date the date to convert.\n *\n * @return the GeneralizedTime value as a string.\n */\nasn1.dateToGeneralizedTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYYYMMDDHHMMSSZ\n var format = [];\n format.push('' + date.getUTCFullYear());\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a javascript integer to a DER-encoded byte buffer to be used\n * as the value for an INTEGER type.\n *\n * @param x the integer.\n *\n * @return the byte buffer.\n */\nasn1.integerToDer = function(x) {\n var rval = forge.util.createBuffer();\n if(x >= -0x80 && x < 0x80) {\n return rval.putSignedInt(x, 8);\n }\n if(x >= -0x8000 && x < 0x8000) {\n return rval.putSignedInt(x, 16);\n }\n if(x >= -0x800000 && x < 0x800000) {\n return rval.putSignedInt(x, 24);\n }\n if(x >= -0x80000000 && x < 0x80000000) {\n return rval.putSignedInt(x, 32);\n }\n var error = new Error('Integer too large; max is 32-bits.');\n error.integer = x;\n throw error;\n};\n\n/**\n * Converts a DER-encoded byte buffer to a javascript integer. This is\n * typically used to decode the value of an INTEGER type.\n *\n * @param bytes the byte buffer.\n *\n * @return the integer.\n */\nasn1.derToInteger = function(bytes) {\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var n = bytes.length() * 8;\n if(n > 32) {\n throw new Error('Integer too large; max is 32-bits.');\n }\n return bytes.getSignedInt(n);\n};\n\n/**\n * Validates that the given ASN.1 object is at least a super set of the\n * given ASN.1 structure. Only tag classes and types are checked. An\n * optional map may also be provided to capture ASN.1 values while the\n * structure is checked.\n *\n * To capture an ASN.1 value, set an object in the validator's 'capture'\n * parameter to the key to use in the capture map. To capture the full\n * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including\n * the leading unused bits counter byte, specify 'captureBitStringContents'.\n * To capture BIT STRING bytes, without the leading unused bits counter byte,\n * specify 'captureBitStringValue'.\n *\n * Objects in the validator may set a field 'optional' to true to indicate\n * that it isn't necessary to pass validation.\n *\n * @param obj the ASN.1 object to validate.\n * @param v the ASN.1 structure validator.\n * @param capture an optional map to capture values in.\n * @param errors an optional array for storing validation errors.\n *\n * @return true on success, false on failure.\n */\nasn1.validate = function(obj, v, capture, errors) {\n var rval = false;\n\n // ensure tag class and type are the same if specified\n if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&\n (obj.type === v.type || typeof(v.type) === 'undefined')) {\n // ensure constructed flag is the same if specified\n if(obj.constructed === v.constructed ||\n typeof(v.constructed) === 'undefined') {\n rval = true;\n\n // handle sub values\n if(v.value && forge.util.isArray(v.value)) {\n var j = 0;\n for(var i = 0; rval && i < v.value.length; ++i) {\n rval = v.value[i].optional || false;\n if(obj.value[j]) {\n rval = asn1.validate(obj.value[j], v.value[i], capture, errors);\n if(rval) {\n ++j;\n } else if(v.value[i].optional) {\n rval = true;\n }\n }\n if(!rval && errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Tag class \"' + v.tagClass + '\", type \"' +\n v.type + '\" expected value length \"' +\n v.value.length + '\", got \"' +\n obj.value.length + '\"');\n }\n }\n }\n\n if(rval && capture) {\n if(v.capture) {\n capture[v.capture] = obj.value;\n }\n if(v.captureAsn1) {\n capture[v.captureAsn1] = obj;\n }\n if(v.captureBitStringContents && 'bitStringContents' in obj) {\n capture[v.captureBitStringContents] = obj.bitStringContents;\n }\n if(v.captureBitStringValue && 'bitStringContents' in obj) {\n var value;\n if(obj.bitStringContents.length < 2) {\n capture[v.captureBitStringValue] = '';\n } else {\n // FIXME: support unused bits with data shifting\n var unused = obj.bitStringContents.charCodeAt(0);\n if(unused !== 0) {\n throw new Error(\n 'captureBitStringValue only supported for zero unused bits');\n }\n capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);\n }\n }\n }\n } else if(errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected constructed \"' + v.constructed + '\", got \"' +\n obj.constructed + '\"');\n }\n } else if(errors) {\n if(obj.tagClass !== v.tagClass) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected tag class \"' + v.tagClass + '\", got \"' +\n obj.tagClass + '\"');\n }\n if(obj.type !== v.type) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected type \"' + v.type + '\", got \"' + obj.type + '\"');\n }\n }\n return rval;\n};\n\n// regex for testing for non-latin characters\nvar _nonLatinRegex = /[^\\\\u0000-\\\\u00ff]/;\n\n/**\n * Pretty prints an ASN.1 object to a string.\n *\n * @param obj the object to write out.\n * @param level the level in the tree.\n * @param indentation the indentation to use.\n *\n * @return the string.\n */\nasn1.prettyPrint = function(obj, level, indentation) {\n var rval = '';\n\n // set default level and indentation\n level = level || 0;\n indentation = indentation || 2;\n\n // start new line for deep levels\n if(level > 0) {\n rval += '\\n';\n }\n\n // create indent\n var indent = '';\n for(var i = 0; i < level * indentation; ++i) {\n indent += ' ';\n }\n\n // print class:type\n rval += indent + 'Tag: ';\n switch(obj.tagClass) {\n case asn1.Class.UNIVERSAL:\n rval += 'Universal:';\n break;\n case asn1.Class.APPLICATION:\n rval += 'Application:';\n break;\n case asn1.Class.CONTEXT_SPECIFIC:\n rval += 'Context-Specific:';\n break;\n case asn1.Class.PRIVATE:\n rval += 'Private:';\n break;\n }\n\n if(obj.tagClass === asn1.Class.UNIVERSAL) {\n rval += obj.type;\n\n // known types\n switch(obj.type) {\n case asn1.Type.NONE:\n rval += ' (None)';\n break;\n case asn1.Type.BOOLEAN:\n rval += ' (Boolean)';\n break;\n case asn1.Type.INTEGER:\n rval += ' (Integer)';\n break;\n case asn1.Type.BITSTRING:\n rval += ' (Bit string)';\n break;\n case asn1.Type.OCTETSTRING:\n rval += ' (Octet string)';\n break;\n case asn1.Type.NULL:\n rval += ' (Null)';\n break;\n case asn1.Type.OID:\n rval += ' (Object Identifier)';\n break;\n case asn1.Type.ODESC:\n rval += ' (Object Descriptor)';\n break;\n case asn1.Type.EXTERNAL:\n rval += ' (External or Instance of)';\n break;\n case asn1.Type.REAL:\n rval += ' (Real)';\n break;\n case asn1.Type.ENUMERATED:\n rval += ' (Enumerated)';\n break;\n case asn1.Type.EMBEDDED:\n rval += ' (Embedded PDV)';\n break;\n case asn1.Type.UTF8:\n rval += ' (UTF8)';\n break;\n case asn1.Type.ROID:\n rval += ' (Relative Object Identifier)';\n break;\n case asn1.Type.SEQUENCE:\n rval += ' (Sequence)';\n break;\n case asn1.Type.SET:\n rval += ' (Set)';\n break;\n case asn1.Type.PRINTABLESTRING:\n rval += ' (Printable String)';\n break;\n case asn1.Type.IA5String:\n rval += ' (IA5String (ASCII))';\n break;\n case asn1.Type.UTCTIME:\n rval += ' (UTC time)';\n break;\n case asn1.Type.GENERALIZEDTIME:\n rval += ' (Generalized time)';\n break;\n case asn1.Type.BMPSTRING:\n rval += ' (BMP String)';\n break;\n }\n } else {\n rval += obj.type;\n }\n\n rval += '\\n';\n rval += indent + 'Constructed: ' + obj.constructed + '\\n';\n\n if(obj.composed) {\n var subvalues = 0;\n var sub = '';\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n subvalues += 1;\n sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);\n if((i + 1) < obj.value.length) {\n sub += ',';\n }\n }\n }\n rval += indent + 'Sub values: ' + subvalues + sub;\n } else {\n rval += indent + 'Value: ';\n if(obj.type === asn1.Type.OID) {\n var oid = asn1.derToOid(obj.value);\n rval += oid;\n if(forge.pki && forge.pki.oids) {\n if(oid in forge.pki.oids) {\n rval += ' (' + forge.pki.oids[oid] + ') ';\n }\n }\n }\n if(obj.type === asn1.Type.INTEGER) {\n try {\n rval += asn1.derToInteger(obj.value);\n } catch(ex) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n }\n } else if(obj.type === asn1.Type.BITSTRING) {\n // TODO: shift bits as needed to display without padding\n if(obj.value.length > 1) {\n // remove unused bits field\n rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));\n } else {\n rval += '(none)';\n }\n // show unused bit count\n if(obj.value.length > 0) {\n var unused = obj.value.charCodeAt(0);\n if(unused == 1) {\n rval += ' (1 unused bit shown)';\n } else if(unused > 1) {\n rval += ' (' + unused + ' unused bits shown)';\n }\n }\n } else if(obj.type === asn1.Type.OCTETSTRING) {\n if(!_nonLatinRegex.test(obj.value)) {\n rval += '(' + obj.value + ') ';\n }\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.type === asn1.Type.UTF8) {\n rval += forge.util.decodeUtf8(obj.value);\n } else if(obj.type === asn1.Type.PRINTABLESTRING ||\n obj.type === asn1.Type.IA5String) {\n rval += obj.value;\n } else if(_nonLatinRegex.test(obj.value)) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.value.length === 0) {\n rval += '[null]';\n } else {\n rval += obj.value;\n }\n }\n\n return rval;\n};\n","/**\n * Node.js module for Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nmodule.exports = forge.md = forge.md || {};\nforge.md.algorithms = forge.md.algorithms || {};\n","/**\n * Hash-based Message Authentication Code implementation. Requires a message\n * digest object that can be obtained, for example, from forge.md.sha1 or\n * forge.md.md5.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\n/* HMAC API */\nvar hmac = module.exports = forge.hmac = forge.hmac || {};\n\n/**\n * Creates an HMAC object that uses the given message digest object.\n *\n * @return an HMAC object.\n */\nhmac.create = function() {\n // the hmac key to use\n var _key = null;\n\n // the message digest to use\n var _md = null;\n\n // the inner padding\n var _ipadding = null;\n\n // the outer padding\n var _opadding = null;\n\n // hmac context\n var ctx = {};\n\n /**\n * Starts or restarts the HMAC with the given key and message digest.\n *\n * @param md the message digest to use, null to reuse the previous one,\n * a string to use builtin 'sha1', 'md5', 'sha256'.\n * @param key the key to use as a string, array of bytes, byte buffer,\n * or null to reuse the previous key.\n */\n ctx.start = function(md, key) {\n if(md !== null) {\n if(typeof md === 'string') {\n // create builtin message digest\n md = md.toLowerCase();\n if(md in forge.md.algorithms) {\n _md = forge.md.algorithms[md].create();\n } else {\n throw new Error('Unknown hash algorithm \"' + md + '\"');\n }\n } else {\n // store message digest\n _md = md;\n }\n }\n\n if(key === null) {\n // reuse previous key\n key = _key;\n } else {\n if(typeof key === 'string') {\n // convert string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key)) {\n // convert byte array into byte buffer\n var tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // if key is longer than blocksize, hash it\n var keylen = key.length();\n if(keylen > _md.blockLength) {\n _md.start();\n _md.update(key.bytes());\n key = _md.digest();\n }\n\n // mix key into inner and outer padding\n // ipadding = [0x36 * blocksize] ^ key\n // opadding = [0x5C * blocksize] ^ key\n _ipadding = forge.util.createBuffer();\n _opadding = forge.util.createBuffer();\n keylen = key.length();\n for(var i = 0; i < keylen; ++i) {\n var tmp = key.at(i);\n _ipadding.putByte(0x36 ^ tmp);\n _opadding.putByte(0x5C ^ tmp);\n }\n\n // if key is shorter than blocksize, add additional padding\n if(keylen < _md.blockLength) {\n var tmp = _md.blockLength - keylen;\n for(var i = 0; i < tmp; ++i) {\n _ipadding.putByte(0x36);\n _opadding.putByte(0x5C);\n }\n }\n _key = key;\n _ipadding = _ipadding.bytes();\n _opadding = _opadding.bytes();\n }\n\n // digest is done like so: hash(opadding | hash(ipadding | message))\n\n // prepare to do inner hash\n // hash(ipadding | message)\n _md.start();\n _md.update(_ipadding);\n };\n\n /**\n * Updates the HMAC with the given message bytes.\n *\n * @param bytes the bytes to update with.\n */\n ctx.update = function(bytes) {\n _md.update(bytes);\n };\n\n /**\n * Produces the Message Authentication Code (MAC).\n *\n * @return a byte buffer containing the digest value.\n */\n ctx.getMac = function() {\n // digest is done like so: hash(opadding | hash(ipadding | message))\n // here we do the outer hashing\n var inner = _md.digest().bytes();\n _md.start();\n _md.update(_opadding);\n _md.update(inner);\n return _md.digest();\n };\n // alias for getMac\n ctx.digest = ctx.getMac;\n\n return ctx;\n};\n","/**\n * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar md5 = module.exports = forge.md5 = forge.md5 || {};\nforge.md.md5 = forge.md.algorithms.md5 = md5;\n\n/**\n * Creates an MD5 message digest object.\n *\n * @return a message digest object.\n */\nmd5.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // MD5 state contains four 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(16);\n\n // message digest object\n var md = {\n algorithm: 'md5',\n blockLength: 64,\n digestLength: 16,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = (len[1] / 0x100000000) >>> 0;\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate MD5 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in little-endian order; since length\n // is stored in bytes we multiply by 8 and add carry\n var bits, carry = 0;\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n bits = md.fullMessageLength[i] * 8 + carry;\n carry = (bits / 0x100000000) >>> 0;\n finalBlock.putInt32Le(bits >>> 0);\n }\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32Le(s2.h0);\n rval.putInt32Le(s2.h1);\n rval.putInt32Le(s2.h2);\n rval.putInt32Le(s2.h3);\n return rval;\n };\n\n return md;\n};\n\n// padding, constant tables for calculating md5\nvar _padding = null;\nvar _g = null;\nvar _r = null;\nvar _k = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // g values\n _g = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12,\n 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2,\n 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9];\n\n // rounds table\n _r = [\n 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];\n\n // get the result of abs(sin(i + 1)) as a 32-bit integer\n _k = new Array(64);\n for(var i = 0; i < 64; ++i) {\n _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000);\n }\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates an MD5 state with the given byte buffer.\n *\n * @param s the MD5 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, f, r, i;\n var len = bytes.length();\n while(len >= 64) {\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32Le();\n f = d ^ (b & (c ^ d));\n t = (a + f + _k[i] + w[i]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 2\n for(; i < 32; ++i) {\n f = c ^ (d & (b ^ c));\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 3\n for(; i < 48; ++i) {\n f = b ^ c ^ d;\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 4\n for(; i < 64; ++i) {\n f = c ^ (b | ~d);\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.\n *\n * See: RFC 1421.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n *\n * A Forge PEM object has the following fields:\n *\n * type: identifies the type of message (eg: \"RSA PRIVATE KEY\").\n *\n * procType: identifies the type of processing performed on the message,\n * it has two subfields: version and type, eg: 4,ENCRYPTED.\n *\n * contentDomain: identifies the type of content in the message, typically\n * only uses the value: \"RFC822\".\n *\n * dekInfo: identifies the message encryption algorithm and mode and includes\n * any parameters for the algorithm, it has two subfields: algorithm and\n * parameters, eg: DES-CBC,F8143EDE5960C597.\n *\n * headers: contains all other PEM encapsulated headers -- where order is\n * significant (for pairing data like recipient ID + key info).\n *\n * body: the binary-encoded body.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n// shortcut for pem API\nvar pem = module.exports = forge.pem = forge.pem || {};\n\n/**\n * Encodes (serializes) the given PEM object.\n *\n * @param msg the PEM message object to encode.\n * @param options the options to use:\n * maxline the maximum characters per line for the body, (default: 64).\n *\n * @return the PEM-formatted string.\n */\npem.encode = function(msg, options) {\n options = options || {};\n var rval = '-----BEGIN ' + msg.type + '-----\\r\\n';\n\n // encode special headers\n var header;\n if(msg.procType) {\n header = {\n name: 'Proc-Type',\n values: [String(msg.procType.version), msg.procType.type]\n };\n rval += foldHeader(header);\n }\n if(msg.contentDomain) {\n header = {name: 'Content-Domain', values: [msg.contentDomain]};\n rval += foldHeader(header);\n }\n if(msg.dekInfo) {\n header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};\n if(msg.dekInfo.parameters) {\n header.values.push(msg.dekInfo.parameters);\n }\n rval += foldHeader(header);\n }\n\n if(msg.headers) {\n // encode all other headers\n for(var i = 0; i < msg.headers.length; ++i) {\n rval += foldHeader(msg.headers[i]);\n }\n }\n\n // terminate header\n if(msg.procType) {\n rval += '\\r\\n';\n }\n\n // add body\n rval += forge.util.encode64(msg.body, options.maxline || 64) + '\\r\\n';\n\n rval += '-----END ' + msg.type + '-----\\r\\n';\n return rval;\n};\n\n/**\n * Decodes (deserializes) all PEM messages found in the given string.\n *\n * @param str the PEM-formatted string to decode.\n *\n * @return the PEM message objects in an array.\n */\npem.decode = function(str) {\n var rval = [];\n\n // split string into PEM messages (be lenient w/EOF on BEGIN line)\n var rMessage = /\\s*-----BEGIN ([A-Z0-9- ]+)-----\\r?\\n?([\\x21-\\x7e\\s]+?(?:\\r?\\n\\r?\\n))?([:A-Za-z0-9+\\/=\\s]+?)-----END \\1-----/g;\n var rHeader = /([\\x21-\\x7e]+):\\s*([\\x21-\\x7e\\s^:]+)/;\n var rCRLF = /\\r?\\n/;\n var match;\n while(true) {\n match = rMessage.exec(str);\n if(!match) {\n break;\n }\n\n var msg = {\n type: match[1],\n procType: null,\n contentDomain: null,\n dekInfo: null,\n headers: [],\n body: forge.util.decode64(match[3])\n };\n rval.push(msg);\n\n // no headers\n if(!match[2]) {\n continue;\n }\n\n // parse headers\n var lines = match[2].split(rCRLF);\n var li = 0;\n while(match && li < lines.length) {\n // get line, trim any rhs whitespace\n var line = lines[li].replace(/\\s+$/, '');\n\n // RFC2822 unfold any following folded lines\n for(var nl = li + 1; nl < lines.length; ++nl) {\n var next = lines[nl];\n if(!/\\s/.test(next[0])) {\n break;\n }\n line += next;\n li = nl;\n }\n\n // parse header\n match = line.match(rHeader);\n if(match) {\n var header = {name: match[1], values: []};\n var values = match[2].split(',');\n for(var vi = 0; vi < values.length; ++vi) {\n header.values.push(ltrim(values[vi]));\n }\n\n // Proc-Type must be the first header\n if(!msg.procType) {\n if(header.name !== 'Proc-Type') {\n throw new Error('Invalid PEM formatted message. The first ' +\n 'encapsulated header must be \"Proc-Type\".');\n } else if(header.values.length !== 2) {\n throw new Error('Invalid PEM formatted message. The \"Proc-Type\" ' +\n 'header must have two subfields.');\n }\n msg.procType = {version: values[0], type: values[1]};\n } else if(!msg.contentDomain && header.name === 'Content-Domain') {\n // special-case Content-Domain\n msg.contentDomain = values[0] || '';\n } else if(!msg.dekInfo && header.name === 'DEK-Info') {\n // special-case DEK-Info\n if(header.values.length === 0) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must have at least one subfield.');\n }\n msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};\n } else {\n msg.headers.push(header);\n }\n }\n\n ++li;\n }\n\n if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must be present if \"Proc-Type\" is \"ENCRYPTED\".');\n }\n }\n\n if(rval.length === 0) {\n throw new Error('Invalid PEM formatted message.');\n }\n\n return rval;\n};\n\nfunction foldHeader(header) {\n var rval = header.name + ': ';\n\n // ensure values with CRLF are folded\n var values = [];\n var insertSpace = function(match, $1) {\n return ' ' + $1;\n };\n for(var i = 0; i < header.values.length; ++i) {\n values.push(header.values[i].replace(/^(\\S+\\r\\n)/, insertSpace));\n }\n rval += values.join(',') + '\\r\\n';\n\n // do folding\n var length = 0;\n var candidate = -1;\n for(var i = 0; i < rval.length; ++i, ++length) {\n if(length > 65 && candidate !== -1) {\n var insert = rval[candidate];\n if(insert === ',') {\n ++candidate;\n rval = rval.substr(0, candidate) + '\\r\\n ' + rval.substr(candidate);\n } else {\n rval = rval.substr(0, candidate) +\n '\\r\\n' + insert + rval.substr(candidate + 1);\n }\n length = (i - candidate - 1);\n candidate = -1;\n ++i;\n } else if(rval[i] === ' ' || rval[i] === '\\t' || rval[i] === ',') {\n candidate = i;\n }\n }\n\n return rval;\n}\n\nfunction ltrim(str) {\n return str.replace(/^\\s+/, '');\n}\n","/**\n * DES (Data Encryption Standard) implementation.\n *\n * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.\n * It is based on the BSD-licensed implementation by Paul Tero:\n *\n * Paul Tero, July 2001\n * http://www.tero.co.uk/des/\n *\n * Optimised for performance with large blocks by\n * Michael Hayworth, November 2001\n * http://www.netdealing.com\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* DES API */\nmodule.exports = forge.des = forge.des || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new DES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the DES algorithm object.\n */\nforge.des.Algorithm = function(name, mode) {\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 8,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this DES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.des.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = forge.util.createBuffer(options.key);\n if(this.name.indexOf('3DES') === 0) {\n if(key.length() !== 24) {\n throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);\n }\n }\n\n // do key expansion to 16 or 48 subkeys (single or triple DES)\n this._keys = _createKeys(key);\n this._init = true;\n};\n\n/** Register DES algorithms **/\n\nregisterAlgorithm('DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('DES-CTR', forge.cipher.modes.ctr);\n\nregisterAlgorithm('3DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('3DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('3DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('3DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('3DES-CTR', forge.cipher.modes.ctr);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.des.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** DES implementation **/\n\nvar spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];\nvar spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];\nvar spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];\nvar spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];\nvar spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];\nvar spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];\nvar spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];\nvar spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];\n\n/**\n * Create necessary sub keys.\n *\n * @param key the 64-bit or 192-bit key.\n *\n * @return the expanded keys.\n */\nfunction _createKeys(key) {\n var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],\n pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],\n pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],\n pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],\n pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],\n pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],\n pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],\n pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],\n pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],\n pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],\n pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],\n pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],\n pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],\n pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];\n\n // how many iterations (1 for des, 3 for triple des)\n // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n var iterations = key.length() > 8 ? 3 : 1;\n\n // stores the return keys\n var keys = [];\n\n // now define the left shifts which need to be done\n var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n\n var n = 0, tmp;\n for(var j = 0; j < iterations; j++) {\n var left = key.getInt32();\n var right = key.getInt32();\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= tmp;\n left ^= (tmp << 2);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // right needs to be shifted and OR'd with last four bits of left\n tmp = (left << 8) | ((right >>> 20) & 0x000000f0);\n\n // left needs to be put upside down\n left = ((right << 24) | ((right << 8) & 0xff0000) |\n ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));\n right = tmp;\n\n // now go through and perform these shifts on the left and right keys\n for(var i = 0; i < shifts.length; ++i) {\n //shift the keys either one or two bits to the left\n if(shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n // now apply PC-2, in such a way that E is easier when encrypting or\n // decrypting this conversion will look like PC-2 except only the last 6\n // bits of each byte are used rather than 48 consecutive bits and the\n // order of lines will be according to how the S selection functions will\n // be applied: S2, S4, S6, S8, S1, S3, S5, S7\n var lefttmp = (\n pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |\n pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |\n pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |\n pc2bytes6[(left >>> 4) & 0xf]);\n var righttmp = (\n pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |\n pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |\n pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf]);\n tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;\n keys[n++] = lefttmp ^ tmp;\n keys[n++] = righttmp ^ (tmp << 16);\n }\n }\n\n return keys;\n}\n\n/**\n * Updates a single block (1 byte) using DES. The update will either\n * encrypt or decrypt the block.\n *\n * @param keys the expanded keys.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(keys, input, output, decrypt) {\n // set up loops for single or triple DES\n var iterations = keys.length === 32 ? 3 : 9;\n var looping;\n if(iterations === 3) {\n looping = decrypt ? [30, -2, -2] : [0, 32, 2];\n } else {\n looping = (decrypt ?\n [94, 62, -2, 32, 64, 2, 30, -2, -2] :\n [0, 32, 2, 62, 30, -2, 64, 96, 2]);\n }\n\n var tmp;\n\n var left = input[0];\n var right = input[1];\n\n // first each 64 bit chunk of the message must be permuted according to IP\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // rotate left 1 bit\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n for(var j = 0; j < iterations; j += 3) {\n var endloop = looping[j + 1];\n var loopinc = looping[j + 2];\n\n // now go through and perform the encryption or decryption\n for(var i = looping[j]; i != endloop; i += loopinc) {\n var right1 = right ^ keys[i];\n var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n\n // passing these bytes through the S selection functions\n tmp = left;\n left = right;\n right = tmp ^ (\n spfunction2[(right1 >>> 24) & 0x3f] |\n spfunction4[(right1 >>> 16) & 0x3f] |\n spfunction6[(right1 >>> 8) & 0x3f] |\n spfunction8[right1 & 0x3f] |\n spfunction1[(right2 >>> 24) & 0x3f] |\n spfunction3[(right2 >>> 16) & 0x3f] |\n spfunction5[(right2 >>> 8) & 0x3f] |\n spfunction7[right2 & 0x3f]);\n }\n // unreverse left and right\n tmp = left;\n left = right;\n right = tmp;\n }\n\n // rotate right 1 bit\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n // now perform IP-1, which is IP in the opposite direction\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n output[0] = left;\n output[1] = right;\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('DES-', key);\n * forge.cipher.createDecipher('DES-', key);\n *\n * Creates a deprecated DES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param options the options to use.\n * key the symmetric key to use (64 or 192 bits).\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'DES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * Password-Based Key-Derivation Function #2 implementation.\n *\n * See RFC 2898 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./hmac');\nrequire('./md');\nrequire('./util');\n\nvar pkcs5 = forge.pkcs5 = forge.pkcs5 || {};\n\nvar crypto;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript) {\n crypto = require('crypto');\n}\n\n/**\n * Derives a key from a password.\n *\n * @param p the password as a binary-encoded string of bytes.\n * @param s the salt as a binary-encoded string of bytes.\n * @param c the iteration count, a positive integer.\n * @param dkLen the intended length, in bytes, of the derived key,\n * (max: 2^32 - 1) * hash length of the PRF.\n * @param [md] the message digest (or algorithm identifier as a string) to use\n * in the PRF, defaults to SHA-1.\n * @param [callback(err, key)] presence triggers asynchronous version, called\n * once the operation completes.\n *\n * @return the derived key, as a binary-encoded string of bytes, for the\n * synchronous version (if no callback is specified).\n */\nmodule.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(\n p, s, c, dkLen, md, callback) {\n if(typeof md === 'function') {\n callback = md;\n md = null;\n }\n\n // use native implementation if possible and not disabled, note that\n // some node versions only support SHA-1, others allow digest to be changed\n if(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n crypto.pbkdf2 && (md === null || typeof md !== 'object') &&\n (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {\n if(typeof md !== 'string') {\n // default prf to SHA-1\n md = 'sha1';\n }\n p = Buffer.from(p, 'binary');\n s = Buffer.from(s, 'binary');\n if(!callback) {\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');\n }\n return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');\n }\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n\n if(typeof md === 'undefined' || md === null) {\n // default prf to SHA-1\n md = 'sha1';\n }\n if(typeof md === 'string') {\n if(!(md in forge.md.algorithms)) {\n throw new Error('Unknown hash algorithm: ' + md);\n }\n md = forge.md[md].create();\n }\n\n var hLen = md.digestLength;\n\n /* 1. If dkLen > (2^32 - 1) * hLen, output \"derived key too long\" and\n stop. */\n if(dkLen > (0xFFFFFFFF * hLen)) {\n var err = new Error('Derived key is too long.');\n if(callback) {\n return callback(err);\n }\n throw err;\n }\n\n /* 2. Let len be the number of hLen-octet blocks in the derived key,\n rounding up, and let r be the number of octets in the last\n block:\n\n len = CEIL(dkLen / hLen),\n r = dkLen - (len - 1) * hLen. */\n var len = Math.ceil(dkLen / hLen);\n var r = dkLen - (len - 1) * hLen;\n\n /* 3. For each block of the derived key apply the function F defined\n below to the password P, the salt S, the iteration count c, and\n the block index to compute the block:\n\n T_1 = F(P, S, c, 1),\n T_2 = F(P, S, c, 2),\n ...\n T_len = F(P, S, c, len),\n\n where the function F is defined as the exclusive-or sum of the\n first c iterates of the underlying pseudorandom function PRF\n applied to the password P and the concatenation of the salt S\n and the block index i:\n\n F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c\n\n where\n\n u_1 = PRF(P, S || INT(i)),\n u_2 = PRF(P, u_1),\n ...\n u_c = PRF(P, u_{c-1}).\n\n Here, INT(i) is a four-octet encoding of the integer i, most\n significant octet first. */\n var prf = forge.hmac.create();\n prf.start(md, p);\n var dk = '';\n var xor, u_c, u_c1;\n\n // sync version\n if(!callback) {\n for(var i = 1; i <= len; ++i) {\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n for(var j = 2; j <= c; ++j) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n }\n /* 5. Output the derived key DK. */\n return dk;\n }\n\n // async version\n var i = 1, j;\n function outer() {\n if(i > len) {\n // done\n return callback(null, dk);\n }\n\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n j = 2;\n inner();\n }\n\n function inner() {\n if(j <= c) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n ++j;\n return forge.util.setImmediate(inner);\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n\n ++i;\n outer();\n }\n\n outer();\n};\n","/**\n * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.\n *\n * See FIPS 180-2 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha256 = module.exports = forge.sha256 = forge.sha256 || {};\nforge.md.sha256 = forge.md.algorithms.sha256 = sha256;\n\n/**\n * Creates a SHA-256 message digest object.\n *\n * @return a message digest object.\n */\nsha256.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-256 state contains eight 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(64);\n\n // message digest object\n var md = {\n algorithm: 'sha256',\n blockLength: 64,\n digestLength: 32,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x6A09E667,\n h1: 0xBB67AE85,\n h2: 0x3C6EF372,\n h3: 0xA54FF53A,\n h4: 0x510E527F,\n h5: 0x9B05688C,\n h6: 0x1F83D9AB,\n h7: 0x5BE0CD19\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-256 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4,\n h5: _state.h5,\n h6: _state.h6,\n h7: _state.h7\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n rval.putInt32(s2.h5);\n rval.putInt32(s2.h6);\n rval.putInt32(s2.h7);\n return rval;\n };\n\n return md;\n};\n\n// sha-256 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // create K table for SHA-256\n _k = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-256 state with the given byte buffer.\n *\n * @param s the SHA-256 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 64 32-bit words according to SHA-256\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32();\n }\n for(; i < 64; ++i) {\n // XOR word 2 words ago rot right 17, rot right 19, shft right 10\n t1 = w[i - 2];\n t1 =\n ((t1 >>> 17) | (t1 << 15)) ^\n ((t1 >>> 19) | (t1 << 13)) ^\n (t1 >>> 10);\n // XOR word 15 words ago rot right 7, rot right 18, shft right 3\n t2 = w[i - 15];\n t2 =\n ((t2 >>> 7) | (t2 << 25)) ^\n ((t2 >>> 18) | (t2 << 14)) ^\n (t2 >>> 3);\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32\n w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;\n }\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n f = s.h5;\n g = s.h6;\n h = s.h7;\n\n // round function\n for(i = 0; i < 64; ++i) {\n // Sum1(e)\n s1 =\n ((e >>> 6) | (e << 26)) ^\n ((e >>> 11) | (e << 21)) ^\n ((e >>> 25) | (e << 7));\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch = g ^ (e & (f ^ g));\n // Sum0(a)\n s0 =\n ((a >>> 2) | (a << 30)) ^\n ((a >>> 13) | (a << 19)) ^\n ((a >>> 22) | (a << 10));\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj = (a & b) | (c & (a ^ b));\n\n // main algorithm\n t1 = h + s1 + ch + _k[i] + w[i];\n t2 = s0 + maj;\n h = g;\n g = f;\n f = e;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n a = (t1 + t2) >>> 0;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n s.h5 = (s.h5 + f) | 0;\n s.h6 = (s.h6 + g) | 0;\n s.h7 = (s.h7 + h) | 0;\n len -= 64;\n }\n}\n","/**\n * A javascript implementation of a cryptographically-secure\n * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed\n * here though the use of SHA-256 is not enforced; when generating an\n * a PRNG context, the hashing algorithm and block cipher used for\n * the generator are specified via a plugin.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar _crypto = null;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n !process.versions['node-webkit']) {\n _crypto = require('crypto');\n}\n\n/* PRNG API */\nvar prng = module.exports = forge.prng = forge.prng || {};\n\n/**\n * Creates a new PRNG context.\n *\n * A PRNG plugin must be passed in that will provide:\n *\n * 1. A function that initializes the key and seed of a PRNG context. It\n * will be given a 16 byte key and a 16 byte seed. Any key expansion\n * or transformation of the seed from a byte string into an array of\n * integers (or similar) should be performed.\n * 2. The cryptographic function used by the generator. It takes a key and\n * a seed.\n * 3. A seed increment function. It takes the seed and returns seed + 1.\n * 4. An api to create a message digest.\n *\n * For an example, see random.js.\n *\n * @param plugin the PRNG plugin to use.\n */\nprng.create = function(plugin) {\n var ctx = {\n plugin: plugin,\n key: null,\n seed: null,\n time: null,\n // number of reseeds so far\n reseeds: 0,\n // amount of data generated so far\n generated: 0,\n // no initial key bytes\n keyBytes: ''\n };\n\n // create 32 entropy pools (each is a message digest)\n var md = plugin.md;\n var pools = new Array(32);\n for(var i = 0; i < 32; ++i) {\n pools[i] = md.create();\n }\n ctx.pools = pools;\n\n // entropy pools are written to cyclically, starting at index 0\n ctx.pool = 0;\n\n /**\n * Generates random bytes. The bytes may be generated synchronously or\n * asynchronously. Web workers must use the asynchronous interface or\n * else the behavior is undefined.\n *\n * @param count the number of random bytes to generate.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return count random bytes as a string.\n */\n ctx.generate = function(count, callback) {\n // do synchronously\n if(!callback) {\n return ctx.generateSync(count);\n }\n\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n var b = forge.util.createBuffer();\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generate` call\n ctx.key = null;\n\n generate();\n\n function generate(err) {\n if(err) {\n return callback(err);\n }\n\n // sufficient bytes generated\n if(b.length() >= count) {\n return callback(null, b.getBytes(count));\n }\n\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n // prevent stack overflow\n return forge.util.nextTick(function() {\n _reseed(generate);\n });\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n\n forge.util.setImmediate(generate);\n }\n };\n\n /**\n * Generates random bytes synchronously.\n *\n * @param count the number of random bytes to generate.\n *\n * @return count random bytes as a string.\n */\n ctx.generateSync = function(count) {\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generateSync` call\n ctx.key = null;\n\n var b = forge.util.createBuffer();\n while(b.length() < count) {\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n _reseedSync();\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n }\n\n return b.getBytes(count);\n };\n\n /**\n * Private function that asynchronously reseeds a generator.\n *\n * @param callback(err) called once the operation completes.\n */\n function _reseed(callback) {\n if(ctx.pools[0].messageLength >= 32) {\n _seed();\n return callback();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.seedFile(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n ctx.collect(bytes);\n _seed();\n callback();\n });\n }\n\n /**\n * Private function that synchronously reseeds a generator.\n */\n function _reseedSync() {\n if(ctx.pools[0].messageLength >= 32) {\n return _seed();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.collect(ctx.seedFileSync(needed));\n _seed();\n }\n\n /**\n * Private function that seeds a generator once enough bytes are available.\n */\n function _seed() {\n // update reseed count\n ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;\n\n // goal is to update `key` via:\n // key = hash(key + s)\n // where 's' is all collected entropy from selected pools, then...\n\n // create a plugin-based message digest\n var md = ctx.plugin.md.create();\n\n // consume current key bytes\n md.update(ctx.keyBytes);\n\n // digest the entropy of pools whose index k meet the\n // condition 'n mod 2^k == 0' where n is the number of reseeds\n var _2powK = 1;\n for(var k = 0; k < 32; ++k) {\n if(ctx.reseeds % _2powK === 0) {\n md.update(ctx.pools[k].digest().getBytes());\n ctx.pools[k].start();\n }\n _2powK = _2powK << 1;\n }\n\n // get digest for key bytes\n ctx.keyBytes = md.digest().getBytes();\n\n // paranoid deviation from Fortuna:\n // update `seed` via `seed = hash(key)`\n // instead of initializing to zero once and only\n // ever incrementing it\n md.start();\n md.update(ctx.keyBytes);\n var seedBytes = md.digest().getBytes();\n\n // update state\n ctx.key = ctx.plugin.formatKey(ctx.keyBytes);\n ctx.seed = ctx.plugin.formatSeed(seedBytes);\n ctx.generated = 0;\n }\n\n /**\n * The built-in default seedFile. This seedFile is used when entropy\n * is needed immediately.\n *\n * @param needed the number of bytes that are needed.\n *\n * @return the random bytes.\n */\n function defaultSeedFile(needed) {\n // use window.crypto.getRandomValues strong source of entropy if available\n var getRandomValues = null;\n var globalScope = forge.util.globalScope;\n var _crypto = globalScope.crypto || globalScope.msCrypto;\n if(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n }\n\n var b = forge.util.createBuffer();\n if(getRandomValues) {\n while(b.length() < needed) {\n // max byte length is 65536 before QuotaExceededError is thrown\n // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues\n var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);\n var entropy = new Uint32Array(Math.floor(count));\n try {\n getRandomValues(entropy);\n for(var i = 0; i < entropy.length; ++i) {\n b.putInt32(entropy[i]);\n }\n } catch(e) {\n /* only ignore QuotaExceededError */\n if(!(typeof QuotaExceededError !== 'undefined' &&\n e instanceof QuotaExceededError)) {\n throw e;\n }\n }\n }\n }\n\n // be sad and add some weak random data\n if(b.length() < needed) {\n /* Draws from Park-Miller \"minimal standard\" 31 bit PRNG,\n implemented with David G. Carta's optimization: with 32 bit math\n and without division (Public Domain). */\n var hi, lo, next;\n var seed = Math.floor(Math.random() * 0x010000);\n while(b.length() < needed) {\n lo = 16807 * (seed & 0xFFFF);\n hi = 16807 * (seed >> 16);\n lo += (hi & 0x7FFF) << 16;\n lo += hi >> 15;\n lo = (lo & 0x7FFFFFFF) + (lo >> 31);\n seed = lo & 0xFFFFFFFF;\n\n // consume lower 3 bytes of seed\n for(var i = 0; i < 3; ++i) {\n // throw in more pseudo random\n next = seed >>> (i << 3);\n next ^= Math.floor(Math.random() * 0x0100);\n b.putByte(String.fromCharCode(next & 0xFF));\n }\n }\n }\n\n return b.getBytes(needed);\n }\n // initialize seed file APIs\n if(_crypto) {\n // use nodejs async API\n ctx.seedFile = function(needed, callback) {\n _crypto.randomBytes(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n callback(null, bytes.toString());\n });\n };\n // use nodejs sync API\n ctx.seedFileSync = function(needed) {\n return _crypto.randomBytes(needed).toString();\n };\n } else {\n ctx.seedFile = function(needed, callback) {\n try {\n callback(null, defaultSeedFile(needed));\n } catch(e) {\n callback(e);\n }\n };\n ctx.seedFileSync = defaultSeedFile;\n }\n\n /**\n * Adds entropy to a prng ctx's accumulator.\n *\n * @param bytes the bytes of entropy as a string.\n */\n ctx.collect = function(bytes) {\n // iterate over pools distributing entropy cyclically\n var count = bytes.length;\n for(var i = 0; i < count; ++i) {\n ctx.pools[ctx.pool].update(bytes.substr(i, 1));\n ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;\n }\n };\n\n /**\n * Collects an integer of n bits.\n *\n * @param i the integer entropy.\n * @param n the number of bits in the integer.\n */\n ctx.collectInt = function(i, n) {\n var bytes = '';\n for(var x = 0; x < n; x += 8) {\n bytes += String.fromCharCode((i >> x) & 0xFF);\n }\n ctx.collect(bytes);\n };\n\n /**\n * Registers a Web Worker to receive immediate entropy from the main thread.\n * This method is required until Web Workers can access the native crypto\n * API. This method should be called twice for each created worker, once in\n * the main thread, and once in the worker itself.\n *\n * @param worker the worker to register.\n */\n ctx.registerWorker = function(worker) {\n // worker receives random bytes\n if(worker === self) {\n ctx.seedFile = function(needed, callback) {\n function listener(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n self.removeEventListener('message', listener);\n callback(data.forge.prng.err, data.forge.prng.bytes);\n }\n }\n self.addEventListener('message', listener);\n self.postMessage({forge: {prng: {needed: needed}}});\n };\n } else {\n // main thread sends random bytes upon request\n var listener = function(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n ctx.seedFile(data.forge.prng.needed, function(err, bytes) {\n worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});\n });\n }\n };\n // TODO: do we need to remove the event listener when the worker dies?\n worker.addEventListener('message', listener);\n }\n };\n\n return ctx;\n};\n","/**\n * An API for getting cryptographically-secure random bytes. The bytes are\n * generated using the Fortuna algorithm devised by Bruce Schneier and\n * Niels Ferguson.\n *\n * Getting strong random bytes is not yet easy to do in javascript. The only\n * truish random entropy that can be collected is from the mouse, keyboard, or\n * from timing with respect to page loads, etc. This generator makes a poor\n * attempt at providing random bytes when those sources haven't yet provided\n * enough entropy to initially seed or to reseed the PRNG.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./sha256');\nrequire('./prng');\nrequire('./util');\n\n(function() {\n\n// forge.random already defined\nif(forge.random && forge.random.getBytes) {\n module.exports = forge.random;\n return;\n}\n\n(function(jQuery) {\n\n// the default prng plugin, uses AES-128\nvar prng_aes = {};\nvar _prng_aes_output = new Array(4);\nvar _prng_aes_buffer = forge.util.createBuffer();\nprng_aes.formatKey = function(key) {\n // convert the key into 32-bit integers\n var tmp = forge.util.createBuffer(key);\n key = new Array(4);\n key[0] = tmp.getInt32();\n key[1] = tmp.getInt32();\n key[2] = tmp.getInt32();\n key[3] = tmp.getInt32();\n\n // return the expanded key\n return forge.aes._expandKey(key, false);\n};\nprng_aes.formatSeed = function(seed) {\n // convert seed into 32-bit integers\n var tmp = forge.util.createBuffer(seed);\n seed = new Array(4);\n seed[0] = tmp.getInt32();\n seed[1] = tmp.getInt32();\n seed[2] = tmp.getInt32();\n seed[3] = tmp.getInt32();\n return seed;\n};\nprng_aes.cipher = function(key, seed) {\n forge.aes._updateBlock(key, seed, _prng_aes_output, false);\n _prng_aes_buffer.putInt32(_prng_aes_output[0]);\n _prng_aes_buffer.putInt32(_prng_aes_output[1]);\n _prng_aes_buffer.putInt32(_prng_aes_output[2]);\n _prng_aes_buffer.putInt32(_prng_aes_output[3]);\n return _prng_aes_buffer.getBytes();\n};\nprng_aes.increment = function(seed) {\n // FIXME: do we care about carry or signed issues?\n ++seed[3];\n return seed;\n};\nprng_aes.md = forge.md.sha256;\n\n/**\n * Creates a new PRNG.\n */\nfunction spawnPrng() {\n var ctx = forge.prng.create(prng_aes);\n\n /**\n * Gets random bytes. If a native secure crypto API is unavailable, this\n * method tries to make the bytes more unpredictable by drawing from data that\n * can be collected from the user of the browser, eg: mouse movement.\n *\n * If a callback is given, this method will be called asynchronously.\n *\n * @param count the number of random bytes to get.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytes = function(count, callback) {\n return ctx.generate(count, callback);\n };\n\n /**\n * Gets random bytes asynchronously. If a native secure crypto API is\n * unavailable, this method tries to make the bytes more unpredictable by\n * drawing from data that can be collected from the user of the browser,\n * eg: mouse movement.\n *\n * @param count the number of random bytes to get.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytesSync = function(count) {\n return ctx.generate(count);\n };\n\n return ctx;\n}\n\n// create default prng context\nvar _ctx = spawnPrng();\n\n// add other sources of entropy only if window.crypto.getRandomValues is not\n// available -- otherwise this source will be automatically used by the prng\nvar getRandomValues = null;\nvar globalScope = forge.util.globalScope;\nvar _crypto = globalScope.crypto || globalScope.msCrypto;\nif(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n}\n\nif(forge.options.usePureJavaScript ||\n (!forge.util.isNodejs && !getRandomValues)) {\n // if this is a web worker, do not use weak entropy, instead register to\n // receive strong entropy asynchronously from the main thread\n if(typeof window === 'undefined' || window.document === undefined) {\n // FIXME:\n }\n\n // get load time entropy\n _ctx.collectInt(+new Date(), 32);\n\n // add some entropy from navigator object\n if(typeof(navigator) !== 'undefined') {\n var _navBytes = '';\n for(var key in navigator) {\n try {\n if(typeof(navigator[key]) == 'string') {\n _navBytes += navigator[key];\n }\n } catch(e) {\n /* Some navigator keys might not be accessible, e.g. the geolocation\n attribute throws an exception if touched in Mozilla chrome://\n context.\n\n Silently ignore this and just don't use this as a source of\n entropy. */\n }\n }\n _ctx.collect(_navBytes);\n _navBytes = null;\n }\n\n // add mouse and keyboard collectors if jquery is available\n if(jQuery) {\n // set up mouse entropy capture\n jQuery().mousemove(function(e) {\n // add mouse coords\n _ctx.collectInt(e.clientX, 16);\n _ctx.collectInt(e.clientY, 16);\n });\n\n // set up keyboard entropy capture\n jQuery().keypress(function(e) {\n _ctx.collectInt(e.charCode, 8);\n });\n }\n}\n\n/* Random API */\nif(!forge.random) {\n forge.random = _ctx;\n} else {\n // extend forge.random with _ctx\n for(var key in _ctx) {\n forge.random[key] = _ctx[key];\n }\n}\n\n// expose spawn PRNG\nforge.random.createInstance = spawnPrng;\n\nmodule.exports = forge.random;\n\n})(typeof(jQuery) !== 'undefined' ? jQuery : null);\n\n})();\n","/**\n * RC2 implementation.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n *\n * Information on the RC2 cipher is available from RFC #2268,\n * http://www.ietf.org/rfc/rfc2268.txt\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar piTable = [\n 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,\n 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,\n 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,\n 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,\n 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1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0xfe, 0x7f, 0xc1, 0xad\n];\n\nvar s = [1, 2, 3, 5];\n\n/**\n * Rotate a word left by given number of bits.\n *\n * Bits that are shifted out on the left are put back in on the right\n * hand side.\n *\n * @param word The word to shift left.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar rol = function(word, bits) {\n return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));\n};\n\n/**\n * Rotate a word right by given number of bits.\n *\n * Bits that are shifted out on the right are put back in on the left\n * hand side.\n *\n * @param word The word to shift right.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar ror = function(word, bits) {\n return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);\n};\n\n/* RC2 API */\nmodule.exports = forge.rc2 = forge.rc2 || {};\n\n/**\n * Perform RC2 key expansion as per RFC #2268, section 2.\n *\n * @param key variable-length user key (between 1 and 128 bytes)\n * @param effKeyBits number of effective key bits (default: 128)\n * @return the expanded RC2 key (ByteBuffer of 128 bytes)\n */\nforge.rc2.expandKey = function(key, effKeyBits) {\n if(typeof key === 'string') {\n key = forge.util.createBuffer(key);\n }\n effKeyBits = effKeyBits || 128;\n\n /* introduce variables that match the names used in RFC #2268 */\n var L = key;\n var T = key.length();\n var T1 = effKeyBits;\n var T8 = Math.ceil(T1 / 8);\n var TM = 0xff >> (T1 & 0x07);\n var i;\n\n for(i = T; i < 128; i++) {\n L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);\n }\n\n L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);\n\n for(i = 127 - T8; i >= 0; i--) {\n L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);\n }\n\n return L;\n};\n\n/**\n * Creates a RC2 cipher object.\n *\n * @param key the symmetric key to use (as base for key generation).\n * @param bits the number of effective key bits.\n * @param encrypt false for decryption, true for encryption.\n *\n * @return the cipher.\n */\nvar createCipher = function(key, bits, encrypt) {\n var _finish = false, _input = null, _output = null, _iv = null;\n var mixRound, mashRound;\n var i, j, K = [];\n\n /* Expand key and fill into K[] Array */\n key = forge.rc2.expandKey(key, bits);\n for(i = 0; i < 64; i++) {\n K.push(key.getInt16Le());\n }\n\n if(encrypt) {\n /**\n * Perform one mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n R[i] = rol(R[i], s[i]);\n j++;\n }\n };\n\n /**\n * Perform one mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[R[(i + 3) % 4] & 63];\n }\n };\n } else {\n /**\n * Perform one r-mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] = ror(R[i], s[i]);\n R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n j--;\n }\n };\n\n /**\n * Perform one r-mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] -= K[R[(i + 3) % 4] & 63];\n }\n };\n }\n\n /**\n * Run the specified cipher execution plan.\n *\n * This function takes four words from the input buffer, applies the IV on\n * it (if requested) and runs the provided execution plan.\n *\n * The plan must be put together in form of a array of arrays. Where the\n * outer one is simply a list of steps to perform and the inner one needs\n * to have two elements: the first one telling how many rounds to perform,\n * the second one telling what to do (i.e. the function to call).\n *\n * @param {Array} plan The plan to execute.\n */\n var runPlan = function(plan) {\n var R = [];\n\n /* Get data from input buffer and fill the four words into R */\n for(i = 0; i < 4; i++) {\n var val = _input.getInt16Le();\n\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting, apply the IV first. */\n val ^= _iv.getInt16Le();\n } else {\n /* We're decryption, keep cipher text for next block. */\n _iv.putInt16Le(val);\n }\n }\n\n R.push(val & 0xffff);\n }\n\n /* Reset global \"j\" variable as per spec. */\n j = encrypt ? 0 : 63;\n\n /* Run execution plan. */\n for(var ptr = 0; ptr < plan.length; ptr++) {\n for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {\n plan[ptr][1](R);\n }\n }\n\n /* Write back result to output buffer. */\n for(i = 0; i < 4; i++) {\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting in CBC-mode, feed back encrypted bytes into\n IV buffer to carry it forward to next block. */\n _iv.putInt16Le(R[i]);\n } else {\n R[i] ^= _iv.getInt16Le();\n }\n }\n\n _output.putInt16Le(R[i]);\n }\n };\n\n /* Create cipher object */\n var cipher = null;\n cipher = {\n /**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * To use the cipher in CBC mode, iv may be given either as a string\n * of bytes, or as a byte buffer. For ECB mode, give null as iv.\n *\n * @param iv the initialization vector to use, null for ECB mode.\n * @param output the output the buffer to write to, null to create one.\n */\n start: function(iv, output) {\n if(iv) {\n /* CBC mode */\n if(typeof iv === 'string') {\n iv = forge.util.createBuffer(iv);\n }\n }\n\n _finish = false;\n _input = forge.util.createBuffer();\n _output = output || new forge.util.createBuffer();\n _iv = iv;\n\n cipher.output = _output;\n },\n\n /**\n * Updates the next block.\n *\n * @param input the buffer to read from.\n */\n update: function(input) {\n if(!_finish) {\n // not finishing, so fill the input buffer with more input\n _input.putBuffer(input);\n }\n\n while(_input.length() >= 8) {\n runPlan([\n [ 5, mixRound ],\n [ 1, mashRound ],\n [ 6, mixRound ],\n [ 1, mashRound ],\n [ 5, mixRound ]\n ]);\n }\n },\n\n /**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use, null for PKCS#7 padding,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\n finish: function(pad) {\n var rval = true;\n\n if(encrypt) {\n if(pad) {\n rval = pad(8, _input, !encrypt);\n } else {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (_input.length() === 8) ? 8 : (8 - _input.length());\n _input.fillWithByte(padding, padding);\n }\n }\n\n if(rval) {\n // do final update\n _finish = true;\n cipher.update();\n }\n\n if(!encrypt) {\n // check for error: input data not a multiple of block size\n rval = (_input.length() === 0);\n if(rval) {\n if(pad) {\n rval = pad(8, _output, !encrypt);\n } else {\n // ensure padding byte count is valid\n var len = _output.length();\n var count = _output.at(len - 1);\n\n if(count > len) {\n rval = false;\n } else {\n // trim off padding bytes\n _output.truncate(count);\n }\n }\n }\n }\n\n return rval;\n }\n };\n\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startEncrypting = function(key, iv, output) {\n var cipher = forge.rc2.createEncryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start encrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createEncryptionCipher = function(key, bits) {\n return createCipher(key, bits, true);\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startDecrypting = function(key, iv, output) {\n var cipher = forge.rc2.createDecryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start decrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createDecryptionCipher = function(key, bits) {\n return createCipher(key, bits, false);\n};\n","// Copyright (c) 2005 Tom Wu\n// All Rights Reserved.\n// See \"LICENSE\" for details.\n\n// Basic JavaScript BN library - subset useful for RSA encryption.\n\n/*\nLicensing (LICENSE)\n-------------------\n\nThis software is covered under the following copyright:\n*/\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a 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\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY\n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n/*\nAddress all questions regarding this license to:\n\n Tom Wu\n tjw@cs.Stanford.EDU\n*/\nvar forge = require('./forge');\n\nmodule.exports = forge.jsbn = forge.jsbn || {};\n\n// Bits per digit\nvar dbits;\n\n// JavaScript engine analysis\nvar canary = 0xdeadbeefcafe;\nvar j_lm = ((canary&0xffffff)==0xefcafe);\n\n// (public) Constructor\nfunction BigInteger(a,b,c) {\n this.data = [];\n if(a != null)\n if(\"number\" == typeof a) this.fromNumber(a,b,c);\n else if(b == null && \"string\" != typeof a) this.fromString(a,256);\n else this.fromString(a,b);\n}\nforge.jsbn.BigInteger = BigInteger;\n\n// return new, unset BigInteger\nfunction nbi() { return new BigInteger(null); }\n\n// am: Compute w_j += (x*this_i), propagate carries,\n// c is initial carry, returns final carry.\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\n// We need to select the fastest one that works in this environment.\n\n// am1: use a single mult and divide to get the high bits,\n// max digit bits should be 26 because\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\nfunction am1(i,x,w,j,c,n) {\n while(--n >= 0) {\n var v = x*this.data[i++]+w.data[j]+c;\n c = Math.floor(v/0x4000000);\n w.data[j++] = v&0x3ffffff;\n }\n return c;\n}\n// am2 avoids a big mult-and-extract completely.\n// Max digit bits should be <= 30 because we do bitwise ops\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\nfunction am2(i,x,w,j,c,n) {\n var xl = x&0x7fff, xh = x>>15;\n while(--n >= 0) {\n var l = this.data[i]&0x7fff;\n var h = this.data[i++]>>15;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);\n c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);\n w.data[j++] = l&0x3fffffff;\n }\n return c;\n}\n// Alternately, set max digit bits to 28 since some\n// browsers slow down when dealing with 32-bit numbers.\nfunction am3(i,x,w,j,c,n) {\n var xl = x&0x3fff, xh = x>>14;\n while(--n >= 0) {\n var l = this.data[i]&0x3fff;\n var h = this.data[i++]>>14;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;\n c = (l>>28)+(m>>14)+xh*h;\n w.data[j++] = l&0xfffffff;\n }\n return c;\n}\n\n// node.js (no browser)\nif(typeof(navigator) === 'undefined')\n{\n BigInteger.prototype.am = am3;\n dbits = 28;\n} else if(j_lm && (navigator.appName == \"Microsoft Internet Explorer\")) {\n BigInteger.prototype.am = am2;\n dbits = 30;\n} else if(j_lm && (navigator.appName != \"Netscape\")) {\n BigInteger.prototype.am = am1;\n dbits = 26;\n} else { // Mozilla/Netscape seems to prefer am3\n BigInteger.prototype.am = am3;\n dbits = 28;\n}\n\nBigInteger.prototype.DB = dbits;\nBigInteger.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}\n\n// (protected) set from integer value x, -DV <= x < DV\nfunction bnpFromInt(x) {\n this.t = 1;\n this.s = (x<0)?-1:0;\n if(x > 0) this.data[0] = x;\n else if(x < -1) this.data[0] = x+this.DV;\n else this.t = 0;\n}\n\n// return bigint initialized to value\nfunction nbv(i) { var r = nbi(); r.fromInt(i); return r; }\n\n// (protected) set from string and radix\nfunction bnpFromString(s,b) {\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 256) k = 8; // byte array\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else { this.fromRadix(s,b); return; }\n this.t = 0;\n this.s = 0;\n var i = s.length, mi = false, sh = 0;\n while(--i >= 0) {\n var x = (k==8)?s[i]&0xff:intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\") mi = true;\n continue;\n }\n mi = false;\n if(sh == 0)\n this.data[this.t++] = x;\n else if(sh+k > this.DB) {\n this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh));\n } else\n this.data[this.t-1] |= x<= this.DB) sh -= this.DB;\n }\n if(k == 8 && (s[0]&0x80) != 0) {\n this.s = -1;\n if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t;\n}\n\n// (public) return string representation in given radix\nfunction bnToString(b) {\n if(this.s < 0) return \"-\"+this.negate().toString(b);\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else return this.toRadix(b);\n var km = (1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }\n while(i >= 0) {\n if(p < k) {\n d = (this.data[i]&((1<>(p+=this.DB-k);\n } else {\n d = (this.data[i]>>(p-=k))&km;\n if(p <= 0) { p += this.DB; --i; }\n }\n if(d > 0) m = true;\n if(m) r += int2char(d);\n }\n }\n return m?r:\"0\";\n}\n\n// (public) -this\nfunction bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }\n\n// (public) |this|\nfunction bnAbs() { return (this.s<0)?this.negate():this; }\n\n// (public) return + if this > a, - if this < a, 0 if equal\nfunction bnCompareTo(a) {\n var r = this.s-a.s;\n if(r != 0) return r;\n var i = this.t;\n r = i-a.t;\n if(r != 0) return (this.s<0)?-r:r;\n while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;\n return 0;\n}\n\n// returns bit length of the integer x\nfunction nbits(x) {\n var r = 1, t;\n if((t=x>>>16) != 0) { x = t; r += 16; }\n if((t=x>>8) != 0) { x = t; r += 8; }\n if((t=x>>4) != 0) { x = t; r += 4; }\n if((t=x>>2) != 0) { x = t; r += 2; }\n if((t=x>>1) != 0) { x = t; r += 1; }\n return r;\n}\n\n// (public) return the number of bits in \"this\"\nfunction bnBitLength() {\n if(this.t <= 0) return 0;\n return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));\n}\n\n// (protected) r = this << n*DB\nfunction bnpDLShiftTo(n,r) {\n var i;\n for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];\n for(i = n-1; i >= 0; --i) r.data[i] = 0;\n r.t = this.t+n;\n r.s = this.s;\n}\n\n// (protected) r = this >> n*DB\nfunction bnpDRShiftTo(n,r) {\n for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];\n r.t = Math.max(this.t-n,0);\n r.s = this.s;\n}\n\n// (protected) r = this << n\nfunction bnpLShiftTo(n,r) {\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<= 0; --i) {\n r.data[i+ds+1] = (this.data[i]>>cbs)|c;\n c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0;\n r.data[ds] = c;\n r.t = this.t+ds+1;\n r.s = this.s;\n r.clamp();\n}\n\n// (protected) r = this >> n\nfunction bnpRShiftTo(n,r) {\n r.s = this.s;\n var ds = Math.floor(n/this.DB);\n if(ds >= this.t) { r.t = 0; return; }\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<>bs;\n for(var i = ds+1; i < this.t; ++i) {\n r.data[i-ds-1] |= (this.data[i]&bm)<>bs;\n }\n if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB;\n }\n if(a.t < this.t) {\n c -= a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n } else {\n c += this.s;\n while(i < a.t) {\n c -= a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c -= a.s;\n }\n r.s = (c<0)?-1:0;\n if(c < -1) r.data[i++] = this.DV+c;\n else if(c > 0) r.data[i++] = c;\n r.t = i;\n r.clamp();\n}\n\n// (protected) r = this * a, r != this,a (HAC 14.12)\n// \"this\" should be the larger one if appropriate.\nfunction bnpMultiplyTo(a,r) {\n var x = this.abs(), y = a.abs();\n var i = x.t;\n r.t = i+y.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);\n r.s = 0;\n r.clamp();\n if(this.s != a.s) BigInteger.ZERO.subTo(r,r);\n}\n\n// (protected) r = this^2, r != this (HAC 14.16)\nfunction bnpSquareTo(r) {\n var x = this.abs();\n var i = r.t = 2*x.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < x.t-1; ++i) {\n var c = x.am(i,x.data[i],r,2*i,0,1);\n if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {\n r.data[i+x.t] -= x.DV;\n r.data[i+x.t+1] = 1;\n }\n }\n if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);\n r.s = 0;\n r.clamp();\n}\n\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\n// r != q, this != m. q or r may be null.\nfunction bnpDivRemTo(m,q,r) {\n var pm = m.abs();\n if(pm.t <= 0) return;\n var pt = this.abs();\n if(pt.t < pm.t) {\n if(q != null) q.fromInt(0);\n if(r != null) this.copyTo(r);\n return;\n }\n if(r == null) r = nbi();\n var y = nbi(), ts = this.s, ms = m.s;\n var nsh = this.DB-nbits(pm.data[pm.t-1]);\t// normalize modulus\n if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }\n var ys = y.t;\n var y0 = y.data[ys-1];\n if(y0 == 0) return;\n var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0);\n var d1 = this.FV/yt, d2 = (1<= 0) {\n r.data[r.t++] = 1;\n r.subTo(t,r);\n }\n BigInteger.ONE.dlShiftTo(ys,t);\n t.subTo(y,y);\t// \"negative\" y so we can replace sub with am later\n while(y.t < ys) y.data[y.t++] = 0;\n while(--j >= 0) {\n // Estimate quotient digit\n var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);\n if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) {\t// Try it out\n y.dlShiftTo(j,t);\n r.subTo(t,r);\n while(r.data[i] < --qd) r.subTo(t,r);\n }\n }\n if(q != null) {\n r.drShiftTo(ys,q);\n if(ts != ms) BigInteger.ZERO.subTo(q,q);\n }\n r.t = ys;\n r.clamp();\n if(nsh > 0) r.rShiftTo(nsh,r);\t// Denormalize remainder\n if(ts < 0) BigInteger.ZERO.subTo(r,r);\n}\n\n// (public) this mod a\nfunction bnMod(a) {\n var r = nbi();\n this.abs().divRemTo(a,null,r);\n if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);\n return r;\n}\n\n// Modular reduction using \"classic\" algorithm\nfunction Classic(m) { this.m = m; }\nfunction cConvert(x) {\n if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);\n else return x;\n}\nfunction cRevert(x) { return x; }\nfunction cReduce(x) { x.divRemTo(this.m,null,x); }\nfunction cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\nfunction cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\nClassic.prototype.convert = cConvert;\nClassic.prototype.revert = cRevert;\nClassic.prototype.reduce = cReduce;\nClassic.prototype.mulTo = cMulTo;\nClassic.prototype.sqrTo = cSqrTo;\n\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\n// justification:\n// xy == 1 (mod m)\n// xy = 1+km\n// xy(2-xy) = (1+km)(1-km)\n// x[y(2-xy)] = 1-k^2m^2\n// x[y(2-xy)] == 1 (mod m^2)\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\nfunction bnpInvDigit() {\n if(this.t < 1) return 0;\n var x = this.data[0];\n if((x&1) == 0) return 0;\n var y = x&3;\t\t// y == 1/x mod 2^2\n y = (y*(2-(x&0xf)*y))&0xf;\t// y == 1/x mod 2^4\n y = (y*(2-(x&0xff)*y))&0xff;\t// y == 1/x mod 2^8\n y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;\t// y == 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y*(2-x*y%this.DV))%this.DV;\t\t// y == 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return (y>0)?this.DV-y:-y;\n}\n\n// Montgomery reduction\nfunction Montgomery(m) {\n this.m = m;\n this.mp = m.invDigit();\n this.mpl = this.mp&0x7fff;\n this.mph = this.mp>>15;\n this.um = (1<<(m.DB-15))-1;\n this.mt2 = 2*m.t;\n}\n\n// xR mod m\nfunction montConvert(x) {\n var r = nbi();\n x.abs().dlShiftTo(this.m.t,r);\n r.divRemTo(this.m,null,r);\n if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);\n return r;\n}\n\n// x/R mod m\nfunction montRevert(x) {\n var r = nbi();\n x.copyTo(r);\n this.reduce(r);\n return r;\n}\n\n// x = x/R mod m (HAC 14.32)\nfunction montReduce(x) {\n while(x.t <= this.mt2)\t// pad x so am has enough room later\n x.data[x.t++] = 0;\n for(var i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x.data[i]*mp mod DV\n var j = x.data[i]&0x7fff;\n var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;\n // use am to combine the multiply-shift-add into one call\n j = i+this.m.t;\n x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);\n // propagate carry\n while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }\n }\n x.clamp();\n x.drShiftTo(this.m.t,x);\n if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n// r = \"x^2/R mod m\"; x != r\nfunction montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n// r = \"xy/R mod m\"; x,y != r\nfunction montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nMontgomery.prototype.convert = montConvert;\nMontgomery.prototype.revert = montRevert;\nMontgomery.prototype.reduce = montReduce;\nMontgomery.prototype.mulTo = montMulTo;\nMontgomery.prototype.sqrTo = montSqrTo;\n\n// (protected) true iff this is even\nfunction bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }\n\n// (protected) this^e, e < 2^32, doing sqr and mul with \"r\" (HAC 14.79)\nfunction bnpExp(e,z) {\n if(e > 0xffffffff || e < 1) return BigInteger.ONE;\n var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;\n g.copyTo(r);\n while(--i >= 0) {\n z.sqrTo(r,r2);\n if((e&(1< 0) z.mulTo(r2,g,r);\n else { var t = r; r = r2; r2 = t; }\n }\n return z.revert(r);\n}\n\n// (public) this^e % m, 0 <= e < 2^32\nfunction bnModPowInt(e,m) {\n var z;\n if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);\n return this.exp(e,z);\n}\n\n// protected\nBigInteger.prototype.copyTo = bnpCopyTo;\nBigInteger.prototype.fromInt = bnpFromInt;\nBigInteger.prototype.fromString = bnpFromString;\nBigInteger.prototype.clamp = bnpClamp;\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\nBigInteger.prototype.subTo = bnpSubTo;\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\nBigInteger.prototype.squareTo = bnpSquareTo;\nBigInteger.prototype.divRemTo = bnpDivRemTo;\nBigInteger.prototype.invDigit = bnpInvDigit;\nBigInteger.prototype.isEven = bnpIsEven;\nBigInteger.prototype.exp = bnpExp;\n\n// public\nBigInteger.prototype.toString = bnToString;\nBigInteger.prototype.negate = bnNegate;\nBigInteger.prototype.abs = bnAbs;\nBigInteger.prototype.compareTo = bnCompareTo;\nBigInteger.prototype.bitLength = bnBitLength;\nBigInteger.prototype.mod = bnMod;\nBigInteger.prototype.modPowInt = bnModPowInt;\n\n// \"constants\"\nBigInteger.ZERO = nbv(0);\nBigInteger.ONE = nbv(1);\n\n// jsbn2 lib\n\n//Copyright (c) 2005-2009 Tom Wu\n//All Rights Reserved.\n//See \"LICENSE\" for details (See jsbn.js for LICENSE).\n\n//Extended JavaScript BN functions, required for RSA private ops.\n\n//Version 1.1: new BigInteger(\"0\", 10) returns \"proper\" zero\n\n//(public)\nfunction bnClone() { var r = nbi(); this.copyTo(r); return r; }\n\n//(public) return value as integer\nfunction bnIntValue() {\nif(this.s < 0) {\n if(this.t == 1) return this.data[0]-this.DV;\n else if(this.t == 0) return -1;\n} else if(this.t == 1) return this.data[0];\nelse if(this.t == 0) return 0;\n// assumes 16 < DB < 32\nreturn ((this.data[1]&((1<<(32-this.DB))-1))<>24; }\n\n//(public) return value as short (assumes DB>=16)\nfunction bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }\n\n//(protected) return x s.t. r^x < DV\nfunction bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }\n\n//(public) 0 if this == 0, 1 if this > 0\nfunction bnSigNum() {\nif(this.s < 0) return -1;\nelse if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;\nelse return 1;\n}\n\n//(protected) convert to radix string\nfunction bnpToRadix(b) {\nif(b == null) b = 10;\nif(this.signum() == 0 || b < 2 || b > 36) return \"0\";\nvar cs = this.chunkSize(b);\nvar a = Math.pow(b,cs);\nvar d = nbv(a), y = nbi(), z = nbi(), r = \"\";\nthis.divRemTo(d,y,z);\nwhile(y.signum() > 0) {\n r = (a+z.intValue()).toString(b).substr(1) + r;\n y.divRemTo(d,y,z);\n}\nreturn z.intValue().toString(b) + r;\n}\n\n//(protected) convert from radix string\nfunction bnpFromRadix(s,b) {\nthis.fromInt(0);\nif(b == null) b = 10;\nvar cs = this.chunkSize(b);\nvar d = Math.pow(b,cs), mi = false, j = 0, w = 0;\nfor(var i = 0; i < s.length; ++i) {\n var x = intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\" && this.signum() == 0) mi = true;\n continue;\n }\n w = b*w+x;\n if(++j >= cs) {\n this.dMultiply(d);\n this.dAddOffset(w,0);\n j = 0;\n w = 0;\n }\n}\nif(j > 0) {\n this.dMultiply(Math.pow(b,j));\n this.dAddOffset(w,0);\n}\nif(mi) BigInteger.ZERO.subTo(this,this);\n}\n\n//(protected) alternate constructor\nfunction bnpFromNumber(a,b,c) {\nif(\"number\" == typeof b) {\n // new BigInteger(int,int,RNG)\n if(a < 2) this.fromInt(1);\n else {\n this.fromNumber(a,c);\n if(!this.testBit(a-1)) // force MSB set\n this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);\n if(this.isEven()) this.dAddOffset(1,0); // force odd\n while(!this.isProbablePrime(b)) {\n this.dAddOffset(2,0);\n if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);\n }\n }\n} else {\n // new BigInteger(int,RNG)\n var x = new Array(), t = a&7;\n x.length = (a>>3)+1;\n b.nextBytes(x);\n if(t > 0) x[0] &= ((1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)\n r[k++] = d|(this.s<<(this.DB-p));\n while(i >= 0) {\n if(p < 8) {\n d = (this.data[i]&((1<>(p+=this.DB-8);\n } else {\n d = (this.data[i]>>(p-=8))&0xff;\n if(p <= 0) { p += this.DB; --i; }\n }\n if((d&0x80) != 0) d |= -256;\n if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;\n if(k > 0 || d != this.s) r[k++] = d;\n }\n}\nreturn r;\n}\n\nfunction bnEquals(a) { return(this.compareTo(a)==0); }\nfunction bnMin(a) { return(this.compareTo(a)<0)?this:a; }\nfunction bnMax(a) { return(this.compareTo(a)>0)?this:a; }\n\n//(protected) r = this op a (bitwise)\nfunction bnpBitwiseTo(a,op,r) {\nvar i, f, m = Math.min(a.t,this.t);\nfor(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);\nif(a.t < this.t) {\n f = a.s&this.DM;\n for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);\n r.t = this.t;\n} else {\n f = this.s&this.DM;\n for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);\n r.t = a.t;\n}\nr.s = op(this.s,a.s);\nr.clamp();\n}\n\n//(public) this & a\nfunction op_and(x,y) { return x&y; }\nfunction bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }\n\n//(public) this | a\nfunction op_or(x,y) { return x|y; }\nfunction bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }\n\n//(public) this ^ a\nfunction op_xor(x,y) { return x^y; }\nfunction bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }\n\n//(public) this & ~a\nfunction op_andnot(x,y) { return x&~y; }\nfunction bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }\n\n//(public) ~this\nfunction bnNot() {\nvar r = nbi();\nfor(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];\nr.t = this.t;\nr.s = ~this.s;\nreturn r;\n}\n\n//(public) this << n\nfunction bnShiftLeft(n) {\nvar r = nbi();\nif(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);\nreturn r;\n}\n\n//(public) this >> n\nfunction bnShiftRight(n) {\nvar r = nbi();\nif(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);\nreturn r;\n}\n\n//return index of lowest 1-bit in x, x < 2^31\nfunction lbit(x) {\nif(x == 0) return -1;\nvar r = 0;\nif((x&0xffff) == 0) { x >>= 16; r += 16; }\nif((x&0xff) == 0) { x >>= 8; r += 8; }\nif((x&0xf) == 0) { x >>= 4; r += 4; }\nif((x&3) == 0) { x >>= 2; r += 2; }\nif((x&1) == 0) ++r;\nreturn r;\n}\n\n//(public) returns index of lowest 1-bit (or -1 if none)\nfunction bnGetLowestSetBit() {\nfor(var i = 0; i < this.t; ++i)\n if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);\nif(this.s < 0) return this.t*this.DB;\nreturn -1;\n}\n\n//return number of 1 bits in x\nfunction cbit(x) {\nvar r = 0;\nwhile(x != 0) { x &= x-1; ++r; }\nreturn r;\n}\n\n//(public) return number of set bits\nfunction bnBitCount() {\nvar r = 0, x = this.s&this.DM;\nfor(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);\nreturn r;\n}\n\n//(public) true iff nth bit is set\nfunction bnTestBit(n) {\nvar j = Math.floor(n/this.DB);\nif(j >= this.t) return(this.s!=0);\nreturn((this.data[j]&(1<<(n%this.DB)))!=0);\n}\n\n//(protected) this op (1<>= this.DB;\n}\nif(a.t < this.t) {\n c += a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n} else {\n c += this.s;\n while(i < a.t) {\n c += a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += a.s;\n}\nr.s = (c<0)?-1:0;\nif(c > 0) r.data[i++] = c;\nelse if(c < -1) r.data[i++] = this.DV+c;\nr.t = i;\nr.clamp();\n}\n\n//(public) this + a\nfunction bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }\n\n//(public) this - a\nfunction bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }\n\n//(public) this * a\nfunction bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }\n\n//(public) this / a\nfunction bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }\n\n//(public) this % a\nfunction bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }\n\n//(public) [this/a,this%a]\nfunction bnDivideAndRemainder(a) {\nvar q = nbi(), r = nbi();\nthis.divRemTo(a,q,r);\nreturn new Array(q,r);\n}\n\n//(protected) this *= n, this >= 0, 1 < n < DV\nfunction bnpDMultiply(n) {\nthis.data[this.t] = this.am(0,n-1,this,0,0,this.t);\n++this.t;\nthis.clamp();\n}\n\n//(protected) this += n << w words, this >= 0\nfunction bnpDAddOffset(n,w) {\nif(n == 0) return;\nwhile(this.t <= w) this.data[this.t++] = 0;\nthis.data[w] += n;\nwhile(this.data[w] >= this.DV) {\n this.data[w] -= this.DV;\n if(++w >= this.t) this.data[this.t++] = 0;\n ++this.data[w];\n}\n}\n\n//A \"null\" reducer\nfunction NullExp() {}\nfunction nNop(x) { return x; }\nfunction nMulTo(x,y,r) { x.multiplyTo(y,r); }\nfunction nSqrTo(x,r) { x.squareTo(r); }\n\nNullExp.prototype.convert = nNop;\nNullExp.prototype.revert = nNop;\nNullExp.prototype.mulTo = nMulTo;\nNullExp.prototype.sqrTo = nSqrTo;\n\n//(public) this^e\nfunction bnPow(e) { return this.exp(e,new NullExp()); }\n\n//(protected) r = lower n words of \"this * a\", a.t <= n\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyLowerTo(a,n,r) {\nvar i = Math.min(this.t+a.t,n);\nr.s = 0; // assumes a,this >= 0\nr.t = i;\nwhile(i > 0) r.data[--i] = 0;\nvar j;\nfor(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t);\nfor(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);\nr.clamp();\n}\n\n//(protected) r = \"this * a\" without lower n words, n > 0\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyUpperTo(a,n,r) {\n--n;\nvar i = r.t = this.t+a.t-n;\nr.s = 0; // assumes a,this >= 0\nwhile(--i >= 0) r.data[i] = 0;\nfor(i = Math.max(n-this.t,0); i < a.t; ++i)\n r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);\nr.clamp();\nr.drShiftTo(1,r);\n}\n\n//Barrett modular reduction\nfunction Barrett(m) {\n// setup Barrett\nthis.r2 = nbi();\nthis.q3 = nbi();\nBigInteger.ONE.dlShiftTo(2*m.t,this.r2);\nthis.mu = this.r2.divide(m);\nthis.m = m;\n}\n\nfunction barrettConvert(x) {\nif(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);\nelse if(x.compareTo(this.m) < 0) return x;\nelse { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }\n}\n\nfunction barrettRevert(x) { return x; }\n\n//x = x mod m (HAC 14.42)\nfunction barrettReduce(x) {\nx.drShiftTo(this.m.t-1,this.r2);\nif(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\nthis.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\nthis.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\nwhile(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\nx.subTo(this.r2,x);\nwhile(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n//r = x^2 mod m; x != r\nfunction barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n//r = x*y mod m; x,y != r\nfunction barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nBarrett.prototype.convert = barrettConvert;\nBarrett.prototype.revert = barrettRevert;\nBarrett.prototype.reduce = barrettReduce;\nBarrett.prototype.mulTo = barrettMulTo;\nBarrett.prototype.sqrTo = barrettSqrTo;\n\n//(public) this^e % m (HAC 14.85)\nfunction bnModPow(e,m) {\nvar i = e.bitLength(), k, r = nbv(1), z;\nif(i <= 0) return r;\nelse if(i < 18) k = 1;\nelse if(i < 48) k = 3;\nelse if(i < 144) k = 4;\nelse if(i < 768) k = 5;\nelse k = 6;\nif(i < 8)\n z = new Classic(m);\nelse if(m.isEven())\n z = new Barrett(m);\nelse\n z = new Montgomery(m);\n\n// precomputation\nvar g = new Array(), n = 3, k1 = k-1, km = (1< 1) {\n var g2 = nbi();\n z.sqrTo(g[1],g2);\n while(n <= km) {\n g[n] = nbi();\n z.mulTo(g2,g[n-2],g[n]);\n n += 2;\n }\n}\n\nvar j = e.t-1, w, is1 = true, r2 = nbi(), t;\ni = nbits(e.data[j])-1;\nwhile(j >= 0) {\n if(i >= k1) w = (e.data[j]>>(i-k1))&km;\n else {\n w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);\n if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);\n }\n\n n = k;\n while((w&1) == 0) { w >>= 1; --n; }\n if((i -= n) < 0) { i += this.DB; --j; }\n if(is1) { // ret == 1, don't bother squaring or multiplying it\n g[w].copyTo(r);\n is1 = false;\n } else {\n while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }\n if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }\n z.mulTo(r2,g[w],r);\n }\n\n while(j >= 0 && (e.data[j]&(1< 0) {\n x.rShiftTo(g,x);\n y.rShiftTo(g,y);\n}\nwhile(x.signum() > 0) {\n if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);\n if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);\n if(x.compareTo(y) >= 0) {\n x.subTo(y,x);\n x.rShiftTo(1,x);\n } else {\n y.subTo(x,y);\n y.rShiftTo(1,y);\n }\n}\nif(g > 0) y.lShiftTo(g,y);\nreturn y;\n}\n\n//(protected) this % n, n < 2^26\nfunction bnpModInt(n) {\nif(n <= 0) return 0;\nvar d = this.DV%n, r = (this.s<0)?n-1:0;\nif(this.t > 0)\n if(d == 0) r = this.data[0]%n;\n else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;\nreturn r;\n}\n\n//(public) 1/this % m (HAC 14.61)\nfunction bnModInverse(m) {\nvar ac = m.isEven();\nif((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;\nvar u = m.clone(), v = this.clone();\nvar a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);\nwhile(u.signum() != 0) {\n while(u.isEven()) {\n u.rShiftTo(1,u);\n if(ac) {\n if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }\n a.rShiftTo(1,a);\n } else if(!b.isEven()) b.subTo(m,b);\n b.rShiftTo(1,b);\n }\n while(v.isEven()) {\n v.rShiftTo(1,v);\n if(ac) {\n if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }\n c.rShiftTo(1,c);\n } else if(!d.isEven()) d.subTo(m,d);\n d.rShiftTo(1,d);\n }\n if(u.compareTo(v) >= 0) {\n u.subTo(v,u);\n if(ac) a.subTo(c,a);\n b.subTo(d,b);\n } else {\n v.subTo(u,v);\n if(ac) c.subTo(a,c);\n d.subTo(b,d);\n }\n}\nif(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;\nif(d.compareTo(m) >= 0) return d.subtract(m);\nif(d.signum() < 0) d.addTo(m,d); else return d;\nif(d.signum() < 0) return d.add(m); else return d;\n}\n\nvar lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];\nvar lplim = (1<<26)/lowprimes[lowprimes.length-1];\n\n//(public) test primality with certainty >= 1-.5^t\nfunction bnIsProbablePrime(t) {\nvar i, x = this.abs();\nif(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {\n for(i = 0; i < lowprimes.length; ++i)\n if(x.data[0] == lowprimes[i]) return true;\n return false;\n}\nif(x.isEven()) return false;\ni = 1;\nwhile(i < lowprimes.length) {\n var m = lowprimes[i], j = i+1;\n while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];\n m = x.modInt(m);\n while(i < j) if(m%lowprimes[i++] == 0) return false;\n}\nreturn x.millerRabin(t);\n}\n\n//(protected) true if probably prime (HAC 4.24, Miller-Rabin)\nfunction bnpMillerRabin(t) {\nvar n1 = this.subtract(BigInteger.ONE);\nvar k = n1.getLowestSetBit();\nif(k <= 0) return false;\nvar r = n1.shiftRight(k);\nvar prng = bnGetPrng();\nvar a;\nfor(var i = 0; i < t; ++i) {\n // select witness 'a' at random from between 1 and n1\n do {\n a = new BigInteger(this.bitLength(), prng);\n }\n while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0);\n var y = a.modPow(r,this);\n if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {\n var j = 1;\n while(j++ < k && y.compareTo(n1) != 0) {\n y = y.modPowInt(2,this);\n if(y.compareTo(BigInteger.ONE) == 0) return false;\n }\n if(y.compareTo(n1) != 0) return false;\n }\n}\nreturn true;\n}\n\n// get pseudo random number generator\nfunction bnGetPrng() {\n // create prng with api that matches BigInteger secure random\n return {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n for(var i = 0; i < x.length; ++i) {\n x[i] = Math.floor(Math.random() * 0x0100);\n }\n }\n };\n}\n\n//protected\nBigInteger.prototype.chunkSize = bnpChunkSize;\nBigInteger.prototype.toRadix = bnpToRadix;\nBigInteger.prototype.fromRadix = bnpFromRadix;\nBigInteger.prototype.fromNumber = bnpFromNumber;\nBigInteger.prototype.bitwiseTo = bnpBitwiseTo;\nBigInteger.prototype.changeBit = bnpChangeBit;\nBigInteger.prototype.addTo = bnpAddTo;\nBigInteger.prototype.dMultiply = bnpDMultiply;\nBigInteger.prototype.dAddOffset = bnpDAddOffset;\nBigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;\nBigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;\nBigInteger.prototype.modInt = bnpModInt;\nBigInteger.prototype.millerRabin = bnpMillerRabin;\n\n//public\nBigInteger.prototype.clone = bnClone;\nBigInteger.prototype.intValue = bnIntValue;\nBigInteger.prototype.byteValue = bnByteValue;\nBigInteger.prototype.shortValue = bnShortValue;\nBigInteger.prototype.signum = bnSigNum;\nBigInteger.prototype.toByteArray = bnToByteArray;\nBigInteger.prototype.equals = bnEquals;\nBigInteger.prototype.min = bnMin;\nBigInteger.prototype.max = bnMax;\nBigInteger.prototype.and = bnAnd;\nBigInteger.prototype.or = bnOr;\nBigInteger.prototype.xor = bnXor;\nBigInteger.prototype.andNot = bnAndNot;\nBigInteger.prototype.not = bnNot;\nBigInteger.prototype.shiftLeft = bnShiftLeft;\nBigInteger.prototype.shiftRight = bnShiftRight;\nBigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;\nBigInteger.prototype.bitCount = bnBitCount;\nBigInteger.prototype.testBit = bnTestBit;\nBigInteger.prototype.setBit = bnSetBit;\nBigInteger.prototype.clearBit = bnClearBit;\nBigInteger.prototype.flipBit = bnFlipBit;\nBigInteger.prototype.add = bnAdd;\nBigInteger.prototype.subtract = bnSubtract;\nBigInteger.prototype.multiply = bnMultiply;\nBigInteger.prototype.divide = bnDivide;\nBigInteger.prototype.remainder = bnRemainder;\nBigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;\nBigInteger.prototype.modPow = bnModPow;\nBigInteger.prototype.modInverse = bnModInverse;\nBigInteger.prototype.pow = bnPow;\nBigInteger.prototype.gcd = bnGCD;\nBigInteger.prototype.isProbablePrime = bnIsProbablePrime;\n\n//BigInteger interfaces not implemented in jsbn:\n\n//BigInteger(int signum, byte[] magnitude)\n//double doubleValue()\n//float floatValue()\n//int hashCode()\n//long longValue()\n//static BigInteger valueOf(long val)\n","/**\n * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha1 = module.exports = forge.sha1 = forge.sha1 || {};\nforge.md.sha1 = forge.md.algorithms.sha1 = sha1;\n\n/**\n * Creates a SHA-1 message digest object.\n *\n * @return a message digest object.\n */\nsha1.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-1 state contains five 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(80);\n\n // message digest object\n var md = {\n algorithm: 'sha1',\n blockLength: 64,\n digestLength: 20,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476,\n h4: 0xC3D2E1F0\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-1 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n return rval;\n };\n\n return md;\n};\n\n// sha-1 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-1 state with the given byte buffer.\n *\n * @param s the SHA-1 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, e, f, i;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 80 32-bit words according to SHA-1 algorithm\n // and for 32-79 using Max Locktyukhin's optimization\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n t = bytes.getInt32();\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 20; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 2\n for(; i < 32; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 40; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 3\n for(; i < 60; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = (b & c) | (d & (b ^ c));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 4\n for(; i < 80; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Partial implementation of PKCS#1 v2.2: RSA-OEAP\n *\n * Modified but based on the following MIT and BSD licensed code:\n *\n * https://github.com/kjur/jsjws/blob/master/rsa.js:\n *\n * The 'jsjws'(JSON Web Signature JavaScript Library) License\n *\n * Copyright (c) 2012 Kenji Urushima\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:\n *\n * RSAES-OAEP.js\n * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $\n * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)\n * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.\n * Contact: ellis@nukinetics.com\n * Distributed under the BSD License.\n *\n * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125\n *\n * @author Evan Jones (http://evanjones.ca/)\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./sha1');\n\n// shortcut for PKCS#1 API\nvar pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {};\n\n/**\n * Encode the given RSAES-OAEP message (M) using key, with optional label (L)\n * and seed.\n *\n * This method does not perform RSA encryption, it only encodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param message the message to encode.\n * @param options the options to use:\n * label an optional label to use.\n * seed the seed to use.\n * md the message digest object to use, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the encoded message bytes.\n */\npkcs1.encode_rsa_oaep = function(key, message, options) {\n // parse arguments\n var label;\n var seed;\n var md;\n var mgf1Md;\n // legacy args (label, seed, md)\n if(typeof options === 'string') {\n label = options;\n seed = arguments[3] || undefined;\n md = arguments[4] || undefined;\n } else if(options) {\n label = options.label || undefined;\n seed = options.seed || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // default OAEP to SHA-1 message digest\n if(!md) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n // compute length in bytes and check output\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n var maxLength = keyLength - 2 * md.digestLength - 2;\n if(message.length > maxLength) {\n var error = new Error('RSAES-OAEP input message length is too long.');\n error.length = message.length;\n error.maxLength = maxLength;\n throw error;\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest();\n\n var PS = '';\n var PS_length = maxLength - message.length;\n for(var i = 0; i < PS_length; i++) {\n PS += '\\x00';\n }\n\n var DB = lHash.getBytes() + PS + '\\x01' + message;\n\n if(!seed) {\n seed = forge.random.getBytes(md.digestLength);\n } else if(seed.length !== md.digestLength) {\n var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +\n 'match the digest length.');\n error.seedLength = seed.length;\n error.digestLength = md.digestLength;\n throw error;\n }\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);\n\n // return encoded message\n return '\\x00' + maskedSeed + maskedDB;\n};\n\n/**\n * Decode the given RSAES-OAEP encoded message (EM) using key, with optional\n * label (L).\n *\n * This method does not perform RSA decryption, it only decodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param em the encoded message to decode.\n * @param options the options to use:\n * label an optional label to use.\n * md the message digest object to use for OAEP, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the decoded message bytes.\n */\npkcs1.decode_rsa_oaep = function(key, em, options) {\n // parse args\n var label;\n var md;\n var mgf1Md;\n // legacy args\n if(typeof options === 'string') {\n label = options;\n md = arguments[3] || undefined;\n } else if(options) {\n label = options.label || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // compute length in bytes\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n\n if(em.length !== keyLength) {\n var error = new Error('RSAES-OAEP encoded message length is invalid.');\n error.length = em.length;\n error.expectedLength = keyLength;\n throw error;\n }\n\n // default OAEP to SHA-1 message digest\n if(md === undefined) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n if(keyLength < 2 * md.digestLength + 2) {\n throw new Error('RSAES-OAEP key is too short for the hash function.');\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest().getBytes();\n\n // split the message into its parts\n var y = em.charAt(0);\n var maskedSeed = em.substring(1, md.digestLength + 1);\n var maskedDB = em.substring(1 + md.digestLength);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);\n\n var lHashPrime = db.substring(0, md.digestLength);\n\n // constant time check that all values match what is expected\n var error = (y !== '\\x00');\n\n // constant time check lHash vs lHashPrime\n for(var i = 0; i < md.digestLength; ++i) {\n error |= (lHash.charAt(i) !== lHashPrime.charAt(i));\n }\n\n // \"constant time\" find the 0x1 byte separating the padding (zeros) from the\n // message\n // TODO: It must be possible to do this in a better/smarter way?\n var in_ps = 1;\n var index = md.digestLength;\n for(var j = md.digestLength; j < db.length; j++) {\n var code = db.charCodeAt(j);\n\n var is_0 = (code & 0x1) ^ 0x1;\n\n // non-zero if not 0 or 1 in the ps section\n var error_mask = in_ps ? 0xfffe : 0x0000;\n error |= (code & error_mask);\n\n // latch in_ps to zero after we find 0x1\n in_ps = in_ps & is_0;\n index += in_ps;\n }\n\n if(error || db.charCodeAt(index) !== 0x1) {\n throw new Error('Invalid RSAES-OAEP padding.');\n }\n\n return db.substring(index + 1);\n};\n\nfunction rsa_mgf1(seed, maskLength, hash) {\n // default to SHA-1 message digest\n if(!hash) {\n hash = forge.md.sha1.create();\n }\n var t = '';\n var count = Math.ceil(maskLength / hash.digestLength);\n for(var i = 0; i < count; ++i) {\n var c = String.fromCharCode(\n (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);\n hash.start();\n hash.update(seed + c);\n t += hash.digest().getBytes();\n }\n return t.substring(0, maskLength);\n}\n","/**\n * Prime number generation API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./jsbn');\nrequire('./random');\n\n(function() {\n\n// forge.prime already defined\nif(forge.prime) {\n module.exports = forge.prime;\n return;\n}\n\n/* PRIME API */\nvar prime = module.exports = forge.prime = forge.prime || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\nvar THIRTY = new BigInteger(null);\nTHIRTY.fromInt(30);\nvar op_or = function(x, y) {return x|y;};\n\n/**\n * Generates a random probable prime with the given number of bits.\n *\n * Alternative algorithms can be specified by name as a string or as an\n * object with custom options like so:\n *\n * {\n * name: 'PRIMEINC',\n * options: {\n * maxBlockTime: ,\n * millerRabinTests: ,\n * workerScript: ,\n * workers: .\n * workLoad: the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * }\n * }\n *\n * @param bits the number of bits for the prime number.\n * @param options the options to use.\n * [algorithm] the algorithm to use (default: 'PRIMEINC').\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n *\n * @return callback(err, num) called once the operation completes.\n */\nprime.generateProbablePrime = function(bits, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // default to PRIMEINC algorithm\n var algorithm = options.algorithm || 'PRIMEINC';\n if(typeof algorithm === 'string') {\n algorithm = {name: algorithm};\n }\n algorithm.options = algorithm.options || {};\n\n // create prng with api that matches BigInteger secure random\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n if(algorithm.name === 'PRIMEINC') {\n return primeincFindPrime(bits, rng, algorithm.options, callback);\n }\n\n throw new Error('Invalid prime generation algorithm: ' + algorithm.name);\n};\n\nfunction primeincFindPrime(bits, rng, options, callback) {\n if('workers' in options) {\n return primeincFindPrimeWithWorkers(bits, rng, options, callback);\n }\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n}\n\nfunction primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {\n // initialize random number\n var num = generateRandom(bits, rng);\n\n /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The\n number we are given is always aligned at 30k + 1. Each time the number is\n determined not to be prime we add to get to the next 'i', eg: if the number\n was at 30k + 1 we add 6. */\n var deltaIdx = 0;\n\n // get required number of MR tests\n var mrTests = getMillerRabinTests(num.bitLength());\n if('millerRabinTests' in options) {\n mrTests = options.millerRabinTests;\n }\n\n // find prime nearest to 'num' for maxBlockTime ms\n // 10 ms gives 5ms of leeway for other calculations before dropping\n // below 60fps (1000/60 == 16.67), but in reality, the number will\n // likely be higher due to an 'atomic' big int modPow\n var maxBlockTime = 10;\n if('maxBlockTime' in options) {\n maxBlockTime = options.maxBlockTime;\n }\n\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n}\n\nfunction _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {\n var start = +new Date();\n do {\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n // do primality test\n if(num.isProbablePrime(mrTests)) {\n return callback(null, num);\n }\n // get next potential prime\n num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));\n\n // keep trying later\n forge.util.setImmediate(function() {\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n });\n}\n\n// NOTE: This algorithm is indeterminate in nature because workers\n// run in parallel looking at different segments of numbers. Even if this\n// algorithm is run twice with the same input from a predictable RNG, it\n// may produce different outputs.\nfunction primeincFindPrimeWithWorkers(bits, rng, options, callback) {\n // web workers unavailable\n if(typeof Worker === 'undefined') {\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n }\n\n // initialize random number\n var num = generateRandom(bits, rng);\n\n // use web workers to generate keys\n var numWorkers = options.workers;\n var workLoad = options.workLoad || 100;\n var range = workLoad * 30 / 8;\n var workerScript = options.workerScript || 'forge/prime.worker.js';\n if(numWorkers === -1) {\n return forge.util.estimateCores(function(err, cores) {\n if(err) {\n // default to 2\n cores = 2;\n }\n numWorkers = cores - 1;\n generate();\n });\n }\n generate();\n\n function generate() {\n // require at least 1 worker\n numWorkers = Math.max(1, numWorkers);\n\n // TODO: consider optimizing by starting workers outside getPrime() ...\n // note that in order to clean up they will have to be made internally\n // asynchronous which may actually be slower\n\n // start workers immediately\n var workers = [];\n for(var i = 0; i < numWorkers; ++i) {\n // FIXME: fix path or use blob URLs\n workers[i] = new Worker(workerScript);\n }\n var running = numWorkers;\n\n // listen for requests from workers and assign ranges to find prime\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].addEventListener('message', workerMessage);\n }\n\n /* Note: The distribution of random numbers is unknown. Therefore, each\n web worker is continuously allocated a range of numbers to check for a\n random number until one is found.\n\n Every 30 numbers will be checked just 8 times, because prime numbers\n have the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)\n\n Therefore, if we want a web worker to run N checks before asking for\n a new range of numbers, each range must contain N*30/8 numbers.\n\n For 100 checks (workLoad), this is a range of 375. */\n\n var found = false;\n function workerMessage(e) {\n // ignore message, prime already found\n if(found) {\n return;\n }\n\n --running;\n var data = e.data;\n if(data.found) {\n // terminate all workers\n for(var i = 0; i < workers.length; ++i) {\n workers[i].terminate();\n }\n found = true;\n return callback(null, new BigInteger(data.prime, 16));\n }\n\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n\n // assign new range to check\n var hex = num.toString(16);\n\n // start prime search\n e.target.postMessage({\n hex: hex,\n workLoad: workLoad\n });\n\n num.dAddOffset(range, 0);\n }\n }\n}\n\n/**\n * Generates a random number using the given number of bits and RNG.\n *\n * @param bits the number of bits for the number.\n * @param rng the random number generator to use.\n *\n * @return the random number.\n */\nfunction generateRandom(bits, rng) {\n var num = new BigInteger(bits, rng);\n // force MSB set\n var bits1 = bits - 1;\n if(!num.testBit(bits1)) {\n num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);\n }\n // align number on 30k+1 boundary\n num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);\n return num;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n})();\n","/**\n * Javascript implementation of basic RSA algorithms.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The only algorithm currently supported for PKI is RSA.\n *\n * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo\n * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier\n * and a subjectPublicKey of type bit string.\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of RSA, there aren't any.\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * For an RSA public key, the subjectPublicKey is:\n *\n * RSAPublicKey ::= SEQUENCE {\n * modulus INTEGER, -- n\n * publicExponent INTEGER -- e\n * }\n *\n * PrivateKeyInfo ::= SEQUENCE {\n * version Version,\n * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,\n * privateKey PrivateKey,\n * attributes [0] IMPLICIT Attributes OPTIONAL\n * }\n *\n * Version ::= INTEGER\n * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier\n * PrivateKey ::= OCTET STRING\n * Attributes ::= SET OF Attribute\n *\n * An RSA private key as the following structure:\n *\n * RSAPrivateKey ::= SEQUENCE {\n * version Version,\n * modulus INTEGER, -- n\n * publicExponent INTEGER, -- e\n * privateExponent INTEGER, -- d\n * prime1 INTEGER, -- p\n * prime2 INTEGER, -- q\n * exponent1 INTEGER, -- d mod (p-1)\n * exponent2 INTEGER, -- d mod (q-1)\n * coefficient INTEGER -- (inverse of q) mod p\n * }\n *\n * Version ::= INTEGER\n *\n * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./jsbn');\nrequire('./oids');\nrequire('./pkcs1');\nrequire('./prime');\nrequire('./random');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar _crypto = forge.util.isNodejs ? require('crypto') : null;\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for util API\nvar util = forge.util;\n\n/*\n * RSA encryption and decryption, see RFC 2313.\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};\nvar pki = forge.pki;\n\n// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\n\n// validator for a PrivateKeyInfo structure\nvar privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\n// validator for an RSA private key\nvar rsaPrivateKeyValidator = {\n // RSAPrivateKey\n name: 'RSAPrivateKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'RSAPrivateKey.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // modulus (n)\n name: 'RSAPrivateKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPrivateKey.publicExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPublicExponent'\n }, {\n // privateExponent (d)\n name: 'RSAPrivateKey.privateExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrivateExponent'\n }, {\n // prime1 (p)\n name: 'RSAPrivateKey.prime1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime1'\n }, {\n // prime2 (q)\n name: 'RSAPrivateKey.prime2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime2'\n }, {\n // exponent1 (d mod (p-1))\n name: 'RSAPrivateKey.exponent1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent1'\n }, {\n // exponent2 (d mod (q-1))\n name: 'RSAPrivateKey.exponent2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent2'\n }, {\n // coefficient ((inverse of q) mod p)\n name: 'RSAPrivateKey.coefficient',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyCoefficient'\n }]\n};\n\n// validator for an RSA public key\nvar rsaPublicKeyValidator = {\n // RSAPublicKey\n name: 'RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // modulus (n)\n name: 'RSAPublicKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPublicKey.exponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyExponent'\n }]\n};\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n }, {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n }]\n};\n\n/**\n * Wrap digest in DigestInfo object.\n *\n * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * @param md the message digest object with the hash to sign.\n *\n * @return the encoded message (ready for RSA encrytion)\n */\nvar emsaPkcs1v15encode = function(md) {\n // get the oid for the algorithm\n var oid;\n if(md.algorithm in pki.oids) {\n oid = pki.oids[md.algorithm];\n } else {\n var error = new Error('Unknown message digest algorithm.');\n error.algorithm = md.algorithm;\n throw error;\n }\n var oidBytes = asn1.oidToDer(oid).getBytes();\n\n // create the digest info\n var digestInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var digestAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));\n var digest = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, md.digest().getBytes());\n digestInfo.value.push(digestAlgorithm);\n digestInfo.value.push(digest);\n\n // encode digest info\n return asn1.toDer(digestInfo).getBytes();\n};\n\n/**\n * Performs x^c mod n (RSA encryption or decryption operation).\n *\n * @param x the number to raise and mod.\n * @param key the key to use.\n * @param pub true if the key is public, false if private.\n *\n * @return the result of x^c mod n.\n */\nvar _modPow = function(x, key, pub) {\n if(pub) {\n return x.modPow(key.e, key.n);\n }\n\n if(!key.p || !key.q) {\n // allow calculation without CRT params (slow)\n return x.modPow(key.d, key.n);\n }\n\n // pre-compute dP, dQ, and qInv if necessary\n if(!key.dP) {\n key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));\n }\n if(!key.dQ) {\n key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));\n }\n if(!key.qInv) {\n key.qInv = key.q.modInverse(key.p);\n }\n\n /* Chinese remainder theorem (CRT) states:\n\n Suppose n1, n2, ..., nk are positive integers which are pairwise\n coprime (n1 and n2 have no common factors other than 1). For any\n integers x1, x2, ..., xk there exists an integer x solving the\n system of simultaneous congruences (where ~= means modularly\n congruent so a ~= b mod n means a mod n = b mod n):\n\n x ~= x1 mod n1\n x ~= x2 mod n2\n ...\n x ~= xk mod nk\n\n This system of congruences has a single simultaneous solution x\n between 0 and n - 1. Furthermore, each xk solution and x itself\n is congruent modulo the product n = n1*n2*...*nk.\n So x1 mod n = x2 mod n = xk mod n = x mod n.\n\n The single simultaneous solution x can be solved with the following\n equation:\n\n x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.\n\n Where x is less than n, xi = x mod ni.\n\n For RSA we are only concerned with k = 2. The modulus n = pq, where\n p and q are coprime. The RSA decryption algorithm is:\n\n y = x^d mod n\n\n Given the above:\n\n x1 = x^d mod p\n r1 = n/p = q\n s1 = q^-1 mod p\n x2 = x^d mod q\n r2 = n/q = p\n s2 = p^-1 mod q\n\n So y = (x1r1s1 + x2r2s2) mod n\n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n\n\n According to Fermat's Little Theorem, if the modulus P is prime,\n for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.\n Since A is not divisible by P it follows that if:\n N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:\n\n A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort\n to calculate). In order to calculate x^d mod p more quickly the\n exponent d mod (p - 1) is stored in the RSA private key (the same\n is done for x^d mod q). These values are referred to as dP and dQ\n respectively. Therefore we now have:\n\n y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n\n\n Since we'll be reducing x^dP by modulo p (same for q) we can also\n reduce x by p (and q respectively) before hand. Therefore, let\n\n xp = ((x mod p)^dP mod p), and\n xq = ((x mod q)^dQ mod q), yielding:\n\n y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n\n\n This can be further reduced to a simple algorithm that only\n requires 1 inverse (the q inverse is used) to be used and stored.\n The algorithm is called Garner's algorithm. If qInv is the\n inverse of q, we simply calculate:\n\n y = (qInv*(xp - xq) mod p) * q + xq\n\n However, there are two further complications. First, we need to\n ensure that xp > xq to prevent signed BigIntegers from being used\n so we add p until this is true (since we will be mod'ing with\n p anyway). Then, there is a known timing attack on algorithms\n using the CRT. To mitigate this risk, \"cryptographic blinding\"\n should be used. This requires simply generating a random number r\n between 0 and n-1 and its inverse and multiplying x by r^e before\n calculating y and then multiplying y by r^-1 afterwards. Note that\n r must be coprime with n (gcd(r, n) === 1) in order to have an\n inverse.\n */\n\n // cryptographic blinding\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),\n 16);\n } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));\n x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);\n\n // calculate xp and xq\n var xp = x.mod(key.p).modPow(key.dP, key.p);\n var xq = x.mod(key.q).modPow(key.dQ, key.q);\n\n // xp must be larger than xq to avoid signed bit usage\n while(xp.compareTo(xq) < 0) {\n xp = xp.add(key.p);\n }\n\n // do last step\n var y = xp.subtract(xq)\n .multiply(key.qInv).mod(key.p)\n .multiply(key.q).add(xq);\n\n // remove effect of random for cryptographic blinding\n y = y.multiply(r.modInverse(key.n)).mod(key.n);\n\n return y;\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or\n * 'encrypt' on a public key object instead.\n *\n * Performs RSA encryption.\n *\n * The parameter bt controls whether to put padding bytes before the\n * message passed in. Set bt to either true or false to disable padding\n * completely (in order to handle e.g. EMSA-PSS encoding seperately before),\n * signaling whether the encryption operation is a public key operation\n * (i.e. encrypting data) or not, i.e. private key operation (data signing).\n *\n * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01\n * (for signing) or 0x02 (for encryption). The key operation mode (private\n * or public) is derived from this flag in that case).\n *\n * @param m the message to encrypt as a byte string.\n * @param key the RSA key to use.\n * @param bt for PKCS#1 v1.5 padding, the block type to use\n * (0x01 for private key, 0x02 for public),\n * to disable padding: true = public key, false = private key.\n *\n * @return the encrypted bytes as a string.\n */\npki.rsa.encrypt = function(m, key, bt) {\n var pub = bt;\n var eb;\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n if(bt !== false && bt !== true) {\n // legacy, default to PKCS#1 v1.5 padding\n pub = (bt === 0x02);\n eb = _encodePkcs1_v1_5(m, key, bt);\n } else {\n eb = forge.util.createBuffer();\n eb.putBytes(m);\n }\n\n // load encryption block as big integer 'x'\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var x = new BigInteger(eb.toHex(), 16);\n\n // do RSA encryption\n var y = _modPow(x, key, pub);\n\n // convert y into the encrypted data byte string, if y is shorter in\n // bytes than k, then prepend zero bytes to fill up ed\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var yhex = y.toString(16);\n var ed = forge.util.createBuffer();\n var zeros = k - Math.ceil(yhex.length / 2);\n while(zeros > 0) {\n ed.putByte(0x00);\n --zeros;\n }\n ed.putBytes(forge.util.hexToBytes(yhex));\n return ed.getBytes();\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or\n * 'verify' on a public key object instead.\n *\n * Performs RSA decryption.\n *\n * The parameter ml controls whether to apply PKCS#1 v1.5 padding\n * or not. Set ml = false to disable padding removal completely\n * (in order to handle e.g. EMSA-PSS later on) and simply pass back\n * the RSA encryption block.\n *\n * @param ed the encrypted data to decrypt in as a byte string.\n * @param key the RSA key to use.\n * @param pub true for a public key operation, false for private.\n * @param ml the message length, if known, false to disable padding.\n *\n * @return the decrypted message as a byte string.\n */\npki.rsa.decrypt = function(ed, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n // error if the length of the encrypted data ED is not k\n if(ed.length !== k) {\n var error = new Error('Encrypted message length is invalid.');\n error.length = ed.length;\n error.expected = k;\n throw error;\n }\n\n // convert encrypted data into a big integer\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);\n\n // y must be less than the modulus or it wasn't the result of\n // a previous mod operation (encryption) using that modulus\n if(y.compareTo(key.n) >= 0) {\n throw new Error('Encrypted message is invalid.');\n }\n\n // do RSA decryption\n var x = _modPow(y, key, pub);\n\n // create the encryption block, if x is shorter in bytes than k, then\n // prepend zero bytes to fill up eb\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var xhex = x.toString(16);\n var eb = forge.util.createBuffer();\n var zeros = k - Math.ceil(xhex.length / 2);\n while(zeros > 0) {\n eb.putByte(0x00);\n --zeros;\n }\n eb.putBytes(forge.util.hexToBytes(xhex));\n\n if(ml !== false) {\n // legacy, default to PKCS#1 v1.5 padding\n return _decodePkcs1_v1_5(eb.getBytes(), key, pub);\n }\n\n // return message\n return eb.getBytes();\n};\n\n/**\n * Creates an RSA key-pair generation state object. It is used to allow\n * key-generation to be performed in steps. It also allows for a UI to\n * display progress updates.\n *\n * @param bits the size for the private key in bits, defaults to 2048.\n * @param e the public exponent to use, defaults to 65537 (0x10001).\n * @param [options] the options to use.\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n * algorithm the algorithm to use (default: 'PRIMEINC').\n *\n * @return the state object to use to generate the key-pair.\n */\npki.rsa.createKeyPairGenerationState = function(bits, e, options) {\n // TODO: migrate step-based prime generation code to forge.prime\n\n // set default bits\n if(typeof(bits) === 'string') {\n bits = parseInt(bits, 10);\n }\n bits = bits || 2048;\n\n // create prng with api that matches BigInteger secure random\n options = options || {};\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n var algorithm = options.algorithm || 'PRIMEINC';\n\n // create PRIMEINC algorithm state\n var rval;\n if(algorithm === 'PRIMEINC') {\n rval = {\n algorithm: algorithm,\n state: 0,\n bits: bits,\n rng: rng,\n eInt: e || 65537,\n e: new BigInteger(null),\n p: null,\n q: null,\n qBits: bits >> 1,\n pBits: bits - (bits >> 1),\n pqState: 0,\n num: null,\n keys: null\n };\n rval.e.fromInt(rval.eInt);\n } else {\n throw new Error('Invalid key generation algorithm: ' + algorithm);\n }\n\n return rval;\n};\n\n/**\n * Attempts to runs the key-generation algorithm for at most n seconds\n * (approximately) using the given state. When key-generation has completed,\n * the keys will be stored in state.keys.\n *\n * To use this function to update a UI while generating a key or to prevent\n * causing browser lockups/warnings, set \"n\" to a value other than 0. A\n * simple pattern for generating a key and showing a progress indicator is:\n *\n * var state = pki.rsa.createKeyPairGenerationState(2048);\n * var step = function() {\n * // step key-generation, run algorithm for 100 ms, repeat\n * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {\n * setTimeout(step, 1);\n * } else {\n * // key-generation complete\n * // TODO: turn off progress indicator here\n * // TODO: use the generated key-pair in \"state.keys\"\n * }\n * };\n * // TODO: turn on progress indicator here\n * setTimeout(step, 0);\n *\n * @param state the state to use.\n * @param n the maximum number of milliseconds to run the algorithm for, 0\n * to run the algorithm to completion.\n *\n * @return true if the key-generation completed, false if not.\n */\npki.rsa.stepKeyPairGenerationState = function(state, n) {\n // set default algorithm if not set\n if(!('algorithm' in state)) {\n state.algorithm = 'PRIMEINC';\n }\n\n // TODO: migrate step-based prime generation code to forge.prime\n // TODO: abstract as PRIMEINC algorithm\n\n // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)\n // with some minor optimizations and designed to run in steps\n\n // local state vars\n var THIRTY = new BigInteger(null);\n THIRTY.fromInt(30);\n var deltaIdx = 0;\n var op_or = function(x, y) {return x | y;};\n\n // keep stepping until time limit is reached or done\n var t1 = +new Date();\n var t2;\n var total = 0;\n while(state.keys === null && (n <= 0 || total < n)) {\n // generate p or q\n if(state.state === 0) {\n /* Note: All primes are of the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i\n\n When we generate a random number, we always align it at 30k + 1. Each\n time the number is determined not to be prime we add to get to the\n next 'i', eg: if the number was at 30k + 1 we add 6. */\n var bits = (state.p === null) ? state.pBits : state.qBits;\n var bits1 = bits - 1;\n\n // get a random number\n if(state.pqState === 0) {\n state.num = new BigInteger(bits, state.rng);\n // force MSB set\n if(!state.num.testBit(bits1)) {\n state.num.bitwiseTo(\n BigInteger.ONE.shiftLeft(bits1), op_or, state.num);\n }\n // align number on 30k+1 boundary\n state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);\n deltaIdx = 0;\n\n ++state.pqState;\n } else if(state.pqState === 1) {\n // try to make the number a prime\n if(state.num.bitLength() > bits) {\n // overflow, try again\n state.pqState = 0;\n // do primality test\n } else if(state.num.isProbablePrime(\n _getMillerRabinTests(state.num.bitLength()))) {\n ++state.pqState;\n } else {\n // get next potential prime\n state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n }\n } else if(state.pqState === 2) {\n // ensure number is coprime with e\n state.pqState =\n (state.num.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) === 0) ? 3 : 0;\n } else if(state.pqState === 3) {\n // store p or q\n state.pqState = 0;\n if(state.p === null) {\n state.p = state.num;\n } else {\n state.q = state.num;\n }\n\n // advance state if both p and q are ready\n if(state.p !== null && state.q !== null) {\n ++state.state;\n }\n state.num = null;\n }\n } else if(state.state === 1) {\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n state.num = state.p;\n state.p = state.q;\n state.q = state.num;\n }\n ++state.state;\n } else if(state.state === 2) {\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n ++state.state;\n } else if(state.state === 3) {\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {\n // phi and e are coprime, advance\n ++state.state;\n } else {\n // phi and e aren't coprime, so generate a new p and q\n state.p = null;\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 4) {\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n\n // ensure n is right number of bits\n if(state.n.bitLength() === state.bits) {\n // success, advance\n ++state.state;\n } else {\n // failed, get new q\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 5) {\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n }\n\n // update timing\n t2 = +new Date();\n total += t2 - t1;\n t1 = t2;\n }\n\n return state.keys !== null;\n};\n\n/**\n * Generates an RSA public-private key pair in a single call.\n *\n * To generate a key-pair in steps (to allow for progress updates and to\n * prevent blocking or warnings in slow browsers) then use the key-pair\n * generation state functions.\n *\n * To generate a key-pair asynchronously (either through web-workers, if\n * available, or by breaking up the work on the main thread), pass a\n * callback function.\n *\n * @param [bits] the size for the private key in bits, defaults to 2048.\n * @param [e] the public exponent to use, defaults to 65537.\n * @param [options] options for key-pair generation, if given then 'bits'\n * and 'e' must *not* be given:\n * bits the size for the private key in bits, (default: 2048).\n * e the public exponent to use, (default: 65537 (0x10001)).\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\". Disables use of native APIs.\n * algorithm the algorithm to use (default: 'PRIMEINC').\n * @param [callback(err, keypair)] called once the operation completes.\n *\n * @return an object with privateKey and publicKey properties.\n */\npki.rsa.generateKeyPair = function(bits, e, options, callback) {\n // (bits), (options), (callback)\n if(arguments.length === 1) {\n if(typeof bits === 'object') {\n options = bits;\n bits = undefined;\n } else if(typeof bits === 'function') {\n callback = bits;\n bits = undefined;\n }\n } else if(arguments.length === 2) {\n // (bits, e), (bits, options), (bits, callback), (options, callback)\n if(typeof bits === 'number') {\n if(typeof e === 'function') {\n callback = e;\n e = undefined;\n } else if(typeof e !== 'number') {\n options = e;\n e = undefined;\n }\n } else {\n options = bits;\n callback = e;\n bits = undefined;\n e = undefined;\n }\n } else if(arguments.length === 3) {\n // (bits, e, options), (bits, e, callback), (bits, options, callback)\n if(typeof e === 'number') {\n if(typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n } else {\n callback = options;\n options = e;\n e = undefined;\n }\n }\n options = options || {};\n if(bits === undefined) {\n bits = options.bits || 2048;\n }\n if(e === undefined) {\n e = options.e || 0x10001;\n }\n\n // use native code if permitted, available, and parameters are acceptable\n if(!forge.options.usePureJavaScript && !options.prng &&\n bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {\n if(callback) {\n // try native async\n if(_detectNodeCrypto('generateKeyPair')) {\n return _crypto.generateKeyPair('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n }, function(err, pub, priv) {\n if(err) {\n return callback(err);\n }\n callback(null, {\n privateKey: pki.privateKeyFromPem(priv),\n publicKey: pki.publicKeyFromPem(pub)\n });\n });\n }\n if(_detectSubtleCrypto('generateKey') &&\n _detectSubtleCrypto('exportKey')) {\n // use standard native generateKey\n return util.globalScope.crypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify'])\n .then(function(pair) {\n return util.globalScope.crypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n // avoiding catch(function(err) {...}) to support IE <= 8\n }).then(undefined, function(err) {\n callback(err);\n }).then(function(pkcs8) {\n if(pkcs8) {\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n }\n });\n }\n if(_detectSubtleMsCrypto('generateKey') &&\n _detectSubtleMsCrypto('exportKey')) {\n var genOp = util.globalScope.msCrypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify']);\n genOp.oncomplete = function(e) {\n var pair = e.target.result;\n var exportOp = util.globalScope.msCrypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n exportOp.oncomplete = function(e) {\n var pkcs8 = e.target.result;\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n };\n exportOp.onerror = function(err) {\n callback(err);\n };\n };\n genOp.onerror = function(err) {\n callback(err);\n };\n return;\n }\n } else {\n // try native sync\n if(_detectNodeCrypto('generateKeyPairSync')) {\n var keypair = _crypto.generateKeyPairSync('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n });\n return {\n privateKey: pki.privateKeyFromPem(keypair.privateKey),\n publicKey: pki.publicKeyFromPem(keypair.publicKey)\n };\n }\n }\n }\n\n // use JavaScript implementation\n var state = pki.rsa.createKeyPairGenerationState(bits, e, options);\n if(!callback) {\n pki.rsa.stepKeyPairGenerationState(state, 0);\n return state.keys;\n }\n _generateKeyPair(state, options, callback);\n};\n\n/**\n * Sets an RSA public key from BigIntegers modulus and exponent.\n *\n * @param n the modulus.\n * @param e the exponent.\n *\n * @return the public key.\n */\npki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {\n var key = {\n n: n,\n e: e\n };\n\n /**\n * Encrypts the given data with this public key. Newer applications\n * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for\n * legacy applications.\n *\n * @param data the byte string to encrypt.\n * @param scheme the encryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA encryption,\n * an object with an 'encode' property set to a function\n * with the signature 'function(data, key)' that returns\n * a binary-encoded string representing the encoded data.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the encrypted byte string.\n */\n key.encrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {\n encode: function(m, key, pub) {\n return _encodePkcs1_v1_5(m, key, 0x02).getBytes();\n }\n };\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n encode: function(m, key) {\n return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {encode: function(e) {return e;}};\n } else if(typeof scheme === 'string') {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // do scheme-based encoding then rsa encryption\n var e = scheme.encode(data, key, true);\n return pki.rsa.encrypt(e, key, true);\n };\n\n /**\n * Verifies the given signature against the given digest.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the\n * signature is an OCTET STRING that holds a DigestInfo.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * To perform PSS signature verification, provide an instance\n * of Forge PSS object as the scheme parameter.\n *\n * @param digest the message digest hash to compare against the signature,\n * as a binary-encoded string.\n * @param signature the signature to verify, as a binary-encoded string.\n * @param scheme signature verification scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be expected, but\n * PKCS#1 v1.5 padding will still be used.\n *\n * @return true if the signature was verified, false if not.\n */\n key.verify = function(digest, signature, scheme) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSASSA-PKCS1-V1_5';\n }\n\n if(scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n // d is ASN.1 BER-encoded DigestInfo\n var obj = asn1.fromDer(d);\n // compare the given digest to the decrypted one\n return digest === obj.value[1].value;\n }\n };\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n return digest === d;\n }\n };\n }\n\n // do rsa decryption w/o any decoding, then verify -- which does decoding\n var d = pki.rsa.decrypt(signature, key, true, false);\n return scheme.verify(digest, d, key.n.bitLength());\n };\n\n return key;\n};\n\n/**\n * Sets an RSA private key from BigIntegers modulus, exponent, primes,\n * prime exponents, and modular multiplicative inverse.\n *\n * @param n the modulus.\n * @param e the public exponent.\n * @param d the private exponent ((inverse of e) mod n).\n * @param p the first prime.\n * @param q the second prime.\n * @param dP exponent1 (d mod (p-1)).\n * @param dQ exponent2 (d mod (q-1)).\n * @param qInv ((inverse of q) mod p)\n *\n * @return the private key.\n */\npki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(\n n, e, d, p, q, dP, dQ, qInv) {\n var key = {\n n: n,\n e: e,\n d: d,\n p: p,\n q: q,\n dP: dP,\n dQ: dQ,\n qInv: qInv\n };\n\n /**\n * Decrypts the given data with this private key. The decryption scheme\n * must match the one used to encrypt the data.\n *\n * @param data the byte string to decrypt.\n * @param scheme the decryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA decryption.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the decrypted byte string.\n */\n key.decrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n // do rsa decryption w/o any decoding\n var d = pki.rsa.decrypt(data, key, false, false);\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {decode: _decodePkcs1_v1_5};\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n decode: function(d, key) {\n return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {decode: function(d) {return d;}};\n } else {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // decode according to scheme\n return scheme.decode(d, key, false);\n };\n\n /**\n * Signs the given digest, producing a signature.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide\n * an instance of Forge PSS object as the scheme parameter.\n *\n * @param md the message digest object with the hash to sign.\n * @param scheme the signature scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be used but\n * PKCS#1 v1.5 padding will still be used.\n *\n * @return the signature as a byte string.\n */\n key.sign = function(md, scheme) {\n /* Note: The internal implementation of RSA operations is being\n transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy\n code like the use of an encoding block identifier 'bt' will eventually\n be removed. */\n\n // private key operation\n var bt = false;\n\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n }\n\n if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {encode: emsaPkcs1v15encode};\n bt = 0x01;\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {encode: function() {return md;}};\n bt = 0x01;\n }\n\n // encode and then encrypt\n var d = scheme.encode(md, key.n.bitLength());\n return pki.rsa.encrypt(d, key, bt);\n };\n\n return key;\n};\n\n/**\n * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.\n *\n * @param rsaKey the ASN.1 RSAPrivateKey.\n *\n * @return the ASN.1 PrivateKeyInfo.\n */\npki.wrapRsaPrivateKey = function(rsaKey) {\n // PrivateKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // privateKeyAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // PrivateKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(rsaKey).getBytes())\n ]);\n};\n\n/**\n * Converts a private key from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a PrivateKeyInfo containing an\n * RSAPrivateKey or an RSAPrivateKey.\n *\n * @return the private key.\n */\npki.privateKeyFromAsn1 = function(obj) {\n // get PrivateKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, privateKeyValidator, capture, errors)) {\n obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));\n }\n\n // get RSAPrivateKey\n capture = {};\n errors = [];\n if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read private key. ' +\n 'ASN.1 object does not contain an RSAPrivateKey.');\n error.errors = errors;\n throw error;\n }\n\n // Note: Version is currently ignored.\n // capture.privateKeyVersion\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n, e, d, p, q, dP, dQ, qInv;\n n = forge.util.createBuffer(capture.privateKeyModulus).toHex();\n e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();\n d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();\n p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();\n q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();\n dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();\n dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();\n qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();\n\n // set private key\n return pki.setRsaPrivateKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16),\n new BigInteger(d, 16),\n new BigInteger(p, 16),\n new BigInteger(q, 16),\n new BigInteger(dP, 16),\n new BigInteger(dQ, 16),\n new BigInteger(qInv, 16));\n};\n\n/**\n * Converts a private key to an ASN.1 RSAPrivateKey.\n *\n * @param key the private key.\n *\n * @return the ASN.1 representation of an RSAPrivateKey.\n */\npki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {\n // RSAPrivateKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0 = only 2 primes, 1 multiple primes)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e)),\n // privateExponent (d)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.d)),\n // privateKeyPrime1 (p)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.p)),\n // privateKeyPrime2 (q)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.q)),\n // privateKeyExponent1 (dP)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dP)),\n // privateKeyExponent2 (dQ)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dQ)),\n // coefficient (qInv)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.qInv))\n ]);\n};\n\n/**\n * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @return the public key.\n */\npki.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, publicKeyValidator, capture, errors)) {\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n var error = new Error('Cannot read public key. Unknown OID.');\n error.oid = oid;\n throw error;\n }\n obj = capture.rsaPublicKey;\n }\n\n // get RSA params\n errors = [];\n if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {\n var error = new Error('Cannot read public key. ' +\n 'ASN.1 object does not contain an RSAPublicKey.');\n error.errors = errors;\n throw error;\n }\n\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();\n var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();\n\n // set public key\n return pki.setRsaPublicKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16));\n};\n\n/**\n * Converts a public key to an ASN.1 SubjectPublicKeyInfo.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a SubjectPublicKeyInfo.\n */\npki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {\n // SubjectPublicKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // subjectPublicKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [\n pki.publicKeyToRSAPublicKey(key)\n ])\n ]);\n};\n\n/**\n * Converts a public key to an ASN.1 RSAPublicKey.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a RSAPublicKey.\n */\npki.publicKeyToRSAPublicKey = function(key) {\n // RSAPublicKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e))\n ]);\n};\n\n/**\n * Encodes a message using PKCS#1 v1.5 padding.\n *\n * @param m the message to encode.\n * @param key the RSA key to use.\n * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02\n * (for encryption).\n *\n * @return the padded byte buffer.\n */\nfunction _encodePkcs1_v1_5(m, key, bt) {\n var eb = forge.util.createBuffer();\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* use PKCS#1 v1.5 padding */\n if(m.length > (k - 11)) {\n var error = new Error('Message is too long for PKCS#1 v1.5 padding.');\n error.length = m.length;\n error.max = k - 11;\n throw error;\n }\n\n /* A block type BT, a padding string PS, and the data D shall be\n formatted into an octet string EB, the encryption block:\n\n EB = 00 || BT || PS || 00 || D\n\n The block type BT shall be a single octet indicating the structure of\n the encryption block. For this version of the document it shall have\n value 00, 01, or 02. For a private-key operation, the block type\n shall be 00 or 01. For a public-key operation, it shall be 02.\n\n The padding string PS shall consist of k-3-||D|| octets. For block\n type 00, the octets shall have value 00; for block type 01, they\n shall have value FF; and for block type 02, they shall be\n pseudorandomly generated and nonzero. This makes the length of the\n encryption block EB equal to k. */\n\n // build the encryption block\n eb.putByte(0x00);\n eb.putByte(bt);\n\n // create the padding\n var padNum = k - 3 - m.length;\n var padByte;\n // private key op\n if(bt === 0x00 || bt === 0x01) {\n padByte = (bt === 0x00) ? 0x00 : 0xFF;\n for(var i = 0; i < padNum; ++i) {\n eb.putByte(padByte);\n }\n } else {\n // public key op\n // pad with random non-zero values\n while(padNum > 0) {\n var numZeros = 0;\n var padBytes = forge.random.getBytes(padNum);\n for(var i = 0; i < padNum; ++i) {\n padByte = padBytes.charCodeAt(i);\n if(padByte === 0) {\n ++numZeros;\n } else {\n eb.putByte(padByte);\n }\n }\n padNum = numZeros;\n }\n }\n\n // zero followed by message\n eb.putByte(0x00);\n eb.putBytes(m);\n\n return eb;\n}\n\n/**\n * Decodes a message using PKCS#1 v1.5 padding.\n *\n * @param em the message to decode.\n * @param key the RSA key to use.\n * @param pub true if the key is a public key, false if it is private.\n * @param ml the message length, if specified.\n *\n * @return the decoded bytes.\n */\nfunction _decodePkcs1_v1_5(em, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* It is an error if any of the following conditions occurs:\n\n 1. The encryption block EB cannot be parsed unambiguously.\n 2. The padding string PS consists of fewer than eight octets\n or is inconsisent with the block type BT.\n 3. The decryption process is a public-key operation and the block\n type BT is not 00 or 01, or the decryption process is a\n private-key operation and the block type is not 02.\n */\n\n // parse the encryption block\n var eb = forge.util.createBuffer(em);\n var first = eb.getByte();\n var bt = eb.getByte();\n if(first !== 0x00 ||\n (pub && bt !== 0x00 && bt !== 0x01) ||\n (!pub && bt != 0x02) ||\n (pub && bt === 0x00 && typeof(ml) === 'undefined')) {\n throw new Error('Encryption block is invalid.');\n }\n\n var padNum = 0;\n if(bt === 0x00) {\n // check all padding bytes for 0x00\n padNum = k - 3 - ml;\n for(var i = 0; i < padNum; ++i) {\n if(eb.getByte() !== 0x00) {\n throw new Error('Encryption block is invalid.');\n }\n }\n } else if(bt === 0x01) {\n // find the first byte that isn't 0xFF, should be after all padding\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() !== 0xFF) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n } else if(bt === 0x02) {\n // look for 0x00 byte\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() === 0x00) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n }\n\n // zero must be 0x00 and padNum must be (k - 3 - message length)\n var zero = eb.getByte();\n if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {\n throw new Error('Encryption block is invalid.');\n }\n\n return eb.getBytes();\n}\n\n/**\n * Runs the key-generation algorithm asynchronously, either in the background\n * via Web Workers, or using the main thread and setImmediate.\n *\n * @param state the key-pair generation state.\n * @param [options] options for key-pair generation:\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2, -1 to use estimated cores minus one).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * @param callback(err, keypair) called once the operation completes.\n */\nfunction _generateKeyPair(state, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n var opts = {\n algorithm: {\n name: options.algorithm || 'PRIMEINC',\n options: {\n workers: options.workers || 2,\n workLoad: options.workLoad || 100,\n workerScript: options.workerScript\n }\n }\n };\n if('prng' in options) {\n opts.prng = options.prng;\n }\n\n generate();\n\n function generate() {\n // find p and then q (done in series to simplify)\n getPrime(state.pBits, function(err, num) {\n if(err) {\n return callback(err);\n }\n state.p = num;\n if(state.q !== null) {\n return finish(err, state.q);\n }\n getPrime(state.qBits, finish);\n });\n }\n\n function getPrime(bits, callback) {\n forge.prime.generateProbablePrime(bits, opts, callback);\n }\n\n function finish(err, num) {\n if(err) {\n return callback(err);\n }\n\n // set q\n state.q = num;\n\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n var tmp = state.p;\n state.p = state.q;\n state.q = tmp;\n }\n\n // ensure p is coprime with e\n if(state.p.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.p = null;\n generate();\n return;\n }\n\n // ensure q is coprime with e\n if(state.q.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {\n // phi and e aren't coprime, so generate a new p and q\n state.p = state.q = null;\n generate();\n return;\n }\n\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n if(state.n.bitLength() !== state.bits) {\n // failed, get new q\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n\n callback(null, state.keys);\n }\n}\n\n/**\n * Converts a positive BigInteger into 2's-complement big-endian bytes.\n *\n * @param b the big integer to convert.\n *\n * @return the bytes.\n */\nfunction _bnToBytes(b) {\n // prepend 0x00 if first byte >= 0x80\n var hex = b.toString(16);\n if(hex[0] >= '8') {\n hex = '00' + hex;\n }\n var bytes = forge.util.hexToBytes(hex);\n\n // ensure integer is minimally-encoded\n if(bytes.length > 1 &&\n // leading 0x00 for positive integer\n ((bytes.charCodeAt(0) === 0 &&\n (bytes.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (bytes.charCodeAt(0) === 0xFF &&\n (bytes.charCodeAt(1) & 0x80) === 0x80))) {\n return bytes.substr(1);\n }\n return bytes;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction _getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n/**\n * Performs feature detection on the Node crypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectNodeCrypto(fn) {\n return forge.util.isNodejs && typeof _crypto[fn] === 'function';\n}\n\n/**\n * Performs feature detection on the SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.crypto === 'object' &&\n typeof util.globalScope.crypto.subtle === 'object' &&\n typeof util.globalScope.crypto.subtle[fn] === 'function');\n}\n\n/**\n * Performs feature detection on the deprecated Microsoft Internet Explorer\n * outdated SubtleCrypto interface. This function should only be used after\n * checking for the modern, standard SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleMsCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.msCrypto === 'object' &&\n typeof util.globalScope.msCrypto.subtle === 'object' &&\n typeof util.globalScope.msCrypto.subtle[fn] === 'function');\n}\n\nfunction _intToUint8Array(x) {\n var bytes = forge.util.hexToBytes(x.toString(16));\n var buffer = new Uint8Array(bytes.length);\n for(var i = 0; i < bytes.length; ++i) {\n buffer[i] = bytes.charCodeAt(i);\n }\n return buffer;\n}\n\nfunction _privateKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error(\n 'Unsupported key algorithm \"' + jwk.kty + '\"; algorithm must be \"RSA\".');\n }\n return pki.setRsaPrivateKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e),\n _base64ToBigInt(jwk.d),\n _base64ToBigInt(jwk.p),\n _base64ToBigInt(jwk.q),\n _base64ToBigInt(jwk.dp),\n _base64ToBigInt(jwk.dq),\n _base64ToBigInt(jwk.qi));\n}\n\nfunction _publicKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error('Key algorithm must be \"RSA\".');\n }\n return pki.setRsaPublicKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e));\n}\n\nfunction _base64ToBigInt(b64) {\n return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);\n}\n","/**\n * Password-based encryption functions.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * An EncryptedPrivateKeyInfo:\n *\n * EncryptedPrivateKeyInfo ::= SEQUENCE {\n * encryptionAlgorithm EncryptionAlgorithmIdentifier,\n * encryptedData EncryptedData }\n *\n * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedData ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./oids');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./random');\nrequire('./rc2');\nrequire('./rsa');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Password-based encryption implementation. */\nvar pki = forge.pki = forge.pki || {};\nmodule.exports = pki.pbe = forge.pbe = forge.pbe || {};\nvar oids = pki.oids;\n\n// validator for an EncryptedPrivateKeyInfo structure\n// Note: Currently only works w/algorithm params\nvar encryptedPrivateKeyValidator = {\n name: 'EncryptedPrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encryptionOid'\n }, {\n name: 'AlgorithmIdentifier.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'encryptionParams'\n }]\n }, {\n // encryptedData\n name: 'EncryptedPrivateKeyInfo.encryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encryptedData'\n }]\n};\n\n// validator for a PBES2Algorithms structure\n// Note: Currently only works w/PBKDF2 + AES encryption schemes\nvar PBES2AlgorithmsValidator = {\n name: 'PBES2Algorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'kdfOid'\n }, {\n name: 'PBES2Algorithms.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.params.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'kdfSalt'\n }, {\n name: 'PBES2Algorithms.params.iterationCount',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'kdfIterationCount'\n }, {\n name: 'PBES2Algorithms.params.keyLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'keyLength'\n }, {\n // prf\n name: 'PBES2Algorithms.params.prf',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'PBES2Algorithms.params.prf.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'prfOid'\n }]\n }]\n }]\n }, {\n name: 'PBES2Algorithms.encryptionScheme',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.encryptionScheme.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encOid'\n }, {\n name: 'PBES2Algorithms.encryptionScheme.iv',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encIv'\n }]\n }]\n};\n\nvar pkcs12PbeParamsValidator = {\n name: 'pkcs-12PbeParams',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'pkcs-12PbeParams.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'salt'\n }, {\n name: 'pkcs-12PbeParams.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'iterations'\n }]\n};\n\n/**\n * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.\n *\n * PBES2Algorithms ALGORITHM-IDENTIFIER ::=\n * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}\n *\n * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}\n *\n * PBES2-params ::= SEQUENCE {\n * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},\n * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}\n * }\n *\n * PBES2-KDFs ALGORITHM-IDENTIFIER ::=\n * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }\n *\n * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }\n *\n * PBKDF2-params ::= SEQUENCE {\n * salt CHOICE {\n * specified OCTET STRING,\n * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}\n * },\n * iterationCount INTEGER (1..MAX),\n * keyLength INTEGER (1..MAX) OPTIONAL,\n * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1\n * }\n *\n * @param obj the ASN.1 PrivateKeyInfo object.\n * @param password the password to encrypt with.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * prfAlgorithm the PRF message digest algorithm to use\n * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptPrivateKeyInfo = function(obj, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || 'aes128';\n options.prfAlgorithm = options.prfAlgorithm || 'sha1';\n\n // generate PBE params\n var salt = forge.random.getBytesSync(options.saltSize);\n var count = options.count;\n var countBytes = asn1.integerToDer(count);\n var dkLen;\n var encryptionAlgorithm;\n var encryptedData;\n if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {\n // do PBES2\n var ivLen, encOid, cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n dkLen = 16;\n ivLen = 16;\n encOid = oids['aes128-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n dkLen = 24;\n ivLen = 16;\n encOid = oids['aes192-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n dkLen = 32;\n ivLen = 16;\n encOid = oids['aes256-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'des':\n dkLen = 8;\n ivLen = 8;\n encOid = oids['desCBC'];\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // get PRF message digest\n var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();\n var md = prfAlgorithmToMessageDigest(prfAlgorithm);\n\n // encrypt private key using pbe SHA-1 and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = forge.random.getBytesSync(ivLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n // get PBKDF2-params\n var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBES2']).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // keyDerivationFunc\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()),\n // PBKDF2-params\n params\n ]),\n // encryptionScheme\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(encOid).getBytes()),\n // iv\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)\n ])\n ])\n ]);\n } else if(options.algorithm === '3des') {\n // Do PKCS12 PBE\n dkLen = 24;\n\n var saltBytes = new forge.util.ByteBuffer(salt);\n var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);\n var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);\n var cipher = forge.des.createEncryptionCipher(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),\n // pkcs-12PbeParams\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ])\n ]);\n } else {\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // EncryptedPrivateKeyInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // encryptionAlgorithm\n encryptionAlgorithm,\n // encryptedData\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)\n ]);\n return rval;\n};\n\n/**\n * Decrypts a ASN.1 PrivateKeyInfo object.\n *\n * @param obj the ASN.1 EncryptedPrivateKeyInfo object.\n * @param password the password to decrypt with.\n *\n * @return the ASN.1 PrivateKeyInfo on success, null on failure.\n */\npki.decryptPrivateKeyInfo = function(obj, password) {\n var rval = null;\n\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // get cipher\n var oid = asn1.derToOid(capture.encryptionOid);\n var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);\n\n // get encrypted data\n var encrypted = forge.util.createBuffer(capture.encryptedData);\n\n cipher.update(encrypted);\n if(cipher.finish()) {\n rval = asn1.fromDer(cipher.output);\n }\n\n return rval;\n};\n\n/**\n * Converts a EncryptedPrivateKeyInfo to PEM format.\n *\n * @param epki the EncryptedPrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted encrypted private key.\n */\npki.encryptedPrivateKeyToPem = function(epki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'ENCRYPTED PRIVATE KEY',\n body: asn1.toDer(epki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption\n * is not performed.\n *\n * @param pem the EncryptedPrivateKeyInfo in PEM-format.\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptedPrivateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY') {\n var error = new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM header type is \"ENCRYPTED PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n return asn1.fromDer(msg.body);\n};\n\n/**\n * Encrypts an RSA private key. By default, the key will be wrapped in\n * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.\n * This is the standard, preferred way to encrypt a private key.\n *\n * To produce a non-standard PEM-encrypted private key that uses encapsulated\n * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL\n * private key encryption), set the 'legacy' option to true. Note: Using this\n * option will cause the iteration count to be forced to 1.\n *\n * Note: The 'des' algorithm is supported, but it is not considered to be\n * secure because it only uses a single 56-bit key. If possible, it is highly\n * recommended that a different algorithm be used.\n *\n * @param rsaKey the RSA key to encrypt.\n * @param password the password to use.\n * @param options:\n * algorithm: the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des', 'des').\n * count: the iteration count to use.\n * saltSize: the salt size to use.\n * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated\n * headers (DEK-Info) private key.\n *\n * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptRsaPrivateKey = function(rsaKey, password, options) {\n // standard PKCS#8\n options = options || {};\n if(!options.legacy) {\n // encrypt PrivateKeyInfo\n var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));\n rval = pki.encryptPrivateKeyInfo(rval, password, options);\n return pki.encryptedPrivateKeyToPem(rval);\n }\n\n // legacy non-PKCS#8\n var algorithm;\n var iv;\n var dkLen;\n var cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n algorithm = 'AES-128-CBC';\n dkLen = 16;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n algorithm = 'AES-192-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n algorithm = 'AES-256-CBC';\n dkLen = 32;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case '3des':\n algorithm = 'DES-EDE3-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n case 'des':\n algorithm = 'DES-CBC';\n dkLen = 8;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Could not encrypt RSA private key; unsupported ' +\n 'encryption algorithm \"' + options.algorithm + '\".');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // encrypt private key using OpenSSL legacy key derivation\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));\n cipher.finish();\n\n var msg = {\n type: 'RSA PRIVATE KEY',\n procType: {\n version: '4',\n type: 'ENCRYPTED'\n },\n dekInfo: {\n algorithm: algorithm,\n parameters: forge.util.bytesToHex(iv).toUpperCase()\n },\n body: cipher.output.getBytes()\n };\n return forge.pem.encode(msg);\n};\n\n/**\n * Decrypts an RSA private key.\n *\n * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.\n * @param password the password to use.\n *\n * @return the RSA key on success, null on failure.\n */\npki.decryptRsaPrivateKey = function(pem, password) {\n var rval = null;\n\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&\n msg.type !== 'PRIVATE KEY' &&\n msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM header type ' +\n 'is not \"ENCRYPTED PRIVATE KEY\", \"PRIVATE KEY\", or \"RSA PRIVATE KEY\".');\n error.headerType = error;\n throw error;\n }\n\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n var dkLen;\n var cipherFn;\n switch(msg.dekInfo.algorithm) {\n case 'DES-CBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'DES-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'AES-128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'RC2-40-CBC':\n dkLen = 5;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 40);\n };\n break;\n case 'RC2-64-CBC':\n dkLen = 8;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 64);\n };\n break;\n case 'RC2-128-CBC':\n dkLen = 16;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 128);\n };\n break;\n default:\n var error = new Error('Could not decrypt private key; unsupported ' +\n 'encryption algorithm \"' + msg.dekInfo.algorithm + '\".');\n error.algorithm = msg.dekInfo.algorithm;\n throw error;\n }\n\n // use OpenSSL legacy key derivation\n var iv = forge.util.hexToBytes(msg.dekInfo.parameters);\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(forge.util.createBuffer(msg.body));\n if(cipher.finish()) {\n rval = cipher.output.getBytes();\n } else {\n return rval;\n }\n } else {\n rval = msg.body;\n }\n\n if(msg.type === 'ENCRYPTED PRIVATE KEY') {\n rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);\n } else {\n // decryption already performed above\n rval = asn1.fromDer(rval);\n }\n\n if(rval !== null) {\n rval = pki.privateKeyFromAsn1(rval);\n }\n\n return rval;\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\npki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {\n var j, l;\n\n if(typeof md === 'undefined' || md === null) {\n if(!('sha1' in forge.md)) {\n throw new Error('\"sha1\" hash algorithm unavailable.');\n }\n md = forge.md.sha1.create();\n }\n\n var u = md.digestLength;\n var v = md.blockLength;\n var result = new forge.util.ByteBuffer();\n\n /* Convert password to Unicode byte buffer + trailing 0-byte. */\n var passBuf = new forge.util.ByteBuffer();\n if(password !== null && password !== undefined) {\n for(l = 0; l < password.length; l++) {\n passBuf.putInt16(password.charCodeAt(l));\n }\n passBuf.putInt16(0);\n }\n\n /* Length of salt and password in BYTES. */\n var p = passBuf.length();\n var s = salt.length();\n\n /* 1. Construct a string, D (the \"diversifier\"), by concatenating\n v copies of ID. */\n var D = new forge.util.ByteBuffer();\n D.fillWithByte(id, v);\n\n /* 2. Concatenate copies of the salt together to create a string S of length\n v * ceil(s / v) bytes (the final copy of the salt may be trunacted\n to create S).\n Note that if the salt is the empty string, then so is S. */\n var Slen = v * Math.ceil(s / v);\n var S = new forge.util.ByteBuffer();\n for(l = 0; l < Slen; l++) {\n S.putByte(salt.at(l % s));\n }\n\n /* 3. Concatenate copies of the password together to create a string P of\n length v * ceil(p / v) bytes (the final copy of the password may be\n truncated to create P).\n Note that if the password is the empty string, then so is P. */\n var Plen = v * Math.ceil(p / v);\n var P = new forge.util.ByteBuffer();\n for(l = 0; l < Plen; l++) {\n P.putByte(passBuf.at(l % p));\n }\n\n /* 4. Set I=S||P to be the concatenation of S and P. */\n var I = S;\n I.putBuffer(P);\n\n /* 5. Set c=ceil(n / u). */\n var c = Math.ceil(n / u);\n\n /* 6. For i=1, 2, ..., c, do the following: */\n for(var i = 1; i <= c; i++) {\n /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */\n var buf = new forge.util.ByteBuffer();\n buf.putBytes(D.bytes());\n buf.putBytes(I.bytes());\n for(var round = 0; round < iter; round++) {\n md.start();\n md.update(buf.getBytes());\n buf = md.digest();\n }\n\n /* b) Concatenate copies of Ai to create a string B of length v bytes (the\n final copy of Ai may be truncated to create B). */\n var B = new forge.util.ByteBuffer();\n for(l = 0; l < v; l++) {\n B.putByte(buf.at(l % u));\n }\n\n /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,\n where k=ceil(s / v) + ceil(p / v), modify I by setting\n Ij=(Ij+B+1) mod 2v for each j. */\n var k = Math.ceil(s / v) + Math.ceil(p / v);\n var Inew = new forge.util.ByteBuffer();\n for(j = 0; j < k; j++) {\n var chunk = new forge.util.ByteBuffer(I.getBytes(v));\n var x = 0x1ff;\n for(l = B.length() - 1; l >= 0; l--) {\n x = x >> 8;\n x += B.at(l) + chunk.at(l);\n chunk.setAt(l, x & 0xff);\n }\n Inew.putBuffer(chunk);\n }\n I = Inew;\n\n /* Add Ai to A. */\n result.putBuffer(buf);\n }\n\n result.truncate(result.length() - n);\n return result;\n};\n\n/**\n * Get new Forge cipher object instance.\n *\n * @param oid the OID (in string notation).\n * @param params the ASN.1 params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipher = function(oid, params, password) {\n switch(oid) {\n case pki.oids['pkcs5PBES2']:\n return pki.pbe.getCipherForPBES2(oid, params, password);\n\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n return pki.pbe.getCipherForPKCS12PBE(oid, params, password);\n\n default:\n var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');\n error.oid = oid;\n error.supportedOids = [\n 'pkcs5PBES2',\n 'pbeWithSHAAnd3-KeyTripleDES-CBC',\n 'pbewithSHAAnd40BitRC2-CBC'\n ];\n throw error;\n }\n};\n\n/**\n * Get new Forge cipher object instance according to PBES2 params block.\n *\n * The returned cipher instance is already started using the IV\n * from PBES2 parameter block.\n *\n * @param oid the PKCS#5 PBKDF2 OID (in string notation).\n * @param params the ASN.1 PBES2-params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipherForPBES2 = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // check oids\n oid = asn1.derToOid(capture.kdfOid);\n if(oid !== pki.oids['pkcs5PBKDF2']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported key derivation function OID.');\n error.oid = oid;\n error.supportedOids = ['pkcs5PBKDF2'];\n throw error;\n }\n oid = asn1.derToOid(capture.encOid);\n if(oid !== pki.oids['aes128-CBC'] &&\n oid !== pki.oids['aes192-CBC'] &&\n oid !== pki.oids['aes256-CBC'] &&\n oid !== pki.oids['des-EDE3-CBC'] &&\n oid !== pki.oids['desCBC']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported encryption scheme OID.');\n error.oid = oid;\n error.supportedOids = [\n 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];\n throw error;\n }\n\n // set PBE params\n var salt = capture.kdfSalt;\n var count = forge.util.createBuffer(capture.kdfIterationCount);\n count = count.getInt(count.length() << 3);\n var dkLen;\n var cipherFn;\n switch(pki.oids[oid]) {\n case 'aes128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'des-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'desCBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n\n // decrypt private key using pbe with chosen PRF and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = capture.encIv;\n var cipher = cipherFn(dk);\n cipher.start(iv);\n\n return cipher;\n};\n\n/**\n * Get new Forge cipher object instance for PKCS#12 PBE.\n *\n * The returned cipher instance is already started using the key & IV\n * derived from the provided password and PKCS#12 PBE salt.\n *\n * @param oid The PKCS#12 PBE OID (in string notation).\n * @param params The ASN.1 PKCS#12 PBE-params object.\n * @param password The password to decrypt with.\n *\n * @return the new cipher object instance.\n */\npki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n var salt = forge.util.createBuffer(capture.salt);\n var count = forge.util.createBuffer(capture.iterations);\n count = count.getInt(count.length() << 3);\n\n var dkLen, dIvLen, cipherFn;\n switch(oid) {\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n dkLen = 24;\n dIvLen = 8;\n cipherFn = forge.des.startDecrypting;\n break;\n\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n dkLen = 5;\n dIvLen = 8;\n cipherFn = function(key, iv) {\n var cipher = forge.rc2.createDecryptionCipher(key, 40);\n cipher.start(iv, null);\n return cipher;\n };\n break;\n\n default:\n var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');\n error.oid = oid;\n throw error;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);\n md.start();\n var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);\n\n return cipherFn(key, iv);\n};\n\n/**\n * OpenSSL's legacy key derivation function.\n *\n * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html\n *\n * @param password the password to derive the key from.\n * @param salt the salt to use, null for none.\n * @param dkLen the number of bytes needed for the derived key.\n * @param [options] the options to use:\n * [md] an optional message digest object to use.\n */\npki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {\n if(typeof md === 'undefined' || md === null) {\n if(!('md5' in forge.md)) {\n throw new Error('\"md5\" hash algorithm unavailable.');\n }\n md = forge.md.md5.create();\n }\n if(salt === null) {\n salt = '';\n }\n var digests = [hash(md, password + salt)];\n for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {\n digests.push(hash(md, digests[i - 1] + password + salt));\n }\n return digests.join('').substr(0, dkLen);\n};\n\nfunction hash(md, bytes) {\n return md.start().update(bytes).digest().getBytes();\n}\n\nfunction prfOidToMessageDigest(prfOid) {\n // get PRF algorithm, default to SHA-1\n var prfAlgorithm;\n if(!prfOid) {\n prfAlgorithm = 'hmacWithSHA1';\n } else {\n prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];\n if(!prfAlgorithm) {\n var error = new Error('Unsupported PRF OID.');\n error.oid = prfOid;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n }\n return prfAlgorithmToMessageDigest(prfAlgorithm);\n}\n\nfunction prfAlgorithmToMessageDigest(prfAlgorithm) {\n var factory = forge.md;\n switch(prfAlgorithm) {\n case 'hmacWithSHA224':\n factory = forge.md.sha512;\n case 'hmacWithSHA1':\n case 'hmacWithSHA256':\n case 'hmacWithSHA384':\n case 'hmacWithSHA512':\n prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();\n break;\n default:\n var error = new Error('Unsupported PRF algorithm.');\n error.algorithm = prfAlgorithm;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n if(!factory || !(prfAlgorithm in factory)) {\n throw new Error('Unknown hash algorithm: ' + prfAlgorithm);\n }\n return factory[prfAlgorithm].create();\n}\n\nfunction createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {\n var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ]);\n // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm\n if(prfAlgorithm !== 'hmacWithSHA1') {\n params.value.push(\n // key length\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(dkLen.toString(16))),\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n return params;\n}\n","/**\n * Javascript implementation of ASN.1 validators for PKCS#7 v1.5.\n *\n * @author Dave Longley\n * @author Stefan Siegl\n *\n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * The ASN.1 representation of PKCS#7 is as follows\n * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt):\n *\n * A PKCS#7 message consists of a ContentInfo on root level, which may\n * contain any number of further ContentInfo nested into it.\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * EnvelopedData ::= SEQUENCE {\n * version Version,\n * recipientInfos RecipientInfos,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * EncryptedData ::= SEQUENCE {\n * version Version,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)\n * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }\n *\n * SignedData ::= SEQUENCE {\n * version INTEGER,\n * digestAlgorithms DigestAlgorithmIdentifiers,\n * contentInfo ContentInfo,\n * certificates [0] IMPLICIT Certificates OPTIONAL,\n * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,\n * signerInfos SignerInfos\n * }\n *\n * SignerInfos ::= SET OF SignerInfo\n *\n * SignerInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * digestAlgorithm DigestAlgorithmIdentifier,\n * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,\n * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,\n * encryptedDigest EncryptedDigest,\n * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL\n * }\n *\n * EncryptedDigest ::= OCTET STRING\n *\n * Attributes ::= SET OF Attribute\n *\n * Attribute ::= SEQUENCE {\n * attrType OBJECT IDENTIFIER,\n * attrValues SET OF AttributeValue\n * }\n *\n * AttributeValue ::= ANY\n *\n * Version ::= INTEGER\n *\n * RecipientInfos ::= SET OF RecipientInfo\n *\n * EncryptedContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,\n * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL\n * }\n *\n * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of AES and DES3, there is only one,\n * the IV.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * EncryptedContent ::= OCTET STRING\n *\n * RecipientInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,\n * encryptedKey EncryptedKey\n * }\n *\n * IssuerAndSerialNumber ::= SEQUENCE {\n * issuer Name,\n * serialNumber CertificateSerialNumber\n * }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedKey ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./util');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {};\nforge.pkcs7 = forge.pkcs7 || {};\nforge.pkcs7.asn1 = p7v;\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'ContentInfo.ContentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n captureAsn1: 'content'\n }]\n};\np7v.contentInfoValidator = contentInfoValidator;\n\nvar encryptedContentInfoValidator = {\n name: 'EncryptedContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'encParameter'\n }]\n }, {\n name: 'EncryptedContentInfo.encryptedContent',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n /* The PKCS#7 structure output by OpenSSL somewhat differs from what\n * other implementations do generate.\n *\n * OpenSSL generates a structure like this:\n * SEQUENCE {\n * ...\n * [0]\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n *\n * Whereas other implementations (and this PKCS#7 module) generate:\n * SEQUENCE {\n * ...\n * [0] {\n * OCTET STRING\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n * }\n *\n * In order to support both, we just capture the context specific\n * field here. The OCTET STRING bit is removed below.\n */\n capture: 'encryptedContent',\n captureAsn1: 'encryptedContentAsn1'\n }]\n};\n\np7v.envelopedDataValidator = {\n name: 'EnvelopedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EnvelopedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'EnvelopedData.RecipientInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'recipientInfos'\n }].concat(encryptedContentInfoValidator)\n};\n\np7v.encryptedDataValidator = {\n name: 'EncryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }].concat(encryptedContentInfoValidator)\n};\n\nvar signerValidator = {\n name: 'SignerInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false\n }, {\n name: 'SignerInfo.issuerAndSerialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.issuerAndSerialNumber.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'SignerInfo.issuerAndSerialNumber.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'SignerInfo.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'digestAlgorithm'\n }, {\n name: 'SignerInfo.digestAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'digestParameter',\n optional: true\n }]\n }, {\n name: 'SignerInfo.authenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'authenticatedAttributes'\n }, {\n name: 'SignerInfo.digestEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n capture: 'signatureAlgorithm'\n }, {\n name: 'SignerInfo.encryptedDigest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'signature'\n }, {\n name: 'SignerInfo.unauthenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n capture: 'unauthenticatedAttributes'\n }]\n};\n\np7v.signedDataValidator = {\n name: 'SignedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'SignedData.DigestAlgorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'digestAlgorithms'\n },\n contentInfoValidator,\n {\n name: 'SignedData.Certificates',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n optional: true,\n captureAsn1: 'certificates'\n }, {\n name: 'SignedData.CertificateRevocationLists',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n optional: true,\n captureAsn1: 'crls'\n }, {\n name: 'SignedData.SignerInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n capture: 'signerInfos',\n optional: true,\n value: [signerValidator]\n }]\n};\n\np7v.recipientInfoValidator = {\n name: 'RecipientInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'RecipientInfo.issuerAndSerial',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.issuerAndSerial.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'RecipientInfo.issuerAndSerial.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'encParameter'\n }]\n }, {\n name: 'RecipientInfo.encryptedKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encKey'\n }]\n};\n","/**\n * Javascript implementation of mask generation function MGF1.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.mgf = forge.mgf || {};\nvar mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};\n\n/**\n * Creates a MGF1 mask generation function object.\n *\n * @param md the message digest API to use (eg: forge.md.sha1.create()).\n *\n * @return a mask generation function object.\n */\nmgf1.create = function(md) {\n var mgf = {\n /**\n * Generate mask of specified length.\n *\n * @param {String} seed The seed for mask generation.\n * @param maskLen Number of bytes to generate.\n * @return {String} The generated mask.\n */\n generate: function(seed, maskLen) {\n /* 2. Let T be the empty octet string. */\n var t = new forge.util.ByteBuffer();\n\n /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */\n var len = Math.ceil(maskLen / md.digestLength);\n for(var i = 0; i < len; i++) {\n /* a. Convert counter to an octet string C of length 4 octets */\n var c = new forge.util.ByteBuffer();\n c.putInt32(i);\n\n /* b. Concatenate the hash of the seed mgfSeed and C to the octet\n * string T: */\n md.start();\n md.update(seed + c.getBytes());\n t.putBuffer(md.digest());\n }\n\n /* Output the leading maskLen octets of T as the octet string mask. */\n t.truncate(t.length() - maskLen);\n return t.getBytes();\n }\n };\n\n return mgf;\n};\n","/**\n * Node.js module for Forge mask generation functions.\n *\n * @author Stefan Siegl\n *\n * Copyright 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./mgf1');\n\nmodule.exports = forge.mgf = forge.mgf || {};\nforge.mgf.mgf1 = forge.mgf1;\n","/**\n * Javascript implementation of PKCS#1 PSS signature padding.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./random');\nrequire('./util');\n\n// shortcut for PSS API\nvar pss = module.exports = forge.pss = forge.pss || {};\n\n/**\n * Creates a PSS signature scheme object.\n *\n * There are several ways to provide a salt for encoding:\n *\n * 1. Specify the saltLength only and the built-in PRNG will generate it.\n * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that\n * will be used.\n * 3. Specify the salt itself as a forge.util.ByteBuffer.\n *\n * @param options the options to use:\n * md the message digest object to use, a forge md instance.\n * mgf the mask generation function to use, a forge mgf instance.\n * [saltLength] the length of the salt in octets.\n * [prng] the pseudo-random number generator to use to produce a salt.\n * [salt] the salt to use when encoding.\n *\n * @return a signature scheme object.\n */\npss.create = function(options) {\n // backwards compatibility w/legacy args: hash, mgf, sLen\n if(arguments.length === 3) {\n options = {\n md: arguments[0],\n mgf: arguments[1],\n saltLength: arguments[2]\n };\n }\n\n var hash = options.md;\n var mgf = options.mgf;\n var hLen = hash.digestLength;\n\n var salt_ = options.salt || null;\n if(typeof salt_ === 'string') {\n // assume binary-encoded string\n salt_ = forge.util.createBuffer(salt_);\n }\n\n var sLen;\n if('saltLength' in options) {\n sLen = options.saltLength;\n } else if(salt_ !== null) {\n sLen = salt_.length();\n } else {\n throw new Error('Salt length not specified or specific salt not given.');\n }\n\n if(salt_ !== null && salt_.length() !== sLen) {\n throw new Error('Given salt length does not match length of given salt.');\n }\n\n var prng = options.prng || forge.random;\n\n var pssobj = {};\n\n /**\n * Encodes a PSS signature.\n *\n * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1.\n *\n * @param md the message digest object with the hash to sign.\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return the encoded message as a binary-encoded string of length\n * ceil((modBits - 1) / 8).\n */\n pssobj.encode = function(md, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* 2. Let mHash = Hash(M), an octet string of length hLen. */\n var mHash = md.digest().getBytes();\n\n /* 3. If emLen < hLen + sLen + 2, output \"encoding error\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Message is too long to encrypt.');\n }\n\n /* 4. Generate a random octet string salt of length sLen; if sLen = 0,\n * then salt is the empty string. */\n var salt;\n if(salt_ === null) {\n salt = prng.getBytesSync(sLen);\n } else {\n salt = salt_.bytes();\n }\n\n /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 6. Let H = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h = hash.digest().getBytes();\n\n /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2\n * zero octets. The length of PS may be 0. */\n var ps = new forge.util.ByteBuffer();\n ps.fillWithByte(0, emLen - sLen - hLen - 2);\n\n /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length\n * emLen - hLen - 1. */\n ps.putByte(0x01);\n ps.putBytes(salt);\n var db = ps.getBytes();\n\n /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */\n var maskLen = emLen - hLen - 1;\n var dbMask = mgf.generate(h, maskLen);\n\n /* 10. Let maskedDB = DB \\xor dbMask. */\n var maskedDB = '';\n for(i = 0; i < maskLen; i++) {\n maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB to zero. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) +\n maskedDB.substr(1);\n\n /* 12. Let EM = maskedDB || H || 0xbc.\n * 13. Output EM. */\n return maskedDB + h + String.fromCharCode(0xbc);\n };\n\n /**\n * Verifies a PSS signature.\n *\n * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2.\n *\n * @param mHash the message digest hash, as a binary-encoded string, to\n * compare against the signature.\n * @param em the encoded message, as a binary-encoded string\n * (RSA decryption result).\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return true if the signature was verified, false if not.\n */\n pssobj.verify = function(mHash, em, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* c. Convert the message representative m to an encoded message EM\n * of length emLen = ceil((modBits - 1) / 8) octets, where modBits\n * is the length in bits of the RSA modulus n */\n em = em.substr(-emLen);\n\n /* 3. If emLen < hLen + sLen + 2, output \"inconsistent\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Inconsistent parameters to PSS signature verification.');\n }\n\n /* 4. If the rightmost octet of EM does not have hexadecimal value\n * 0xbc, output \"inconsistent\" and stop. */\n if(em.charCodeAt(emLen - 1) !== 0xbc) {\n throw new Error('Encoded message does not end in 0xBC.');\n }\n\n /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and\n * let H be the next hLen octets. */\n var maskLen = emLen - hLen - 1;\n var maskedDB = em.substr(0, maskLen);\n var h = em.substr(maskLen, hLen);\n\n /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB are not all equal to zero, output \"inconsistent\" and stop. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n if((maskedDB.charCodeAt(0) & mask) !== 0) {\n throw new Error('Bits beyond keysize not zero as expected.');\n }\n\n /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */\n var dbMask = mgf.generate(h, maskLen);\n\n /* 8. Let DB = maskedDB \\xor dbMask. */\n var db = '';\n for(i = 0; i < maskLen; i++) {\n db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet\n * in DB to zero. */\n db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);\n\n /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero\n * or if the octet at position emLen - hLen - sLen - 1 (the leftmost\n * position is \"position 1\") does not have hexadecimal value 0x01,\n * output \"inconsistent\" and stop. */\n var checkLen = emLen - hLen - sLen - 2;\n for(i = 0; i < checkLen; i++) {\n if(db.charCodeAt(i) !== 0x00) {\n throw new Error('Leftmost octets not zero as expected');\n }\n }\n\n if(db.charCodeAt(checkLen) !== 0x01) {\n throw new Error('Inconsistent PSS signature, 0x01 marker not found');\n }\n\n /* 11. Let salt be the last sLen octets of DB. */\n var salt = db.substr(-sLen);\n\n /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 13. Let H' = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h_ = hash.digest().getBytes();\n\n /* 14. If H = H', output \"consistent.\" Otherwise, output \"inconsistent.\" */\n return h === h_;\n };\n\n return pssobj;\n};\n","/**\n * Javascript implementation of X.509 and related components (such as\n * Certification Signing Requests) of a Public Key Infrastructure.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The ASN.1 representation of an X.509v3 certificate is as follows\n * (see RFC 2459):\n *\n * Certificate ::= SEQUENCE {\n * tbsCertificate TBSCertificate,\n * signatureAlgorithm AlgorithmIdentifier,\n * signatureValue BIT STRING\n * }\n *\n * TBSCertificate ::= SEQUENCE {\n * version [0] EXPLICIT Version DEFAULT v1,\n * serialNumber CertificateSerialNumber,\n * signature AlgorithmIdentifier,\n * issuer Name,\n * validity Validity,\n * subject Name,\n * subjectPublicKeyInfo SubjectPublicKeyInfo,\n * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * extensions [3] EXPLICIT Extensions OPTIONAL\n * -- If present, version shall be v3\n * }\n *\n * Version ::= INTEGER { v1(0), v2(1), v3(2) }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * Name ::= CHOICE {\n * // only one possible choice for now\n * RDNSequence\n * }\n *\n * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName\n *\n * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue\n *\n * AttributeTypeAndValue ::= SEQUENCE {\n * type AttributeType,\n * value AttributeValue\n * }\n * AttributeType ::= OBJECT IDENTIFIER\n * AttributeValue ::= ANY DEFINED BY AttributeType\n *\n * Validity ::= SEQUENCE {\n * notBefore Time,\n * notAfter Time\n * }\n *\n * Time ::= CHOICE {\n * utcTime UTCTime,\n * generalTime GeneralizedTime\n * }\n *\n * UniqueIdentifier ::= BIT STRING\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension\n *\n * Extension ::= SEQUENCE {\n * extnID OBJECT IDENTIFIER,\n * critical BOOLEAN DEFAULT FALSE,\n * extnValue OCTET STRING\n * }\n *\n * The only key algorithm currently supported for PKI is RSA.\n *\n * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.\n *\n * PKCS#10 v1.7 describes certificate signing requests:\n *\n * CertificationRequestInfo:\n *\n * CertificationRequestInfo ::= SEQUENCE {\n * version INTEGER { v1(0) } (v1,...),\n * subject Name,\n * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},\n * attributes [0] Attributes{{ CRIAttributes }}\n * }\n *\n * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}\n *\n * CRIAttributes ATTRIBUTE ::= {\n * ... -- add any locally defined attributes here -- }\n *\n * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {\n * type ATTRIBUTE.&id({IOSet}),\n * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})\n * }\n *\n * CertificationRequest ::= SEQUENCE {\n * certificationRequestInfo CertificationRequestInfo,\n * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},\n * signature BIT STRING\n * }\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./mgf');\nrequire('./oids');\nrequire('./pem');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\nvar oids = pki.oids;\n\n// short name OID mappings\nvar _shortNames = {};\n_shortNames['CN'] = oids['commonName'];\n_shortNames['commonName'] = 'CN';\n_shortNames['C'] = oids['countryName'];\n_shortNames['countryName'] = 'C';\n_shortNames['L'] = oids['localityName'];\n_shortNames['localityName'] = 'L';\n_shortNames['ST'] = oids['stateOrProvinceName'];\n_shortNames['stateOrProvinceName'] = 'ST';\n_shortNames['O'] = oids['organizationName'];\n_shortNames['organizationName'] = 'O';\n_shortNames['OU'] = oids['organizationalUnitName'];\n_shortNames['organizationalUnitName'] = 'OU';\n_shortNames['E'] = oids['emailAddress'];\n_shortNames['emailAddress'] = 'E';\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator;\n\n// validator for an X.509v3 certificate\nvar x509CertificateValidator = {\n name: 'Certificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'tbsCertificate',\n value: [{\n name: 'Certificate.TBSCertificate.version',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.version.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certVersion'\n }]\n }, {\n name: 'Certificate.TBSCertificate.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certSerialNumber'\n }, {\n name: 'Certificate.TBSCertificate.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate.signature.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certinfoSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certinfoSignatureParams'\n }]\n }, {\n name: 'Certificate.TBSCertificate.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certIssuer'\n }, {\n name: 'Certificate.TBSCertificate.validity',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n // Note: UTC and generalized times may both appear so the capture\n // names are based on their detected order, the names used below\n // are only for the common case, which validity time really means\n // \"notBefore\" and which means \"notAfter\" will be determined by order\n value: [{\n // notBefore (Time) (UTC time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity1UTCTime'\n }, {\n // notBefore (Time) (generalized time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity2GeneralizedTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity3UTCTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity4GeneralizedTime'\n }]\n }, {\n // Name (subject) (RDNSequence)\n name: 'Certificate.TBSCertificate.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n // issuerUniqueID (optional)\n name: 'Certificate.TBSCertificate.issuerUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.issuerUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certIssuerUniqueId'\n }]\n }, {\n // subjectUniqueID (optional)\n name: 'Certificate.TBSCertificate.subjectUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.subjectUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certSubjectUniqueId'\n }]\n }, {\n // Extensions (optional)\n name: 'Certificate.TBSCertificate.extensions',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n constructed: true,\n captureAsn1: 'certExtensions',\n optional: true\n }]\n }, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'Certificate.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'Certificate.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certSignatureParams'\n }]\n }, {\n // SignatureValue\n name: 'Certificate.signatureValue',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'certSignature'\n }]\n};\n\nvar rsassaPssParameterValidator = {\n name: 'rsapss',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'hashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }, {\n name: 'rsapss.maskGenAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenOid'\n }, {\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenHashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }]\n }, {\n name: 'rsapss.saltLength',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n optional: true,\n value: [{\n name: 'rsapss.saltLength.saltLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'saltLength'\n }]\n }, {\n name: 'rsapss.trailerField',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n optional: true,\n value: [{\n name: 'rsapss.trailer.trailer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'trailer'\n }]\n }]\n};\n\n// validator for a CertificationRequestInfo structure\nvar certificationRequestInfoValidator = {\n name: 'CertificationRequestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfo',\n value: [{\n name: 'CertificationRequestInfo.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certificationRequestInfoVersion'\n }, {\n // Name (subject) (RDNSequence)\n name: 'CertificationRequestInfo.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfoSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'certificationRequestInfoAttributes',\n value: [{\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertificationRequestInfo.attributes.type',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false\n }, {\n name: 'CertificationRequestInfo.attributes.value',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true\n }]\n }]\n }]\n};\n\n// validator for a CertificationRequest structure\nvar certificationRequestValidator = {\n name: 'CertificationRequest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'csr',\n value: [\n certificationRequestInfoValidator, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'CertificationRequest.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'CertificationRequest.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'csrSignatureOid'\n }, {\n name: 'CertificationRequest.signatureAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'csrSignatureParams'\n }]\n }, {\n // signature\n name: 'CertificationRequest.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'csrSignature'\n }\n ]\n};\n\n/**\n * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName\n * sets into an array with objects that have type and value properties.\n *\n * @param rdn the RDNSequence to convert.\n * @param md a message digest to append type and value to if provided.\n */\npki.RDNAttributesAsArray = function(rdn, md) {\n var rval = [];\n\n // each value in 'rdn' in is a SET of RelativeDistinguishedName\n var set, attr, obj;\n for(var si = 0; si < rdn.value.length; ++si) {\n // get the RelativeDistinguishedName set\n set = rdn.value[si];\n\n // each value in the SET is an AttributeTypeAndValue sequence\n // containing first a type (an OID) and second a value (defined by\n // the OID)\n for(var i = 0; i < set.value.length; ++i) {\n obj = {};\n attr = set.value[i];\n obj.type = asn1.derToOid(attr.value[0].value);\n obj.value = attr.value[1].value;\n obj.valueTagClass = attr.value[1].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n if(md) {\n md.update(obj.type);\n md.update(obj.value);\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Converts ASN.1 CRIAttributes into an array with objects that have type and\n * value properties.\n *\n * @param attributes the CRIAttributes to convert.\n */\npki.CRIAttributesAsArray = function(attributes) {\n var rval = [];\n\n // each value in 'attributes' in is a SEQUENCE with an OID and a SET\n for(var si = 0; si < attributes.length; ++si) {\n // get the attribute sequence\n var seq = attributes[si];\n\n // each value in the SEQUENCE containing first a type (an OID) and\n // second a set of values (defined by the OID)\n var type = asn1.derToOid(seq.value[0].value);\n var values = seq.value[1].value;\n for(var vi = 0; vi < values.length; ++vi) {\n var obj = {};\n obj.type = type;\n obj.value = values[vi].value;\n obj.valueTagClass = values[vi].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n // parse extensions\n if(obj.type === oids.extensionRequest) {\n obj.extensions = [];\n for(var ei = 0; ei < obj.value.length; ++ei) {\n obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));\n }\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Gets an issuer or subject attribute from its name, type, or short name.\n *\n * @param obj the issuer or subject object.\n * @param options a short name string or an object with:\n * shortName the short name for the attribute.\n * name the name for the attribute.\n * type the type for the attribute.\n *\n * @return the attribute.\n */\nfunction _getAttribute(obj, options) {\n if(typeof options === 'string') {\n options = {shortName: options};\n }\n\n var rval = null;\n var attr;\n for(var i = 0; rval === null && i < obj.attributes.length; ++i) {\n attr = obj.attributes[i];\n if(options.type && options.type === attr.type) {\n rval = attr;\n } else if(options.name && options.name === attr.name) {\n rval = attr;\n } else if(options.shortName && options.shortName === attr.shortName) {\n rval = attr;\n }\n }\n return rval;\n}\n\n/**\n * Converts signature parameters from ASN.1 structure.\n *\n * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had\n * no parameters.\n *\n * RSASSA-PSS-params ::= SEQUENCE {\n * hashAlgorithm [0] HashAlgorithm DEFAULT\n * sha1Identifier,\n * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT\n * mgf1SHA1Identifier,\n * saltLength [2] INTEGER DEFAULT 20,\n * trailerField [3] INTEGER DEFAULT 1\n * }\n *\n * HashAlgorithm ::= AlgorithmIdentifier\n *\n * MaskGenAlgorithm ::= AlgorithmIdentifier\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * @param oid The OID specifying the signature algorithm\n * @param obj The ASN.1 structure holding the parameters\n * @param fillDefaults Whether to use return default values where omitted\n * @return signature parameter object\n */\nvar _readSignatureParameters = function(oid, obj, fillDefaults) {\n var params = {};\n\n if(oid !== oids['RSASSA-PSS']) {\n return params;\n }\n\n if(fillDefaults) {\n params = {\n hash: {\n algorithmOid: oids['sha1']\n },\n mgf: {\n algorithmOid: oids['mgf1'],\n hash: {\n algorithmOid: oids['sha1']\n }\n },\n saltLength: 20\n };\n }\n\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {\n var error = new Error('Cannot read RSASSA-PSS parameter block.');\n error.errors = errors;\n throw error;\n }\n\n if(capture.hashOid !== undefined) {\n params.hash = params.hash || {};\n params.hash.algorithmOid = asn1.derToOid(capture.hashOid);\n }\n\n if(capture.maskGenOid !== undefined) {\n params.mgf = params.mgf || {};\n params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);\n params.mgf.hash = params.mgf.hash || {};\n params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);\n }\n\n if(capture.saltLength !== undefined) {\n params.saltLength = capture.saltLength.charCodeAt(0);\n }\n\n return params;\n};\n\n/**\n * Converts an X.509 certificate from PEM format.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. This will scan the TBSCertificate part of the ASN.1\n * object while it is converted so it doesn't need to be converted back\n * to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certificate.\n */\npki.certificateFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error(\n 'Could not convert certificate from PEM; PEM header type ' +\n 'is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or \"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error(\n 'Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificateFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts an X.509 certificate to PEM format.\n *\n * @param cert the certificate.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certificate.\n */\npki.certificateToPem = function(cert, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE',\n body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key from PEM format.\n *\n * @param pem the PEM-formatted public key.\n *\n * @return the public key.\n */\npki.publicKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {\n var error = new Error('Could not convert public key from PEM; PEM header ' +\n 'type is not \"PUBLIC KEY\" or \"RSA PUBLIC KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert public key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.publicKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key to PEM format (using an RSAPublicKey).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToRSAPublicKeyPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Gets a fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.sha1).\n * [type] the type of fingerprint, such as 'RSAPublicKey',\n * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\npki.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.sha1.create();\n var type = options.type || 'RSAPublicKey';\n\n var bytes;\n switch(type) {\n case 'RSAPublicKey':\n bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();\n break;\n case 'SubjectPublicKeyInfo':\n bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();\n break;\n default:\n throw new Error('Unknown fingerprint type \"' + options.type + '\".');\n }\n\n // hash public key bytes\n md.start();\n md.update(bytes);\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from PEM format.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. This will scan the CertificationRequestInfo part of\n * the ASN.1 object while it is converted so it doesn't need to be converted\n * back to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE REQUEST') {\n var error = new Error('Could not convert certification request from PEM; ' +\n 'PEM header type is not \"CERTIFICATE REQUEST\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certification request from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificationRequestFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) to PEM format.\n *\n * @param csr the certification request.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certification request.\n */\npki.certificationRequestToPem = function(csr, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE REQUEST',\n body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Creates an empty X.509v3 RSA certificate.\n *\n * @return the certificate.\n */\npki.createCertificate = function() {\n var cert = {};\n cert.version = 0x02;\n cert.serialNumber = '00';\n cert.signatureOid = null;\n cert.signature = null;\n cert.siginfo = {};\n cert.siginfo.algorithmOid = null;\n cert.validity = {};\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n\n cert.issuer = {};\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = [];\n cert.issuer.hash = null;\n\n cert.subject = {};\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = [];\n cert.subject.hash = null;\n\n cert.extensions = [];\n cert.publicKey = null;\n cert.md = null;\n\n /**\n * Sets the subject of this certificate.\n *\n * @param attrs the array of subject attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setSubject = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.subject.attributes = attrs;\n delete cert.subject.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.subject.uniqueId = uniqueId;\n }\n cert.subject.hash = null;\n };\n\n /**\n * Sets the issuer of this certificate.\n *\n * @param attrs the array of issuer attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setIssuer = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.issuer.attributes = attrs;\n delete cert.issuer.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.issuer.uniqueId = uniqueId;\n }\n cert.issuer.hash = null;\n };\n\n /**\n * Sets the extensions of this certificate.\n *\n * @param exts the array of extensions to use.\n */\n cert.setExtensions = function(exts) {\n for(var i = 0; i < exts.length; ++i) {\n _fillMissingExtensionFields(exts[i], {cert: cert});\n }\n // set new extensions\n cert.extensions = exts;\n };\n\n /**\n * Gets an extension by its name or id.\n *\n * @param options the name to use or an object with:\n * name the name to use.\n * id the id to use.\n *\n * @return the extension or null if not found.\n */\n cert.getExtension = function(options) {\n if(typeof options === 'string') {\n options = {name: options};\n }\n\n var rval = null;\n var ext;\n for(var i = 0; rval === null && i < cert.extensions.length; ++i) {\n ext = cert.extensions[i];\n if(options.id && ext.id === options.id) {\n rval = ext;\n } else if(options.name && ext.name === options.name) {\n rval = ext;\n }\n }\n return rval;\n };\n\n /**\n * Signs this certificate using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n cert.sign = function(key, md) {\n // TODO: get signature OID from private key\n cert.md = md || forge.md.sha1.create();\n var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = cert.md.algorithm;\n throw error;\n }\n cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;\n\n // get TBSCertificate, convert to DER\n cert.tbsCertificate = pki.getTBSCertificate(cert);\n var bytes = asn1.toDer(cert.tbsCertificate);\n\n // digest and sign\n cert.md.update(bytes.getBytes());\n cert.signature = key.sign(cert.md);\n };\n\n /**\n * Attempts verify the signature on the passed certificate using this\n * certificate's public key.\n *\n * @param child the certificate to verify.\n *\n * @return true if verified, false if not.\n */\n cert.verify = function(child) {\n var rval = false;\n\n if(!cert.issued(child)) {\n var issuer = child.issuer;\n var subject = cert.subject;\n var error = new Error(\n 'The parent certificate did not issue the given child ' +\n 'certificate; the child certificate\\'s issuer does not match the ' +\n 'parent\\'s subject.');\n error.expectedIssuer = issuer.attributes;\n error.actualIssuer = subject.attributes;\n throw error;\n }\n\n var md = child.md;\n if(md === null) {\n // check signature OID for supported signature types\n if(child.signatureOid in oids) {\n var oid = oids[child.signatureOid];\n switch(oid) {\n case 'sha1WithRSAEncryption':\n md = forge.md.sha1.create();\n break;\n case 'md5WithRSAEncryption':\n md = forge.md.md5.create();\n break;\n case 'sha256WithRSAEncryption':\n md = forge.md.sha256.create();\n break;\n case 'sha384WithRSAEncryption':\n md = forge.md.sha384.create();\n break;\n case 'sha512WithRSAEncryption':\n md = forge.md.sha512.create();\n break;\n case 'RSASSA-PSS':\n md = forge.md.sha256.create();\n break;\n }\n }\n if(md === null) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = child.signatureOid;\n throw error;\n }\n\n // produce DER formatted TBSCertificate and digest it\n var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);\n var bytes = asn1.toDer(tbsCertificate);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n var scheme;\n\n switch(child.signatureOid) {\n case oids.sha1WithRSAEncryption:\n scheme = undefined; /* use PKCS#1 v1.5 padding scheme */\n break;\n case oids['RSASSA-PSS']:\n var hash, mgf;\n\n /* initialize mgf */\n hash = oids[child.signatureParameters.mgf.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported MGF hash function.');\n error.oid = child.signatureParameters.mgf.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n mgf = oids[child.signatureParameters.mgf.algorithmOid];\n if(mgf === undefined || forge.mgf[mgf] === undefined) {\n var error = new Error('Unsupported MGF function.');\n error.oid = child.signatureParameters.mgf.algorithmOid;\n error.name = mgf;\n throw error;\n }\n\n mgf = forge.mgf[mgf].create(forge.md[hash].create());\n\n /* initialize hash function */\n hash = oids[child.signatureParameters.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n throw {\n message: 'Unsupported RSASSA-PSS hash function.',\n oid: child.signatureParameters.hash.algorithmOid,\n name: hash\n };\n }\n\n scheme = forge.pss.create(forge.md[hash].create(), mgf,\n child.signatureParameters.saltLength);\n break;\n }\n\n // verify signature on cert using public key\n rval = cert.publicKey.verify(\n md.digest().getBytes(), child.signature, scheme);\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's issuer matches the passed\n * certificate's subject. Note that no signature check is performed.\n *\n * @param parent the certificate to check.\n *\n * @return true if this certificate's issuer matches the passed certificate's\n * subject.\n */\n cert.isIssuer = function(parent) {\n var rval = false;\n\n var i = cert.issuer;\n var s = parent.subject;\n\n // compare hashes if present\n if(i.hash && s.hash) {\n rval = (i.hash === s.hash);\n } else if(i.attributes.length === s.attributes.length) {\n // all attributes are the same so issuer matches subject\n rval = true;\n var iattr, sattr;\n for(var n = 0; rval && n < i.attributes.length; ++n) {\n iattr = i.attributes[n];\n sattr = s.attributes[n];\n if(iattr.type !== sattr.type || iattr.value !== sattr.value) {\n // attribute mismatch\n rval = false;\n }\n }\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's subject matches the issuer of the\n * given certificate). Note that not signature check is performed.\n *\n * @param child the certificate to check.\n *\n * @return true if this certificate's subject matches the passed\n * certificate's issuer.\n */\n cert.issued = function(child) {\n return child.isIssuer(cert);\n };\n\n /**\n * Generates the subjectKeyIdentifier for this certificate as byte buffer.\n *\n * @return the subjectKeyIdentifier for this certificate as byte buffer.\n */\n cert.generateSubjectKeyIdentifier = function() {\n /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:\n\n (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the\n value of the BIT STRING subjectPublicKey (excluding the tag,\n length, and number of unused bits).\n\n (2) The keyIdentifier is composed of a four bit type field with\n the value 0100 followed by the least significant 60 bits of the\n SHA-1 hash of the value of the BIT STRING subjectPublicKey\n (excluding the tag, length, and number of unused bit string bits).\n */\n\n // skipping the tag, length, and number of unused bits is the same\n // as just using the RSAPublicKey (for RSA keys, which are the\n // only ones supported)\n return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});\n };\n\n /**\n * Verifies the subjectKeyIdentifier extension value for this certificate\n * against its public key. If no extension is found, false will be\n * returned.\n *\n * @return true if verified, false if not.\n */\n cert.verifySubjectKeyIdentifier = function() {\n var oid = oids['subjectKeyIdentifier'];\n for(var i = 0; i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.id === oid) {\n var ski = cert.generateSubjectKeyIdentifier().getBytes();\n return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski);\n }\n }\n return false;\n };\n\n return cert;\n};\n\n/**\n * Converts an X.509v3 RSA certificate from an ASN.1 object.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1\n * object needs to be scanned before the cert object is created.\n *\n * @param obj the asn1 representation of an X.509v3 RSA certificate.\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certificate.\n */\npki.certificateFromAsn1 = function(obj, computeHash) {\n // validate certificate and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) {\n var error = new Error('Cannot read X.509 certificate. ' +\n 'ASN.1 object is not an X509v3 Certificate.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certificate\n var cert = pki.createCertificate();\n cert.version = capture.certVersion ?\n capture.certVersion.charCodeAt(0) : 0;\n var serial = forge.util.createBuffer(capture.certSerialNumber);\n cert.serialNumber = serial.toHex();\n cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);\n cert.signatureParameters = _readSignatureParameters(\n cert.signatureOid, capture.certSignatureParams, true);\n cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);\n cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,\n capture.certinfoSignatureParams, false);\n cert.signature = capture.certSignature;\n\n var validity = [];\n if(capture.certValidity1UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));\n }\n if(capture.certValidity2GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity2GeneralizedTime));\n }\n if(capture.certValidity3UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));\n }\n if(capture.certValidity4GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity4GeneralizedTime));\n }\n if(validity.length > 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; more ' +\n 'than two times were provided in the certificate.');\n }\n if(validity.length < 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; they ' +\n 'were not provided as either UTCTime or GeneralizedTime.');\n }\n cert.validity.notBefore = validity[0];\n cert.validity.notAfter = validity[1];\n\n // keep TBSCertificate to preserve signature when exporting\n cert.tbsCertificate = capture.tbsCertificate;\n\n if(computeHash) {\n // check signature OID for supported signature types\n cert.md = null;\n if(cert.signatureOid in oids) {\n var oid = oids[cert.signatureOid];\n switch(oid) {\n case 'sha1WithRSAEncryption':\n cert.md = forge.md.sha1.create();\n break;\n case 'md5WithRSAEncryption':\n cert.md = forge.md.md5.create();\n break;\n case 'sha256WithRSAEncryption':\n cert.md = forge.md.sha256.create();\n break;\n case 'sha384WithRSAEncryption':\n cert.md = forge.md.sha384.create();\n break;\n case 'sha512WithRSAEncryption':\n cert.md = forge.md.sha512.create();\n break;\n case 'RSASSA-PSS':\n cert.md = forge.md.sha256.create();\n break;\n }\n }\n if(cert.md === null) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = cert.signatureOid;\n throw error;\n }\n\n // produce DER formatted TBSCertificate and digest it\n var bytes = asn1.toDer(cert.tbsCertificate);\n cert.md.update(bytes.getBytes());\n }\n\n // handle issuer, build issuer message digest\n var imd = forge.md.sha1.create();\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer, imd);\n if(capture.certIssuerUniqueId) {\n cert.issuer.uniqueId = capture.certIssuerUniqueId;\n }\n cert.issuer.hash = imd.digest().toHex();\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject, smd);\n if(capture.certSubjectUniqueId) {\n cert.subject.uniqueId = capture.certSubjectUniqueId;\n }\n cert.subject.hash = smd.digest().toHex();\n\n // handle extensions\n if(capture.certExtensions) {\n cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);\n } else {\n cert.extensions = [];\n }\n\n // convert RSA public key from ASN.1\n cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n return cert;\n};\n\n/**\n * Converts an ASN.1 extensions object (with extension sequences as its\n * values) into an array of extension objects with types and values.\n *\n * Supported extensions:\n *\n * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }\n * KeyUsage ::= BIT STRING {\n * digitalSignature (0),\n * nonRepudiation (1),\n * keyEncipherment (2),\n * dataEncipherment (3),\n * keyAgreement (4),\n * keyCertSign (5),\n * cRLSign (6),\n * encipherOnly (7),\n * decipherOnly (8)\n * }\n *\n * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }\n * BasicConstraints ::= SEQUENCE {\n * cA BOOLEAN DEFAULT FALSE,\n * pathLenConstraint INTEGER (0..MAX) OPTIONAL\n * }\n *\n * subjectAltName EXTENSION ::= {\n * SYNTAX GeneralNames\n * IDENTIFIED BY id-ce-subjectAltName\n * }\n *\n * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName\n *\n * GeneralName ::= CHOICE {\n * otherName [0] INSTANCE OF OTHER-NAME,\n * rfc822Name [1] IA5String,\n * dNSName [2] IA5String,\n * x400Address [3] ORAddress,\n * directoryName [4] Name,\n * ediPartyName [5] EDIPartyName,\n * uniformResourceIdentifier [6] IA5String,\n * IPAddress [7] OCTET STRING,\n * registeredID [8] OBJECT IDENTIFIER\n * }\n *\n * OTHER-NAME ::= TYPE-IDENTIFIER\n *\n * EDIPartyName ::= SEQUENCE {\n * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,\n * partyName [1] DirectoryString {ub-name}\n * }\n *\n * @param exts the extensions ASN.1 with extension sequences to parse.\n *\n * @return the array.\n */\npki.certificateExtensionsFromAsn1 = function(exts) {\n var rval = [];\n for(var i = 0; i < exts.value.length; ++i) {\n // get extension sequence\n var extseq = exts.value[i];\n for(var ei = 0; ei < extseq.value.length; ++ei) {\n rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));\n }\n }\n\n return rval;\n};\n\n/**\n * Parses a single certificate extension from ASN.1.\n *\n * @param ext the extension in ASN.1 format.\n *\n * @return the parsed extension as an object.\n */\npki.certificateExtensionFromAsn1 = function(ext) {\n // an extension has:\n // [0] extnID OBJECT IDENTIFIER\n // [1] critical BOOLEAN DEFAULT FALSE\n // [2] extnValue OCTET STRING\n var e = {};\n e.id = asn1.derToOid(ext.value[0].value);\n e.critical = false;\n if(ext.value[1].type === asn1.Type.BOOLEAN) {\n e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);\n e.value = ext.value[2].value;\n } else {\n e.value = ext.value[1].value;\n }\n // if the oid is known, get its name\n if(e.id in oids) {\n e.name = oids[e.id];\n\n // handle key usage\n if(e.name === 'keyUsage') {\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n var b3 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;\n }\n // set flags\n e.digitalSignature = (b2 & 0x80) === 0x80;\n e.nonRepudiation = (b2 & 0x40) === 0x40;\n e.keyEncipherment = (b2 & 0x20) === 0x20;\n e.dataEncipherment = (b2 & 0x10) === 0x10;\n e.keyAgreement = (b2 & 0x08) === 0x08;\n e.keyCertSign = (b2 & 0x04) === 0x04;\n e.cRLSign = (b2 & 0x02) === 0x02;\n e.encipherOnly = (b2 & 0x01) === 0x01;\n e.decipherOnly = (b3 & 0x80) === 0x80;\n } else if(e.name === 'basicConstraints') {\n // handle basic constraints\n // get value as SEQUENCE\n var ev = asn1.fromDer(e.value);\n // get cA BOOLEAN flag (defaults to false)\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {\n e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);\n } else {\n e.cA = false;\n }\n // get path length constraint\n var value = null;\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {\n value = ev.value[0].value;\n } else if(ev.value.length > 1) {\n value = ev.value[1].value;\n }\n if(value !== null) {\n e.pathLenConstraint = asn1.derToInteger(value);\n }\n } else if(e.name === 'extKeyUsage') {\n // handle extKeyUsage\n // value is a SEQUENCE of OIDs\n var ev = asn1.fromDer(e.value);\n for(var vi = 0; vi < ev.value.length; ++vi) {\n var oid = asn1.derToOid(ev.value[vi].value);\n if(oid in oids) {\n e[oids[oid]] = true;\n } else {\n e[oid] = true;\n }\n }\n } else if(e.name === 'nsCertType') {\n // handle nsCertType\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n }\n // set flags\n e.client = (b2 & 0x80) === 0x80;\n e.server = (b2 & 0x40) === 0x40;\n e.email = (b2 & 0x20) === 0x20;\n e.objsign = (b2 & 0x10) === 0x10;\n e.reserved = (b2 & 0x08) === 0x08;\n e.sslCA = (b2 & 0x04) === 0x04;\n e.emailCA = (b2 & 0x02) === 0x02;\n e.objCA = (b2 & 0x01) === 0x01;\n } else if(\n e.name === 'subjectAltName' ||\n e.name === 'issuerAltName') {\n // handle subjectAltName/issuerAltName\n e.altNames = [];\n\n // ev is a SYNTAX SEQUENCE\n var gn;\n var ev = asn1.fromDer(e.value);\n for(var n = 0; n < ev.value.length; ++n) {\n // get GeneralName\n gn = ev.value[n];\n\n var altName = {\n type: gn.type,\n value: gn.value\n };\n e.altNames.push(altName);\n\n // Note: Support for types 1,2,6,7,8\n switch(gn.type) {\n // rfc822Name\n case 1:\n // dNSName\n case 2:\n // uniformResourceIdentifier (URI)\n case 6:\n break;\n // IPAddress\n case 7:\n // convert to IPv4/IPv6 string representation\n altName.ip = forge.util.bytesToIP(gn.value);\n break;\n // registeredID\n case 8:\n altName.oid = asn1.derToOid(gn.value);\n break;\n default:\n // unsupported\n }\n }\n } else if(e.name === 'subjectKeyIdentifier') {\n // value is an OCTETSTRING w/the hash of the key-type specific\n // public key structure (eg: RSAPublicKey)\n var ev = asn1.fromDer(e.value);\n e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);\n }\n }\n return e;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the CertificationRequestInfo part of the\n * ASN.1 object needs to be scanned before the csr object is created.\n *\n * @param obj the asn1 representation of a PKCS#10 certification request (CSR).\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromAsn1 = function(obj, computeHash) {\n // validate certification request and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#10 certificate request. ' +\n 'ASN.1 object is not a PKCS#10 CertificationRequest.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certification request\n var csr = pki.createCertificationRequest();\n csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;\n csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.signatureParameters = _readSignatureParameters(\n csr.signatureOid, capture.csrSignatureParams, true);\n csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.siginfo.parameters = _readSignatureParameters(\n csr.siginfo.algorithmOid, capture.csrSignatureParams, false);\n csr.signature = capture.csrSignature;\n\n // keep CertificationRequestInfo to preserve signature when exporting\n csr.certificationRequestInfo = capture.certificationRequestInfo;\n\n if(computeHash) {\n // check signature OID for supported signature types\n csr.md = null;\n if(csr.signatureOid in oids) {\n var oid = oids[csr.signatureOid];\n switch(oid) {\n case 'sha1WithRSAEncryption':\n csr.md = forge.md.sha1.create();\n break;\n case 'md5WithRSAEncryption':\n csr.md = forge.md.md5.create();\n break;\n case 'sha256WithRSAEncryption':\n csr.md = forge.md.sha256.create();\n break;\n case 'sha384WithRSAEncryption':\n csr.md = forge.md.sha384.create();\n break;\n case 'sha512WithRSAEncryption':\n csr.md = forge.md.sha512.create();\n break;\n case 'RSASSA-PSS':\n csr.md = forge.md.sha256.create();\n break;\n }\n }\n if(csr.md === null) {\n var error = new Error('Could not compute certification request digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = csr.signatureOid;\n throw error;\n }\n\n // produce DER formatted CertificationRequestInfo and digest it\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n csr.md.update(bytes.getBytes());\n }\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = pki.RDNAttributesAsArray(\n capture.certificationRequestInfoSubject, smd);\n csr.subject.hash = smd.digest().toHex();\n\n // convert RSA public key from ASN.1\n csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n // convert attributes from ASN.1\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.attributes = pki.CRIAttributesAsArray(\n capture.certificationRequestInfoAttributes || []);\n\n return csr;\n};\n\n/**\n * Creates an empty certification request (a CSR or certificate signing\n * request). Once created, its public key and attributes can be set and then\n * it can be signed.\n *\n * @return the empty certification request.\n */\npki.createCertificationRequest = function() {\n var csr = {};\n csr.version = 0x00;\n csr.signatureOid = null;\n csr.signature = null;\n csr.siginfo = {};\n csr.siginfo.algorithmOid = null;\n\n csr.subject = {};\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = [];\n csr.subject.hash = null;\n\n csr.publicKey = null;\n csr.attributes = [];\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.md = null;\n\n /**\n * Sets the subject of this certification request.\n *\n * @param attrs the array of subject attributes to use.\n */\n csr.setSubject = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.subject.attributes = attrs;\n csr.subject.hash = null;\n };\n\n /**\n * Sets the attributes of this certification request.\n *\n * @param attrs the array of attributes to use.\n */\n csr.setAttributes = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.attributes = attrs;\n };\n\n /**\n * Signs this certification request using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n csr.sign = function(key, md) {\n // TODO: get signature OID from private key\n csr.md = md || forge.md.sha1.create();\n var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certification request digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = csr.md.algorithm;\n throw error;\n }\n csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;\n\n // get CertificationRequestInfo, convert to DER\n csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n\n // digest and sign\n csr.md.update(bytes.getBytes());\n csr.signature = key.sign(csr.md);\n };\n\n /**\n * Attempts verify the signature on the passed certification request using\n * its public key.\n *\n * A CSR that has been exported to a file in PEM format can be verified using\n * OpenSSL using this command:\n *\n * openssl req -in -verify -noout -text\n *\n * @return true if verified, false if not.\n */\n csr.verify = function() {\n var rval = false;\n\n var md = csr.md;\n if(md === null) {\n // check signature OID for supported signature types\n if(csr.signatureOid in oids) {\n // TODO: create DRY `OID to md` function\n var oid = oids[csr.signatureOid];\n switch(oid) {\n case 'sha1WithRSAEncryption':\n md = forge.md.sha1.create();\n break;\n case 'md5WithRSAEncryption':\n md = forge.md.md5.create();\n break;\n case 'sha256WithRSAEncryption':\n md = forge.md.sha256.create();\n break;\n case 'sha384WithRSAEncryption':\n md = forge.md.sha384.create();\n break;\n case 'sha512WithRSAEncryption':\n md = forge.md.sha512.create();\n break;\n case 'RSASSA-PSS':\n md = forge.md.sha256.create();\n break;\n }\n }\n if(md === null) {\n var error = new Error(\n 'Could not compute certification request digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = csr.signatureOid;\n throw error;\n }\n\n // produce DER formatted CertificationRequestInfo and digest it\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(cri);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n var scheme;\n\n switch(csr.signatureOid) {\n case oids.sha1WithRSAEncryption:\n /* use PKCS#1 v1.5 padding scheme */\n break;\n case oids['RSASSA-PSS']:\n var hash, mgf;\n\n /* initialize mgf */\n hash = oids[csr.signatureParameters.mgf.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported MGF hash function.');\n error.oid = csr.signatureParameters.mgf.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n mgf = oids[csr.signatureParameters.mgf.algorithmOid];\n if(mgf === undefined || forge.mgf[mgf] === undefined) {\n var error = new Error('Unsupported MGF function.');\n error.oid = csr.signatureParameters.mgf.algorithmOid;\n error.name = mgf;\n throw error;\n }\n\n mgf = forge.mgf[mgf].create(forge.md[hash].create());\n\n /* initialize hash function */\n hash = oids[csr.signatureParameters.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported RSASSA-PSS hash function.');\n error.oid = csr.signatureParameters.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n scheme = forge.pss.create(forge.md[hash].create(), mgf,\n csr.signatureParameters.saltLength);\n break;\n }\n\n // verify signature on csr using its public key\n rval = csr.publicKey.verify(\n md.digest().getBytes(), csr.signature, scheme);\n }\n\n return rval;\n };\n\n return csr;\n};\n\n/**\n * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.\n *\n * @param obj the subject or issuer (distinguished name).\n *\n * @return the ASN.1 RDNSequence.\n */\nfunction _dnToAsn1(obj) {\n // create an empty RDNSequence\n var rval = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // iterate over attributes\n var attr, set;\n var attrs = obj.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.PRINTABLESTRING;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n // FIXME: handle more encodings\n }\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n // AttributeValue\n asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)\n ])\n ]);\n rval.value.push(set);\n }\n\n return rval;\n}\n\n/**\n * Gets all printable attributes (typically of an issuer or subject) in a\n * simplified JSON format for display.\n *\n * @param attrs the attributes.\n *\n * @return the JSON for display.\n */\nfunction _getAttributesAsJson(attrs) {\n var rval = {};\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n if(attr.shortName && (\n attr.valueTagClass === asn1.Type.UTF8 ||\n attr.valueTagClass === asn1.Type.PRINTABLESTRING ||\n attr.valueTagClass === asn1.Type.IA5STRING)) {\n var value = attr.value;\n if(attr.valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(attr.value);\n }\n if(!(attr.shortName in rval)) {\n rval[attr.shortName] = value;\n } else if(forge.util.isArray(rval[attr.shortName])) {\n rval[attr.shortName].push(value);\n } else {\n rval[attr.shortName] = [rval[attr.shortName], value];\n }\n }\n }\n return rval;\n}\n\n/**\n * Fills in missing fields in attributes.\n *\n * @param attrs the attributes to fill missing fields in.\n */\nfunction _fillMissingFields(attrs) {\n var attr;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n\n // populate missing name\n if(typeof attr.name === 'undefined') {\n if(attr.type && attr.type in pki.oids) {\n attr.name = pki.oids[attr.type];\n } else if(attr.shortName && attr.shortName in _shortNames) {\n attr.name = pki.oids[_shortNames[attr.shortName]];\n }\n }\n\n // populate missing type (OID)\n if(typeof attr.type === 'undefined') {\n if(attr.name && attr.name in pki.oids) {\n attr.type = pki.oids[attr.name];\n } else {\n var error = new Error('Attribute type not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n\n // populate missing shortname\n if(typeof attr.shortName === 'undefined') {\n if(attr.name && attr.name in _shortNames) {\n attr.shortName = _shortNames[attr.name];\n }\n }\n\n // convert extensions to value\n if(attr.type === oids.extensionRequest) {\n attr.valueConstructed = true;\n attr.valueTagClass = asn1.Type.SEQUENCE;\n if(!attr.value && attr.extensions) {\n attr.value = [];\n for(var ei = 0; ei < attr.extensions.length; ++ei) {\n attr.value.push(pki.certificateExtensionToAsn1(\n _fillMissingExtensionFields(attr.extensions[ei])));\n }\n }\n }\n\n if(typeof attr.value === 'undefined') {\n var error = new Error('Attribute value not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n}\n\n/**\n * Fills in missing fields in certificate extensions.\n *\n * @param e the extension.\n * @param [options] the options to use.\n * [cert] the certificate the extensions are for.\n *\n * @return the extension.\n */\nfunction _fillMissingExtensionFields(e, options) {\n options = options || {};\n\n // populate missing name\n if(typeof e.name === 'undefined') {\n if(e.id && e.id in pki.oids) {\n e.name = pki.oids[e.id];\n }\n }\n\n // populate missing id\n if(typeof e.id === 'undefined') {\n if(e.name && e.name in pki.oids) {\n e.id = pki.oids[e.name];\n } else {\n var error = new Error('Extension ID not specified.');\n error.extension = e;\n throw error;\n }\n }\n\n if(typeof e.value !== 'undefined') {\n return e;\n }\n\n // handle missing value:\n\n // value is a BIT STRING\n if(e.name === 'keyUsage') {\n // build flags\n var unused = 0;\n var b2 = 0x00;\n var b3 = 0x00;\n if(e.digitalSignature) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.nonRepudiation) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.keyEncipherment) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.dataEncipherment) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.keyAgreement) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.keyCertSign) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.cRLSign) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.encipherOnly) {\n b2 |= 0x01;\n unused = 0;\n }\n if(e.decipherOnly) {\n b3 |= 0x80;\n unused = 7;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b3 !== 0) {\n value += String.fromCharCode(b2) + String.fromCharCode(b3);\n } else if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'basicConstraints') {\n // basicConstraints is a SEQUENCE\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n // cA BOOLEAN flag defaults to false\n if(e.cA) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n if('pathLenConstraint' in e) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(e.pathLenConstraint).getBytes()));\n }\n } else if(e.name === 'extKeyUsage') {\n // extKeyUsage is a SEQUENCE of OIDs\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n for(var key in e) {\n if(e[key] !== true) {\n continue;\n }\n // key is name in OID map\n if(key in oids) {\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(oids[key]).getBytes()));\n } else if(key.indexOf('.') !== -1) {\n // assume key is an OID\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(key).getBytes()));\n }\n }\n } else if(e.name === 'nsCertType') {\n // nsCertType is a BIT STRING\n // build flags\n var unused = 0;\n var b2 = 0x00;\n\n if(e.client) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.server) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.email) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.objsign) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.reserved) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.sslCA) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.emailCA) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.objCA) {\n b2 |= 0x01;\n unused = 0;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n e.value.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n } else if(e.name === 'nsComment' && options.cert) {\n // sanity check value is ASCII (req'd) and not too big\n if(!(/^[\\x00-\\x7F]*$/.test(e.comment)) ||\n (e.comment.length < 1) || (e.comment.length > 128)) {\n throw new Error('Invalid \"nsComment\" content.');\n }\n // IA5STRING opaque comment\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);\n } else if(e.name === 'subjectKeyIdentifier' && options.cert) {\n var ski = options.cert.generateSubjectKeyIdentifier();\n e.subjectKeyIdentifier = ski.toHex();\n // OCTETSTRING w/digest\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());\n } else if(e.name === 'authorityKeyIdentifier' && options.cert) {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n if(e.keyIdentifier) {\n var keyIdentifier = (e.keyIdentifier === true ?\n options.cert.generateSubjectKeyIdentifier().getBytes() :\n e.keyIdentifier);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));\n }\n\n if(e.authorityCertIssuer) {\n var authorityCertIssuer = [\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [\n _dnToAsn1(e.authorityCertIssuer === true ?\n options.cert.issuer : e.authorityCertIssuer)\n ])\n ];\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));\n }\n\n if(e.serialNumber) {\n var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?\n options.cert.serialNumber : e.serialNumber);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));\n }\n } else if(e.name === 'cRLDistributionPoints') {\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n // Create sub SEQUENCE of DistributionPointName\n var subSeq = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // Create fullName CHOICE\n var fullNameGeneralNames = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n fullNameGeneralNames.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n\n // Add to the parent SEQUENCE\n subSeq.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));\n seq.push(subSeq);\n }\n\n // ensure value has been defined by now\n if(typeof e.value === 'undefined') {\n var error = new Error('Extension value not specified.');\n error.extension = e;\n throw error;\n }\n\n return e;\n}\n\n/**\n * Convert signature parameters object to ASN.1\n *\n * @param {String} oid Signature algorithm OID\n * @param params The signature parametrs object\n * @return ASN.1 object representing signature parameters\n */\nfunction _signatureParametersToAsn1(oid, params) {\n switch(oid) {\n case oids['RSASSA-PSS']:\n var parts = [];\n\n if(params.hash.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]));\n }\n\n if(params.mgf.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ])\n ]));\n }\n\n if(params.saltLength !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(params.saltLength).getBytes())\n ]));\n }\n\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);\n\n default:\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');\n }\n}\n\n/**\n * Converts a certification request's attributes to an ASN.1 set of\n * CRIAttributes.\n *\n * @param csr certification request.\n *\n * @return the ASN.1 set of CRIAttributes.\n */\nfunction _CRIAttributesToAsn1(csr) {\n // create an empty context-specific container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // no attributes, return empty container\n if(csr.attributes.length === 0) {\n return rval;\n }\n\n // each attribute has a sequence with a type and a set of values\n var attrs = csr.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.UTF8;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n }\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n var valueConstructed = false;\n if('valueConstructed' in attr) {\n valueConstructed = attr.valueConstructed;\n }\n // FIXME: handle more encodings\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n asn1.create(\n asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)\n ])\n ]);\n rval.value.push(seq);\n }\n\n return rval;\n}\n\nvar jan_1_1950 = new Date('1950-01-01T00:00:00Z');\nvar jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n\n/**\n * Converts a Date object to ASN.1\n * Handles the different format before and after 1st January 2050\n *\n * @param date date object.\n *\n * @return the ASN.1 object representing the date.\n */\nfunction _dateToAsn1(date) {\n if(date >= jan_1_1950 && date < jan_1_2050) {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n}\n\n/**\n * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.\n *\n * @param cert the certificate.\n *\n * @return the asn1 TBSCertificate.\n */\npki.getTBSCertificate = function(cert) {\n // TBSCertificate\n var notBefore = _dateToAsn1(cert.validity.notBefore);\n var notAfter = _dateToAsn1(cert.validity.notAfter);\n var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // integer\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(cert.version).getBytes())\n ]),\n // serialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(cert.serialNumber)),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(\n cert.siginfo.algorithmOid, cert.siginfo.parameters)\n ]),\n // issuer\n _dnToAsn1(cert.issuer),\n // validity\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n notBefore,\n notAfter\n ]),\n // subject\n _dnToAsn1(cert.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(cert.publicKey)\n ]);\n\n if(cert.issuer.uniqueId) {\n // issuerUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.issuer.uniqueId\n )\n ])\n );\n }\n if(cert.subject.uniqueId) {\n // subjectUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.subject.uniqueId\n )\n ])\n );\n }\n\n if(cert.extensions.length > 0) {\n // extensions (optional)\n tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));\n }\n\n return tbs;\n};\n\n/**\n * Gets the ASN.1 CertificationRequestInfo part of a\n * PKCS#10 CertificationRequest.\n *\n * @param csr the certification request.\n *\n * @return the asn1 CertificationRequestInfo.\n */\npki.getCertificationRequestInfo = function(csr) {\n // CertificationRequestInfo\n var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(csr.version).getBytes()),\n // subject\n _dnToAsn1(csr.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(csr.publicKey),\n // attributes\n _CRIAttributesToAsn1(csr)\n ]);\n\n return cri;\n};\n\n/**\n * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.\n *\n * @param dn the DistinguishedName.\n *\n * @return the asn1 representation of a DistinguishedName.\n */\npki.distinguishedNameToAsn1 = function(dn) {\n return _dnToAsn1(dn);\n};\n\n/**\n * Converts an X.509v3 RSA certificate to an ASN.1 object.\n *\n * @param cert the certificate.\n *\n * @return the asn1 representation of an X.509v3 RSA certificate.\n */\npki.certificateToAsn1 = function(cert) {\n // prefer cached TBSCertificate over generating one\n var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // TBSCertificate\n tbsCertificate,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)\n ]),\n // SignatureValue\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + cert.signature)\n ]);\n};\n\n/**\n * Converts X.509v3 certificate extensions to ASN.1.\n *\n * @param exts the extensions to convert.\n *\n * @return the extensions in ASN.1 format.\n */\npki.certificateExtensionsToAsn1 = function(exts) {\n // create top-level extension container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);\n\n // create extension sequence (stores a sequence for each extension)\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n rval.value.push(seq);\n\n for(var i = 0; i < exts.length; ++i) {\n seq.value.push(pki.certificateExtensionToAsn1(exts[i]));\n }\n\n return rval;\n};\n\n/**\n * Converts a single certificate extension to ASN.1.\n *\n * @param ext the extension to convert.\n *\n * @return the extension in ASN.1 format.\n */\npki.certificateExtensionToAsn1 = function(ext) {\n // create a sequence for each extension\n var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // extnID (OID)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ext.id).getBytes()));\n\n // critical defaults to false\n if(ext.critical) {\n // critical BOOLEAN DEFAULT FALSE\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n\n var value = ext.value;\n if(typeof ext.value !== 'string') {\n // value is asn.1\n value = asn1.toDer(value).getBytes();\n }\n\n // extnValue (OCTET STRING)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));\n\n return extseq;\n};\n\n/**\n * Converts a PKCS#10 certification request to an ASN.1 object.\n *\n * @param csr the certification request.\n *\n * @return the asn1 representation of a certification request.\n */\npki.certificationRequestToAsn1 = function(csr) {\n // prefer cached CertificationRequestInfo over generating one\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // CertificationRequestInfo\n cri,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(csr.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)\n ]),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + csr.signature)\n ]);\n};\n\n/**\n * Creates a CA store.\n *\n * @param certs an optional array of certificate objects or PEM-formatted\n * certificate strings to add to the CA store.\n *\n * @return the CA store.\n */\npki.createCaStore = function(certs) {\n // create CA store\n var caStore = {\n // stored certificates\n certs: {}\n };\n\n /**\n * Gets the certificate that issued the passed certificate or its\n * 'parent'.\n *\n * @param cert the certificate to get the parent for.\n *\n * @return the parent certificate or null if none was found.\n */\n caStore.getIssuer = function(cert) {\n var rval = getBySubject(cert.issuer);\n\n // see if there are multiple matches\n /*if(forge.util.isArray(rval)) {\n // TODO: resolve multiple matches by checking\n // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.\n // FIXME: or alternatively do authority key mapping\n // if possible (X.509v1 certs can't work?)\n throw new Error('Resolving multiple issuer matches not implemented yet.');\n }*/\n\n return rval;\n };\n\n /**\n * Adds a trusted certificate to the store.\n *\n * @param cert the certificate to add as a trusted certificate (either a\n * pki.certificate object or a PEM-formatted certificate).\n */\n caStore.addCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n ensureSubjectHasHash(cert.subject);\n\n if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store\n if(cert.subject.hash in caStore.certs) {\n // subject hash already exists, append to array\n var tmp = caStore.certs[cert.subject.hash];\n if(!forge.util.isArray(tmp)) {\n tmp = [tmp];\n }\n tmp.push(cert);\n caStore.certs[cert.subject.hash] = tmp;\n } else {\n caStore.certs[cert.subject.hash] = cert;\n }\n }\n };\n\n /**\n * Checks to see if the given certificate is in the store.\n *\n * @param cert the certificate to check (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return true if the certificate is in the store, false if not.\n */\n caStore.hasCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n var match = getBySubject(cert.subject);\n if(!match) {\n return false;\n }\n if(!forge.util.isArray(match)) {\n match = [match];\n }\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n return true;\n }\n }\n return false;\n };\n\n /**\n * Lists all of the certificates kept in the store.\n *\n * @return an array of all of the pki.certificate objects in the store.\n */\n caStore.listAllCertificates = function() {\n var certList = [];\n\n for(var hash in caStore.certs) {\n if(caStore.certs.hasOwnProperty(hash)) {\n var value = caStore.certs[hash];\n if(!forge.util.isArray(value)) {\n certList.push(value);\n } else {\n for(var i = 0; i < value.length; ++i) {\n certList.push(value[i]);\n }\n }\n }\n }\n\n return certList;\n };\n\n /**\n * Removes a certificate from the store.\n *\n * @param cert the certificate to remove (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return the certificate that was removed or null if the certificate\n * wasn't in store.\n */\n caStore.removeCertificate = function(cert) {\n var result;\n\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n ensureSubjectHasHash(cert.subject);\n if(!caStore.hasCertificate(cert)) {\n return null;\n }\n\n var match = getBySubject(cert.subject);\n\n if(!forge.util.isArray(match)) {\n result = caStore.certs[cert.subject.hash];\n delete caStore.certs[cert.subject.hash];\n return result;\n }\n\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n result = match[i];\n match.splice(i, 1);\n }\n }\n if(match.length === 0) {\n delete caStore.certs[cert.subject.hash];\n }\n\n return result;\n };\n\n function getBySubject(subject) {\n ensureSubjectHasHash(subject);\n return caStore.certs[subject.hash] || null;\n }\n\n function ensureSubjectHasHash(subject) {\n // produce subject hash if it doesn't exist\n if(!subject.hash) {\n var md = forge.md.sha1.create();\n subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);\n subject.hash = md.digest().toHex();\n }\n }\n\n // auto-add passed in certs\n if(certs) {\n // parse PEM-formatted certificates as necessary\n for(var i = 0; i < certs.length; ++i) {\n var cert = certs[i];\n caStore.addCertificate(cert);\n }\n }\n\n return caStore;\n};\n\n/**\n * Certificate verification errors, based on TLS.\n */\npki.certificateError = {\n bad_certificate: 'forge.pki.BadCertificate',\n unsupported_certificate: 'forge.pki.UnsupportedCertificate',\n certificate_revoked: 'forge.pki.CertificateRevoked',\n certificate_expired: 'forge.pki.CertificateExpired',\n certificate_unknown: 'forge.pki.CertificateUnknown',\n unknown_ca: 'forge.pki.UnknownCertificateAuthority'\n};\n\n/**\n * Verifies a certificate chain against the given Certificate Authority store\n * with an optional custom verify callback.\n *\n * @param caStore a certificate store to verify against.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end (an array of certificates).\n * @param options a callback to be called for every certificate in the chain or\n * an object with:\n * verify a callback to be called for every certificate in the\n * chain\n * validityCheckDate the date against which the certificate\n * validity period should be checked. Pass null to not check\n * the validity period. By default, the current date is used.\n *\n * The verify callback has the following signature:\n *\n * verified - Set to true if certificate was verified, otherwise the\n * pki.certificateError for why the certificate failed.\n * depth - The current index in the chain, where 0 is the end point's cert.\n * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous\n * end point.\n *\n * The function returns true on success and on failure either the appropriate\n * pki.certificateError or an object with 'error' set to the appropriate\n * pki.certificateError and 'message' set to a custom error message.\n *\n * @return true if successful, error thrown if not.\n */\npki.verifyCertificateChain = function(caStore, chain, options) {\n /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate\n Section 6: Certification Path Validation\n See inline parentheticals related to this particular implementation.\n\n The primary goal of path validation is to verify the binding between\n a subject distinguished name or a subject alternative name and subject\n public key, as represented in the end entity certificate, based on the\n public key of the trust anchor. This requires obtaining a sequence of\n certificates that support that binding. That sequence should be provided\n in the passed 'chain'. The trust anchor should be in the given CA\n store. The 'end entity' certificate is the certificate provided by the\n end point (typically a server) and is the first in the chain.\n\n To meet this goal, the path validation process verifies, among other\n things, that a prospective certification path (a sequence of n\n certificates or a 'chain') satisfies the following conditions:\n\n (a) for all x in {1, ..., n-1}, the subject of certificate x is\n the issuer of certificate x+1;\n\n (b) certificate 1 is issued by the trust anchor;\n\n (c) certificate n is the certificate to be validated; and\n\n (d) for all x in {1, ..., n}, the certificate was valid at the\n time in question.\n\n Note that here 'n' is index 0 in the chain and 1 is the last certificate\n in the chain and it must be signed by a certificate in the connection's\n CA store.\n\n The path validation process also determines the set of certificate\n policies that are valid for this path, based on the certificate policies\n extension, policy mapping extension, policy constraints extension, and\n inhibit any-policy extension.\n\n Note: Policy mapping extension not supported (Not Required).\n\n Note: If the certificate has an unsupported critical extension, then it\n must be rejected.\n\n Note: A certificate is self-issued if the DNs that appear in the subject\n and issuer fields are identical and are not empty.\n\n The path validation algorithm assumes the following seven inputs are\n provided to the path processing logic. What this specific implementation\n will use is provided parenthetically:\n\n (a) a prospective certification path of length n (the 'chain')\n (b) the current date/time: ('now').\n (c) user-initial-policy-set: A set of certificate policy identifiers\n naming the policies that are acceptable to the certificate user.\n The user-initial-policy-set contains the special value any-policy\n if the user is not concerned about certificate policy\n (Not implemented. Any policy is accepted).\n (d) trust anchor information, describing a CA that serves as a trust\n anchor for the certification path. The trust anchor information\n includes:\n\n (1) the trusted issuer name,\n (2) the trusted public key algorithm,\n (3) the trusted public key, and\n (4) optionally, the trusted public key parameters associated\n with the public key.\n\n (Trust anchors are provided via certificates in the CA store).\n\n The trust anchor information may be provided to the path processing\n procedure in the form of a self-signed certificate. The trusted anchor\n information is trusted because it was delivered to the path processing\n procedure by some trustworthy out-of-band procedure. If the trusted\n public key algorithm requires parameters, then the parameters are\n provided along with the trusted public key (No parameters used in this\n implementation).\n\n (e) initial-policy-mapping-inhibit, which indicates if policy mapping is\n allowed in the certification path.\n (Not implemented, no policy checking)\n\n (f) initial-explicit-policy, which indicates if the path must be valid\n for at least one of the certificate policies in the user-initial-\n policy-set.\n (Not implemented, no policy checking)\n\n (g) initial-any-policy-inhibit, which indicates whether the\n anyPolicy OID should be processed if it is included in a\n certificate.\n (Not implemented, so any policy is valid provided that it is\n not marked as critical) */\n\n /* Basic Path Processing:\n\n For each certificate in the 'chain', the following is checked:\n\n 1. The certificate validity period includes the current time.\n 2. The certificate was signed by its parent (where the parent is either\n the next in the chain or from the CA store). Allow processing to\n continue to the next step if no parent is found but the certificate is\n in the CA store.\n 3. TODO: The certificate has not been revoked.\n 4. The certificate issuer name matches the parent's subject name.\n 5. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is within one of the permitted subtrees of X.500 distinguished names\n and that each of the alternative names in the subjectAltName extension\n (critical or non-critical) is within one of the permitted subtrees for\n that name type.\n 6. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is not within one of the excluded subtrees for X.500 distinguished\n names and none of the subjectAltName extension names are excluded for\n that name type.\n 7. The other steps in the algorithm for basic path processing involve\n handling the policy extension which is not presently supported in this\n implementation. Instead, if a critical policy extension is found, the\n certificate is rejected as not supported.\n 8. If the certificate is not the first or if its the only certificate in\n the chain (having no parent from the CA store or is self-signed) and it\n has a critical key usage extension, verify that the keyCertSign bit is\n set. If the key usage extension exists, verify that the basic\n constraints extension exists. If the basic constraints extension exists,\n verify that the cA flag is set. If pathLenConstraint is set, ensure that\n the number of certificates that precede in the chain (come earlier\n in the chain as implemented below), excluding the very first in the\n chain (typically the end-entity one), isn't greater than the\n pathLenConstraint. This constraint limits the number of intermediate\n CAs that may appear below a CA before only end-entity certificates\n may be issued. */\n\n // if a verify callback is passed as the third parameter, package it within\n // the options object. This is to support a legacy function signature that\n // expected the verify callback as the third parameter.\n if(typeof options === 'function') {\n options = {verify: options};\n }\n options = options || {};\n\n // copy cert chain references to another array to protect against changes\n // in verify callback\n chain = chain.slice(0);\n var certs = chain.slice(0);\n\n var validityCheckDate = options.validityCheckDate;\n // if no validityCheckDate is specified, default to the current date. Make\n // sure to maintain the value null because it indicates that the validity\n // period should not be checked.\n if(typeof validityCheckDate === 'undefined') {\n validityCheckDate = new Date();\n }\n\n // verify each cert in the chain using its parent, where the parent\n // is either the next in the chain or from the CA store\n var first = true;\n var error = null;\n var depth = 0;\n do {\n var cert = chain.shift();\n var parent = null;\n var selfSigned = false;\n\n if(validityCheckDate) {\n // 1. check valid time\n if(validityCheckDate < cert.validity.notBefore ||\n validityCheckDate > cert.validity.notAfter) {\n error = {\n message: 'Certificate is not valid yet or has expired.',\n error: pki.certificateError.certificate_expired,\n notBefore: cert.validity.notBefore,\n notAfter: cert.validity.notAfter,\n // TODO: we might want to reconsider renaming 'now' to\n // 'validityCheckDate' should this API be changed in the future.\n now: validityCheckDate\n };\n }\n }\n\n // 2. verify with parent from chain or CA store\n if(error === null) {\n parent = chain[0] || caStore.getIssuer(cert);\n if(parent === null) {\n // check for self-signed cert\n if(cert.isIssuer(cert)) {\n selfSigned = true;\n parent = cert;\n }\n }\n\n if(parent) {\n // FIXME: current CA store implementation might have multiple\n // certificates where the issuer can't be determined from the\n // certificate (happens rarely with, eg: old certificates) so normalize\n // by always putting parents into an array\n // TODO: there's may be an extreme degenerate case currently uncovered\n // where an old intermediate certificate seems to have a matching parent\n // but none of the parents actually verify ... but the intermediate\n // is in the CA and it should pass this check; needs investigation\n var parents = parent;\n if(!forge.util.isArray(parents)) {\n parents = [parents];\n }\n\n // try to verify with each possible parent (typically only one)\n var verified = false;\n while(!verified && parents.length > 0) {\n parent = parents.shift();\n try {\n verified = parent.verify(cert);\n } catch(ex) {\n // failure to verify, don't care why, try next one\n }\n }\n\n if(!verified) {\n error = {\n message: 'Certificate signature is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n\n if(error === null && (!parent || selfSigned) &&\n !caStore.hasCertificate(cert)) {\n // no parent issuer and certificate itself is not trusted\n error = {\n message: 'Certificate is not trusted.',\n error: pki.certificateError.unknown_ca\n };\n }\n }\n\n // TODO: 3. check revoked\n\n // 4. check for matching issuer/subject\n if(error === null && parent && !cert.isIssuer(parent)) {\n // parent is not issuer\n error = {\n message: 'Certificate issuer is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // 5. TODO: check names with permitted names tree\n\n // 6. TODO: check names against excluded names tree\n\n // 7. check for unsupported critical extensions\n if(error === null) {\n // supported extensions\n var se = {\n keyUsage: true,\n basicConstraints: true\n };\n for(var i = 0; error === null && i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.critical && !(ext.name in se)) {\n error = {\n message:\n 'Certificate has an unsupported critical extension.',\n error: pki.certificateError.unsupported_certificate\n };\n }\n }\n }\n\n // 8. check for CA if cert is not first or is the only certificate\n // remaining in chain with no parent or is self-signed\n if(error === null &&\n (!first || (chain.length === 0 && (!parent || selfSigned)))) {\n // first check keyUsage extension and then basic constraints\n var bcExt = cert.getExtension('basicConstraints');\n var keyUsageExt = cert.getExtension('keyUsage');\n if(keyUsageExt !== null) {\n // keyCertSign must be true and there must be a basic\n // constraints extension\n if(!keyUsageExt.keyCertSign || bcExt === null) {\n // bad certificate\n error = {\n message:\n 'Certificate keyUsage or basicConstraints conflict ' +\n 'or indicate that the certificate is not a CA. ' +\n 'If the certificate is the only one in the chain or ' +\n 'isn\\'t the first then the certificate must be a ' +\n 'valid CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n // basic constraints cA flag must be set\n if(error === null && bcExt !== null && !bcExt.cA) {\n // bad certificate\n error = {\n message:\n 'Certificate basicConstraints indicates the certificate ' +\n 'is not a CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n // if error is not null and keyUsage is available, then we know it\n // has keyCertSign and there is a basic constraints extension too,\n // which means we can check pathLenConstraint (if it exists)\n if(error === null && keyUsageExt !== null &&\n 'pathLenConstraint' in bcExt) {\n // pathLen is the maximum # of intermediate CA certs that can be\n // found between the current certificate and the end-entity (depth 0)\n // certificate; this number does not include the end-entity (depth 0,\n // last in the chain) even if it happens to be a CA certificate itself\n var pathLen = depth - 1;\n if(pathLen > bcExt.pathLenConstraint) {\n // pathLenConstraint violated, bad certificate\n error = {\n message:\n 'Certificate basicConstraints pathLenConstraint violated.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n }\n\n // call application callback\n var vfd = (error === null) ? true : error.error;\n var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;\n if(ret === true) {\n // clear any set error\n error = null;\n } else {\n // if passed basic tests, set default message and alert\n if(vfd === true) {\n error = {\n message: 'The application rejected the certificate.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // check for custom error info\n if(ret || ret === 0) {\n // set custom message and error\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.error) {\n error.error = ret.error;\n }\n } else if(typeof ret === 'string') {\n // set custom error\n error.error = ret;\n }\n }\n\n // throw error\n throw error;\n }\n\n // no longer first cert in chain\n first = false;\n ++depth;\n } while(chain.length > 0);\n\n return true;\n};\n","/**\n * Javascript implementation of PKCS#12.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * The ASN.1 representation of PKCS#12 is as follows\n * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details)\n *\n * PFX ::= SEQUENCE {\n * version INTEGER {v3(3)}(v3,...),\n * authSafe ContentInfo,\n * macData MacData OPTIONAL\n * }\n *\n * MacData ::= SEQUENCE {\n * mac DigestInfo,\n * macSalt OCTET STRING,\n * iterations INTEGER DEFAULT 1\n * }\n * Note: The iterations default is for historical reasons and its use is\n * deprecated. A higher value, like 1024, is recommended.\n *\n * DigestInfo is defined in PKCS#7 as follows:\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of SHA1 there is none.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * Digest ::= OCTET STRING\n *\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * AuthenticatedSafe ::= SEQUENCE OF ContentInfo\n * -- Data if unencrypted\n * -- EncryptedData if password-encrypted\n * -- EnvelopedData if public key-encrypted\n *\n *\n * SafeContents ::= SEQUENCE OF SafeBag\n *\n * SafeBag ::= SEQUENCE {\n * bagId BAG-TYPE.&id ({PKCS12BagSet})\n * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),\n * bagAttributes SET OF PKCS12Attribute OPTIONAL\n * }\n *\n * PKCS12Attribute ::= SEQUENCE {\n * attrId ATTRIBUTE.&id ({PKCS12AttrSet}),\n * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId})\n * } -- This type is compatible with the X.500 type 'Attribute'\n *\n * PKCS12AttrSet ATTRIBUTE ::= {\n * friendlyName | -- from PKCS #9\n * localKeyId, -- from PKCS #9\n * ... -- Other attributes are allowed\n * }\n *\n * CertBag ::= SEQUENCE {\n * certId BAG-TYPE.&id ({CertTypes}),\n * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId})\n * }\n *\n * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}}\n * -- DER-encoded X.509 certificate stored in OCTET STRING\n *\n * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}}\n * -- Base64-encoded SDSI certificate stored in IA5String\n *\n * CertTypes BAG-TYPE ::= {\n * x509Certificate |\n * sdsiCertificate,\n * ... -- For future extensions\n * }\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./hmac');\nrequire('./oids');\nrequire('./pkcs7asn1');\nrequire('./pbe');\nrequire('./random');\nrequire('./rsa');\nrequire('./sha1');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for asn.1 & PKI API\nvar asn1 = forge.asn1;\nvar pki = forge.pki;\n\n// shortcut for PKCS#12 API\nvar p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {};\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // a ContentInfo\n constructed: true,\n value: [{\n name: 'ContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n captureAsn1: 'content'\n }]\n};\n\nvar pfxValidator = {\n name: 'PFX',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PFX.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n },\n contentInfoValidator, {\n name: 'PFX.macData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'mac',\n value: [{\n name: 'PFX.macData.mac',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // DigestInfo\n constructed: true,\n value: [{\n name: 'PFX.macData.mac.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier\n constructed: true,\n value: [{\n name: 'PFX.macData.mac.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'macAlgorithm'\n }, {\n name: 'PFX.macData.mac.digestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'macAlgorithmParameters'\n }]\n }, {\n name: 'PFX.macData.mac.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'macDigest'\n }]\n }, {\n name: 'PFX.macData.macSalt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'macSalt'\n }, {\n name: 'PFX.macData.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'macIterations'\n }]\n }]\n};\n\nvar safeBagValidator = {\n name: 'SafeBag',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SafeBag.bagId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'bagId'\n }, {\n name: 'SafeBag.bagValue',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n captureAsn1: 'bagValue'\n }, {\n name: 'SafeBag.bagAttributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n optional: true,\n capture: 'bagAttributes'\n }]\n};\n\nvar attributeValidator = {\n name: 'Attribute',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Attribute.attrId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'oid'\n }, {\n name: 'Attribute.attrValues',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n capture: 'values'\n }]\n};\n\nvar certBagValidator = {\n name: 'CertBag',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertBag.certId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certId'\n }, {\n name: 'CertBag.certValue',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n /* So far we only support X.509 certificates (which are wrapped in\n an OCTET STRING, hence hard code that here). */\n value: [{\n name: 'CertBag.certValue[0]',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.OCTETSTRING,\n constructed: false,\n capture: 'cert'\n }]\n }]\n};\n\n/**\n * Search SafeContents structure for bags with matching attributes.\n *\n * The search can optionally be narrowed by a certain bag type.\n *\n * @param safeContents the SafeContents structure to search in.\n * @param attrName the name of the attribute to compare against.\n * @param attrValue the attribute value to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of matching bags.\n */\nfunction _getBagsByAttribute(safeContents, attrName, attrValue, bagType) {\n var result = [];\n\n for(var i = 0; i < safeContents.length; i++) {\n for(var j = 0; j < safeContents[i].safeBags.length; j++) {\n var bag = safeContents[i].safeBags[j];\n if(bagType !== undefined && bag.type !== bagType) {\n continue;\n }\n // only filter by bag type, no attribute specified\n if(attrName === null) {\n result.push(bag);\n continue;\n }\n if(bag.attributes[attrName] !== undefined &&\n bag.attributes[attrName].indexOf(attrValue) >= 0) {\n result.push(bag);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object.\n *\n * @param obj The PKCS#12 PFX in ASN.1 notation.\n * @param strict true to use strict DER decoding, false not to (default: true).\n * @param {String} password Password to decrypt with (optional).\n *\n * @return PKCS#12 PFX object.\n */\np12.pkcs12FromAsn1 = function(obj, strict, password) {\n // handle args\n if(typeof strict === 'string') {\n password = strict;\n strict = true;\n } else if(strict === undefined) {\n strict = true;\n }\n\n // validate PFX and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, pfxValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 PFX. ' +\n 'ASN.1 object is not an PKCS#12 PFX.');\n error.errors = error;\n throw error;\n }\n\n var pfx = {\n version: capture.version.charCodeAt(0),\n safeContents: [],\n\n /**\n * Gets bags with matching attributes.\n *\n * @param filter the attributes to filter by:\n * [localKeyId] the localKeyId to search for.\n * [localKeyIdHex] the localKeyId in hex to search for.\n * [friendlyName] the friendly name to search for.\n * [bagType] bag type to narrow each attribute search by.\n *\n * @return a map of attribute type to an array of matching bags or, if no\n * attribute was given but a bag type, the map key will be the\n * bag type.\n */\n getBags: function(filter) {\n var rval = {};\n\n var localKeyId;\n if('localKeyId' in filter) {\n localKeyId = filter.localKeyId;\n } else if('localKeyIdHex' in filter) {\n localKeyId = forge.util.hexToBytes(filter.localKeyIdHex);\n }\n\n // filter on bagType only\n if(localKeyId === undefined && !('friendlyName' in filter) &&\n 'bagType' in filter) {\n rval[filter.bagType] = _getBagsByAttribute(\n pfx.safeContents, null, null, filter.bagType);\n }\n\n if(localKeyId !== undefined) {\n rval.localKeyId = _getBagsByAttribute(\n pfx.safeContents, 'localKeyId',\n localKeyId, filter.bagType);\n }\n if('friendlyName' in filter) {\n rval.friendlyName = _getBagsByAttribute(\n pfx.safeContents, 'friendlyName',\n filter.friendlyName, filter.bagType);\n }\n\n return rval;\n },\n\n /**\n * DEPRECATED: use getBags() instead.\n *\n * Get bags with matching friendlyName attribute.\n *\n * @param friendlyName the friendly name to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of bags with matching friendlyName attribute.\n */\n getBagsByFriendlyName: function(friendlyName, bagType) {\n return _getBagsByAttribute(\n pfx.safeContents, 'friendlyName', friendlyName, bagType);\n },\n\n /**\n * DEPRECATED: use getBags() instead.\n *\n * Get bags with matching localKeyId attribute.\n *\n * @param localKeyId the localKeyId to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of bags with matching localKeyId attribute.\n */\n getBagsByLocalKeyId: function(localKeyId, bagType) {\n return _getBagsByAttribute(\n pfx.safeContents, 'localKeyId', localKeyId, bagType);\n }\n };\n\n if(capture.version.charCodeAt(0) !== 3) {\n var error = new Error('PKCS#12 PFX of version other than 3 not supported.');\n error.version = capture.version.charCodeAt(0);\n throw error;\n }\n\n if(asn1.derToOid(capture.contentType) !== pki.oids.data) {\n var error = new Error('Only PKCS#12 PFX in password integrity mode supported.');\n error.oid = asn1.derToOid(capture.contentType);\n throw error;\n }\n\n var data = capture.content.value[0];\n if(data.tagClass !== asn1.Class.UNIVERSAL ||\n data.type !== asn1.Type.OCTETSTRING) {\n throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.');\n }\n data = _decodePkcs7Data(data);\n\n // check for MAC\n if(capture.mac) {\n var md = null;\n var macKeyBytes = 0;\n var macAlgorithm = asn1.derToOid(capture.macAlgorithm);\n switch(macAlgorithm) {\n case pki.oids.sha1:\n md = forge.md.sha1.create();\n macKeyBytes = 20;\n break;\n case pki.oids.sha256:\n md = forge.md.sha256.create();\n macKeyBytes = 32;\n break;\n case pki.oids.sha384:\n md = forge.md.sha384.create();\n macKeyBytes = 48;\n break;\n case pki.oids.sha512:\n md = forge.md.sha512.create();\n macKeyBytes = 64;\n break;\n case pki.oids.md5:\n md = forge.md.md5.create();\n macKeyBytes = 16;\n break;\n }\n if(md === null) {\n throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm);\n }\n\n // verify MAC (iterations default to 1)\n var macSalt = new forge.util.ByteBuffer(capture.macSalt);\n var macIterations = (('macIterations' in capture) ?\n parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1);\n var macKey = p12.generateKey(\n password, macSalt, 3, macIterations, macKeyBytes, md);\n var mac = forge.hmac.create();\n mac.start(md, macKey);\n mac.update(data.value);\n var macValue = mac.getMac();\n if(macValue.getBytes() !== capture.macDigest) {\n throw new Error('PKCS#12 MAC could not be verified. Invalid password?');\n }\n }\n\n _decodeAuthenticatedSafe(pfx, data.value, strict, password);\n return pfx;\n};\n\n/**\n * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines \"Data\" as an OCTET STRING,\n * but it is sometimes an OCTET STRING that is composed/constructed of chunks,\n * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This\n * function transforms this corner-case into the usual simple,\n * non-composed/constructed OCTET STRING.\n *\n * This function may be moved to ASN.1 at some point to better deal with\n * more BER-encoding issues, should they arise.\n *\n * @param data the ASN.1 Data object to transform.\n */\nfunction _decodePkcs7Data(data) {\n // handle special case of \"chunked\" data content: an octet string composed\n // of other octet strings\n if(data.composed || data.constructed) {\n var value = forge.util.createBuffer();\n for(var i = 0; i < data.value.length; ++i) {\n value.putBytes(data.value[i].value);\n }\n data.composed = data.constructed = false;\n data.value = value.getBytes();\n }\n return data;\n}\n\n/**\n * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object.\n *\n * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo.\n *\n * @param pfx The PKCS#12 PFX object to fill.\n * @param {String} authSafe BER-encoded AuthenticatedSafe.\n * @param strict true to use strict DER decoding, false not to.\n * @param {String} password Password to decrypt with (optional).\n */\nfunction _decodeAuthenticatedSafe(pfx, authSafe, strict, password) {\n authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */\n\n if(authSafe.tagClass !== asn1.Class.UNIVERSAL ||\n authSafe.type !== asn1.Type.SEQUENCE ||\n authSafe.constructed !== true) {\n throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' +\n 'SEQUENCE OF ContentInfo');\n }\n\n for(var i = 0; i < authSafe.value.length; i++) {\n var contentInfo = authSafe.value[i];\n\n // validate contentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var obj = {\n encrypted: false\n };\n var safeContents = null;\n var data = capture.content.value[0];\n switch(asn1.derToOid(capture.contentType)) {\n case pki.oids.data:\n if(data.tagClass !== asn1.Class.UNIVERSAL ||\n data.type !== asn1.Type.OCTETSTRING) {\n throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.');\n }\n safeContents = _decodePkcs7Data(data).value;\n break;\n case pki.oids.encryptedData:\n safeContents = _decryptSafeContents(data, password);\n obj.encrypted = true;\n break;\n default:\n var error = new Error('Unsupported PKCS#12 contentType.');\n error.contentType = asn1.derToOid(capture.contentType);\n throw error;\n }\n\n obj.safeBags = _decodeSafeContents(safeContents, strict, password);\n pfx.safeContents.push(obj);\n }\n}\n\n/**\n * Decrypt PKCS#7 EncryptedData structure.\n *\n * @param data ASN.1 encoded EncryptedContentInfo object.\n * @param password The user-provided password.\n *\n * @return The decrypted SafeContents (ASN.1 object).\n */\nfunction _decryptSafeContents(data, password) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(\n data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) {\n var error = new Error('Cannot read EncryptedContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var oid = asn1.derToOid(capture.contentType);\n if(oid !== pki.oids.data) {\n var error = new Error(\n 'PKCS#12 EncryptedContentInfo ContentType is not Data.');\n error.oid = oid;\n throw error;\n }\n\n // get cipher\n oid = asn1.derToOid(capture.encAlgorithm);\n var cipher = pki.pbe.getCipher(oid, capture.encParameter, password);\n\n // get encrypted data\n var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);\n var encrypted = forge.util.createBuffer(encryptedContentAsn1.value);\n\n cipher.update(encrypted);\n if(!cipher.finish()) {\n throw new Error('Failed to decrypt PKCS#12 SafeContents.');\n }\n\n return cipher.output.getBytes();\n}\n\n/**\n * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects.\n *\n * The safeContents is a BER-encoded SEQUENCE OF SafeBag.\n *\n * @param {String} safeContents BER-encoded safeContents.\n * @param strict true to use strict DER decoding, false not to.\n * @param {String} password Password to decrypt with (optional).\n *\n * @return {Array} Array of Bag objects.\n */\nfunction _decodeSafeContents(safeContents, strict, password) {\n // if strict and no safe contents, return empty safes\n if(!strict && safeContents.length === 0) {\n return [];\n }\n\n // actually it's BER-encoded\n safeContents = asn1.fromDer(safeContents, strict);\n\n if(safeContents.tagClass !== asn1.Class.UNIVERSAL ||\n safeContents.type !== asn1.Type.SEQUENCE ||\n safeContents.constructed !== true) {\n throw new Error(\n 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.');\n }\n\n var res = [];\n for(var i = 0; i < safeContents.value.length; i++) {\n var safeBag = safeContents.value[i];\n\n // validate SafeBag and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) {\n var error = new Error('Cannot read SafeBag.');\n error.errors = errors;\n throw error;\n }\n\n /* Create bag object and push to result array. */\n var bag = {\n type: asn1.derToOid(capture.bagId),\n attributes: _decodeBagAttributes(capture.bagAttributes)\n };\n res.push(bag);\n\n var validator, decoder;\n var bagAsn1 = capture.bagValue.value[0];\n switch(bag.type) {\n case pki.oids.pkcs8ShroudedKeyBag:\n /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt.\n Afterwards we can handle it like a keyBag,\n which is a PrivateKeyInfo. */\n bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password);\n if(bagAsn1 === null) {\n throw new Error(\n 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?');\n }\n\n /* fall through */\n case pki.oids.keyBag:\n /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our\n PKI module, hence we don't have to do validation/capturing here,\n just pass what we already got. */\n try {\n bag.key = pki.privateKeyFromAsn1(bagAsn1);\n } catch(e) {\n // ignore unknown key type, pass asn1 value\n bag.key = null;\n bag.asn1 = bagAsn1;\n }\n continue; /* Nothing more to do. */\n\n case pki.oids.certBag:\n /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates.\n Therefore put the SafeBag content through another validator to\n capture the fields. Afterwards check & store the results. */\n validator = certBagValidator;\n decoder = function() {\n if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) {\n var error = new Error(\n 'Unsupported certificate type, only X.509 supported.');\n error.oid = asn1.derToOid(capture.certId);\n throw error;\n }\n\n // true=produce cert hash\n var certAsn1 = asn1.fromDer(capture.cert, strict);\n try {\n bag.cert = pki.certificateFromAsn1(certAsn1, true);\n } catch(e) {\n // ignore unknown cert type, pass asn1 value\n bag.cert = null;\n bag.asn1 = certAsn1;\n }\n };\n break;\n\n default:\n var error = new Error('Unsupported PKCS#12 SafeBag type.');\n error.oid = bag.type;\n throw error;\n }\n\n /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */\n if(validator !== undefined &&\n !asn1.validate(bagAsn1, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 ' + validator.name);\n error.errors = errors;\n throw error;\n }\n\n /* Call decoder function from above to store the results. */\n decoder();\n }\n\n return res;\n}\n\n/**\n * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object.\n *\n * @param attributes SET OF PKCS12Attribute (ASN.1 object).\n *\n * @return the decoded attributes.\n */\nfunction _decodeBagAttributes(attributes) {\n var decodedAttrs = {};\n\n if(attributes !== undefined) {\n for(var i = 0; i < attributes.length; ++i) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 BagAttribute.');\n error.errors = errors;\n throw error;\n }\n\n var oid = asn1.derToOid(capture.oid);\n if(pki.oids[oid] === undefined) {\n // unsupported attribute type, ignore.\n continue;\n }\n\n decodedAttrs[pki.oids[oid]] = [];\n for(var j = 0; j < capture.values.length; ++j) {\n decodedAttrs[pki.oids[oid]].push(capture.values[j].value);\n }\n }\n }\n\n return decodedAttrs;\n}\n\n/**\n * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a\n * password is provided then the private key will be encrypted.\n *\n * An entire certificate chain may also be included. To do this, pass\n * an array for the \"cert\" parameter where the first certificate is\n * the one that is paired with the private key and each subsequent one\n * verifies the previous one. The certificates may be in PEM format or\n * have been already parsed by Forge.\n *\n * @todo implement password-based-encryption for the whole package\n *\n * @param key the private key.\n * @param cert the certificate (may be an array of certificates in order\n * to specify a certificate chain).\n * @param password the password to use, null for none.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * useMac true to include a MAC, false not to, defaults to true.\n * localKeyId the local key ID to use, in hex.\n * friendlyName the friendly name to use.\n * generateLocalKeyId true to generate a random local key ID,\n * false not to, defaults to true.\n *\n * @return the PKCS#12 PFX ASN.1 object.\n */\np12.toPkcs12Asn1 = function(key, cert, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || options.encAlgorithm || 'aes128';\n if(!('useMac' in options)) {\n options.useMac = true;\n }\n if(!('localKeyId' in options)) {\n options.localKeyId = null;\n }\n if(!('generateLocalKeyId' in options)) {\n options.generateLocalKeyId = true;\n }\n\n var localKeyId = options.localKeyId;\n var bagAttrs;\n if(localKeyId !== null) {\n localKeyId = forge.util.hexToBytes(localKeyId);\n } else if(options.generateLocalKeyId) {\n // use SHA-1 of paired cert, if available\n if(cert) {\n var pairedCert = forge.util.isArray(cert) ? cert[0] : cert;\n if(typeof pairedCert === 'string') {\n pairedCert = pki.certificateFromPem(pairedCert);\n }\n var sha1 = forge.md.sha1.create();\n sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes());\n localKeyId = sha1.digest().getBytes();\n } else {\n // FIXME: consider using SHA-1 of public key (which can be generated\n // from private key components), see: cert.generateSubjectKeyIdentifier\n // generate random bytes\n localKeyId = forge.random.getBytes(20);\n }\n }\n\n var attrs = [];\n if(localKeyId !== null) {\n attrs.push(\n // localKeyID\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // attrId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.localKeyId).getBytes()),\n // attrValues\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n localKeyId)\n ])\n ]));\n }\n if('friendlyName' in options) {\n attrs.push(\n // friendlyName\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // attrId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.friendlyName).getBytes()),\n // attrValues\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false,\n options.friendlyName)\n ])\n ]));\n }\n\n if(attrs.length > 0) {\n bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs);\n }\n\n // collect contents for AuthenticatedSafe\n var contents = [];\n\n // create safe bag(s) for certificate chain\n var chain = [];\n if(cert !== null) {\n if(forge.util.isArray(cert)) {\n chain = cert;\n } else {\n chain = [cert];\n }\n }\n\n var certSafeBags = [];\n for(var i = 0; i < chain.length; ++i) {\n // convert cert from PEM as necessary\n cert = chain[i];\n if(typeof cert === 'string') {\n cert = pki.certificateFromPem(cert);\n }\n\n // SafeBag\n var certBagAttrs = (i === 0) ? bagAttrs : undefined;\n var certAsn1 = pki.certificateToAsn1(cert);\n var certSafeBag =\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.certBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // CertBag\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // certId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.x509Certificate).getBytes()),\n // certValue (x509Certificate)\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(certAsn1).getBytes())\n ])])]),\n // bagAttributes (OPTIONAL)\n certBagAttrs\n ]);\n certSafeBags.push(certSafeBag);\n }\n\n if(certSafeBags.length > 0) {\n // SafeContents\n var certSafeContents = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags);\n\n // ContentInfo\n var certCI =\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(certSafeContents).getBytes())\n ])\n ]);\n contents.push(certCI);\n }\n\n // create safe contents for private key\n var keyBag = null;\n if(key !== null) {\n // SafeBag\n var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));\n if(password === null) {\n // no encryption\n keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.keyBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // PrivateKeyInfo\n pkAsn1\n ]),\n // bagAttributes (OPTIONAL)\n bagAttrs\n ]);\n } else {\n // encrypted PrivateKeyInfo\n keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // EncryptedPrivateKeyInfo\n pki.encryptPrivateKeyInfo(pkAsn1, password, options)\n ]),\n // bagAttributes (OPTIONAL)\n bagAttrs\n ]);\n }\n\n // SafeContents\n var keySafeContents =\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]);\n\n // ContentInfo\n var keyCI =\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(keySafeContents).getBytes())\n ])\n ]);\n contents.push(keyCI);\n }\n\n // create AuthenticatedSafe by stringing together the contents\n var safe = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents);\n\n var macData;\n if(options.useMac) {\n // MacData\n var sha1 = forge.md.sha1.create();\n var macSalt = new forge.util.ByteBuffer(\n forge.random.getBytes(options.saltSize));\n var count = options.count;\n // 160-bit key\n var key = p12.generateKey(password, macSalt, 3, count, 20);\n var mac = forge.hmac.create();\n mac.start(sha1, key);\n mac.update(asn1.toDer(safe).getBytes());\n var macValue = mac.getMac();\n macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // mac DigestInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm = SHA-1\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.sha1).getBytes()),\n // parameters = Null\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // digest\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, macValue.getBytes())\n ]),\n // macSalt OCTET STRING\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()),\n // iterations INTEGER (XXX: Only support count < 65536)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(count).getBytes()\n )\n ]);\n }\n\n // PFX\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (3)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(3).getBytes()),\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(safe).getBytes())\n ])\n ]),\n macData\n ]);\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\np12.generateKey = forge.pbe.generatePkcs12Key;\n","/**\n * Javascript implementation of a basic Public Key Infrastructure, including\n * support for RSA public and private keys.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./oids');\nrequire('./pbe');\nrequire('./pem');\nrequire('./pbkdf2');\nrequire('./pkcs12');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead.\n *\n * Converts PEM-formatted data to DER.\n *\n * @param pem the PEM-formatted data.\n *\n * @return the DER-formatted data.\n */\npki.pemToDer = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PEM to DER; PEM is encrypted.');\n }\n return forge.util.createBuffer(msg.body);\n};\n\n/**\n * Converts an RSA private key from PEM format.\n *\n * @param pem the PEM-formatted private key.\n *\n * @return the private key.\n */\npki.privateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM ' +\n 'header type is not \"PRIVATE KEY\" or \"RSA PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert private key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.privateKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA private key to PEM format.\n *\n * @param key the private key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted private key.\n */\npki.privateKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PRIVATE KEY',\n body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PrivateKeyInfo to PEM format.\n *\n * @param pki the PrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted private key.\n */\npki.privateKeyInfoToPem = function(pki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'PRIVATE KEY',\n body: asn1.toDer(pki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n","/**\n * A Javascript implementation of Transport Layer Security (TLS).\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n *\n * The TLS Handshake Protocol involves the following steps:\n *\n * - Exchange hello messages to agree on algorithms, exchange random values,\n * and check for session resumption.\n *\n * - Exchange the necessary cryptographic parameters to allow the client and\n * server to agree on a premaster secret.\n *\n * - Exchange certificates and cryptographic information to allow the client\n * and server to authenticate themselves.\n *\n * - Generate a master secret from the premaster secret and exchanged random\n * values.\n *\n * - Provide security parameters to the record layer.\n *\n * - Allow the client and server to verify that their peer has calculated the\n * same security parameters and that the handshake occurred without tampering\n * by an attacker.\n *\n * Up to 4 different messages may be sent during a key exchange. The server\n * certificate, the server key exchange, the client certificate, and the\n * client key exchange.\n *\n * A typical handshake (from the client's perspective).\n *\n * 1. Client sends ClientHello.\n * 2. Client receives ServerHello.\n * 3. Client receives optional Certificate.\n * 4. Client receives optional ServerKeyExchange.\n * 5. Client receives ServerHelloDone.\n * 6. Client sends optional Certificate.\n * 7. Client sends ClientKeyExchange.\n * 8. Client sends optional CertificateVerify.\n * 9. Client sends ChangeCipherSpec.\n * 10. Client sends Finished.\n * 11. Client receives ChangeCipherSpec.\n * 12. Client receives Finished.\n * 13. Client sends/receives application data.\n *\n * To reuse an existing session:\n *\n * 1. Client sends ClientHello with session ID for reuse.\n * 2. Client receives ServerHello with same session ID if reusing.\n * 3. Client receives ChangeCipherSpec message if reusing.\n * 4. Client receives Finished.\n * 5. Client sends ChangeCipherSpec.\n * 6. Client sends Finished.\n *\n * Note: Client ignores HelloRequest if in the middle of a handshake.\n *\n * Record Layer:\n *\n * The record layer fragments information blocks into TLSPlaintext records\n * carrying data in chunks of 2^14 bytes or less. Client message boundaries are\n * not preserved in the record layer (i.e., multiple client messages of the\n * same ContentType MAY be coalesced into a single TLSPlaintext record, or a\n * single message MAY be fragmented across several records).\n *\n * struct {\n * uint8 major;\n * uint8 minor;\n * } ProtocolVersion;\n *\n * struct {\n * ContentType type;\n * ProtocolVersion version;\n * uint16 length;\n * opaque fragment[TLSPlaintext.length];\n * } TLSPlaintext;\n *\n * type:\n * The higher-level protocol used to process the enclosed fragment.\n *\n * version:\n * The version of the protocol being employed. TLS Version 1.2 uses version\n * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that\n * supports multiple versions of TLS may not know what version will be\n * employed before it receives the ServerHello.\n *\n * length:\n * The length (in bytes) of the following TLSPlaintext.fragment. The length\n * MUST NOT exceed 2^14 = 16384 bytes.\n *\n * fragment:\n * The application data. This data is transparent and treated as an\n * independent block to be dealt with by the higher-level protocol specified\n * by the type field.\n *\n * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or\n * ChangeCipherSpec content types. Zero-length fragments of Application data\n * MAY be sent as they are potentially useful as a traffic analysis\n * countermeasure.\n *\n * Note: Data of different TLS record layer content types MAY be interleaved.\n * Application data is generally of lower precedence for transmission than\n * other content types. However, records MUST be delivered to the network in\n * the same order as they are protected by the record layer. Recipients MUST\n * receive and process interleaved application layer traffic during handshakes\n * subsequent to the first one on a connection.\n *\n * struct {\n * ContentType type; // same as TLSPlaintext.type\n * ProtocolVersion version;// same as TLSPlaintext.version\n * uint16 length;\n * opaque fragment[TLSCompressed.length];\n * } TLSCompressed;\n *\n * length:\n * The length (in bytes) of the following TLSCompressed.fragment.\n * The length MUST NOT exceed 2^14 + 1024.\n *\n * fragment:\n * The compressed form of TLSPlaintext.fragment.\n *\n * Note: A CompressionMethod.null operation is an identity operation; no fields\n * are altered. In this implementation, since no compression is supported,\n * uncompressed records are always the same as compressed records.\n *\n * Encryption Information:\n *\n * The encryption and MAC functions translate a TLSCompressed structure into a\n * TLSCiphertext. The decryption functions reverse the process. The MAC of the\n * record also includes a sequence number so that missing, extra, or repeated\n * messages are detectable.\n *\n * struct {\n * ContentType type;\n * ProtocolVersion version;\n * uint16 length;\n * select (SecurityParameters.cipher_type) {\n * case stream: GenericStreamCipher;\n * case block: GenericBlockCipher;\n * case aead: GenericAEADCipher;\n * } fragment;\n * } TLSCiphertext;\n *\n * type:\n * The type field is identical to TLSCompressed.type.\n *\n * version:\n * The version field is identical to TLSCompressed.version.\n *\n * length:\n * The length (in bytes) of the following TLSCiphertext.fragment.\n * The length MUST NOT exceed 2^14 + 2048.\n *\n * fragment:\n * The encrypted form of TLSCompressed.fragment, with the MAC.\n *\n * Note: Only CBC Block Ciphers are supported by this implementation.\n *\n * The TLSCompressed.fragment structures are converted to/from block\n * TLSCiphertext.fragment structures.\n *\n * struct {\n * opaque IV[SecurityParameters.record_iv_length];\n * block-ciphered struct {\n * opaque content[TLSCompressed.length];\n * opaque MAC[SecurityParameters.mac_length];\n * uint8 padding[GenericBlockCipher.padding_length];\n * uint8 padding_length;\n * };\n * } GenericBlockCipher;\n *\n * The MAC is generated as described in Section 6.2.3.1.\n *\n * IV:\n * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be\n * unpredictable. Note that in versions of TLS prior to 1.1, there was no\n * IV field, and the last ciphertext block of the previous record (the \"CBC\n * residue\") was used as the IV. This was changed to prevent the attacks\n * described in [CBCATT]. For block ciphers, the IV length is of length\n * SecurityParameters.record_iv_length, which is equal to the\n * SecurityParameters.block_size.\n *\n * padding:\n * Padding that is added to force the length of the plaintext to be an\n * integral multiple of the block cipher's block length. The padding MAY be\n * any length up to 255 bytes, as long as it results in the\n * TLSCiphertext.length being an integral multiple of the block length.\n * Lengths longer than necessary might be desirable to frustrate attacks on\n * a protocol that are based on analysis of the lengths of exchanged\n * messages. Each uint8 in the padding data vector MUST be filled with the\n * padding length value. The receiver MUST check this padding and MUST use\n * the bad_record_mac alert to indicate padding errors.\n *\n * padding_length:\n * The padding length MUST be such that the total size of the\n * GenericBlockCipher structure is a multiple of the cipher's block length.\n * Legal values range from zero to 255, inclusive. This length specifies the\n * length of the padding field exclusive of the padding_length field itself.\n *\n * The encrypted data length (TLSCiphertext.length) is one more than the sum of\n * SecurityParameters.block_length, TLSCompressed.length,\n * SecurityParameters.mac_length, and padding_length.\n *\n * Example: If the block length is 8 bytes, the content length\n * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the\n * length before padding is 82 bytes (this does not include the IV. Thus, the\n * padding length modulo 8 must be equal to 6 in order to make the total length\n * an even multiple of 8 bytes (the block length). The padding length can be\n * 6, 14, 22, and so on, through 254. If the padding length were the minimum\n * necessary, 6, the padding would be 6 bytes, each containing the value 6.\n * Thus, the last 8 octets of the GenericBlockCipher before block encryption\n * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC.\n *\n * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical\n * that the entire plaintext of the record be known before any ciphertext is\n * transmitted. Otherwise, it is possible for the attacker to mount the attack\n * described in [CBCATT].\n *\n * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing\n * attack on CBC padding based on the time required to compute the MAC. In\n * order to defend against this attack, implementations MUST ensure that\n * record processing time is essentially the same whether or not the padding\n * is correct. In general, the best way to do this is to compute the MAC even\n * if the padding is incorrect, and only then reject the packet. For instance,\n * if the pad appears to be incorrect, the implementation might assume a\n * zero-length pad and then compute the MAC. This leaves a small timing\n * channel, since MAC performance depends, to some extent, on the size of the\n * data fragment, but it is not believed to be large enough to be exploitable,\n * due to the large block size of existing MACs and the small size of the\n * timing signal.\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./hmac');\nrequire('./md5');\nrequire('./pem');\nrequire('./pki');\nrequire('./random');\nrequire('./sha1');\nrequire('./util');\n\n/**\n * Generates pseudo random bytes by mixing the result of two hash functions,\n * MD5 and SHA-1.\n *\n * prf_TLS1(secret, label, seed) =\n * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);\n *\n * Each P_hash function functions as follows:\n *\n * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +\n * HMAC_hash(secret, A(2) + seed) +\n * HMAC_hash(secret, A(3) + seed) + ...\n * A() is defined as:\n * A(0) = seed\n * A(i) = HMAC_hash(secret, A(i-1))\n *\n * The '+' operator denotes concatenation.\n *\n * As many iterations A(N) as are needed are performed to generate enough\n * pseudo random byte output. If an iteration creates more data than is\n * necessary, then it is truncated.\n *\n * Therefore:\n * A(1) = HMAC_hash(secret, A(0))\n * = HMAC_hash(secret, seed)\n * A(2) = HMAC_hash(secret, A(1))\n * = HMAC_hash(secret, HMAC_hash(secret, seed))\n *\n * Therefore:\n * P_hash(secret, seed) =\n * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) +\n * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) +\n * ...\n *\n * Therefore:\n * P_hash(secret, seed) =\n * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) +\n * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) +\n * ...\n *\n * @param secret the secret to use.\n * @param label the label to use.\n * @param seed the seed value to use.\n * @param length the number of bytes to generate.\n *\n * @return the pseudo random bytes in a byte buffer.\n */\nvar prf_TLS1 = function(secret, label, seed, length) {\n var rval = forge.util.createBuffer();\n\n /* For TLS 1.0, the secret is split in half, into two secrets of equal\n length. If the secret has an odd length then the last byte of the first\n half will be the same as the first byte of the second. The length of the\n two secrets is half of the secret rounded up. */\n var idx = (secret.length >> 1);\n var slen = idx + (secret.length & 1);\n var s1 = secret.substr(0, slen);\n var s2 = secret.substr(idx, slen);\n var ai = forge.util.createBuffer();\n var hmac = forge.hmac.create();\n seed = label + seed;\n\n // determine the number of iterations that must be performed to generate\n // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20\n var md5itr = Math.ceil(length / 16);\n var sha1itr = Math.ceil(length / 20);\n\n // do md5 iterations\n hmac.start('MD5', s1);\n var md5bytes = forge.util.createBuffer();\n ai.putBytes(seed);\n for(var i = 0; i < md5itr; ++i) {\n // HMAC_hash(secret, A(i-1))\n hmac.start(null, null);\n hmac.update(ai.getBytes());\n ai.putBuffer(hmac.digest());\n\n // HMAC_hash(secret, A(i) + seed)\n hmac.start(null, null);\n hmac.update(ai.bytes() + seed);\n md5bytes.putBuffer(hmac.digest());\n }\n\n // do sha1 iterations\n hmac.start('SHA1', s2);\n var sha1bytes = forge.util.createBuffer();\n ai.clear();\n ai.putBytes(seed);\n for(var i = 0; i < sha1itr; ++i) {\n // HMAC_hash(secret, A(i-1))\n hmac.start(null, null);\n hmac.update(ai.getBytes());\n ai.putBuffer(hmac.digest());\n\n // HMAC_hash(secret, A(i) + seed)\n hmac.start(null, null);\n hmac.update(ai.bytes() + seed);\n sha1bytes.putBuffer(hmac.digest());\n }\n\n // XOR the md5 bytes with the sha1 bytes\n rval.putBytes(forge.util.xorBytes(\n md5bytes.getBytes(), sha1bytes.getBytes(), length));\n\n return rval;\n};\n\n/**\n * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2.\n *\n * @param secret the secret to use.\n * @param label the label to use.\n * @param seed the seed value to use.\n * @param length the number of bytes to generate.\n *\n * @return the pseudo random bytes in a byte buffer.\n */\nvar prf_sha256 = function(secret, label, seed, length) {\n // FIXME: implement me for TLS 1.2\n};\n\n/**\n * Gets a MAC for a record using the SHA-1 hash algorithm.\n *\n * @param key the mac key.\n * @param state the sequence number (array of two 32-bit integers).\n * @param record the record.\n *\n * @return the sha-1 hash (20 bytes) for the given record.\n */\nvar hmac_sha1 = function(key, seqNum, record) {\n /* MAC is computed like so:\n HMAC_hash(\n key, seqNum +\n TLSCompressed.type +\n TLSCompressed.version +\n TLSCompressed.length +\n TLSCompressed.fragment)\n */\n var hmac = forge.hmac.create();\n hmac.start('SHA1', key);\n var b = forge.util.createBuffer();\n b.putInt32(seqNum[0]);\n b.putInt32(seqNum[1]);\n b.putByte(record.type);\n b.putByte(record.version.major);\n b.putByte(record.version.minor);\n b.putInt16(record.length);\n b.putBytes(record.fragment.bytes());\n hmac.update(b.getBytes());\n return hmac.digest().getBytes();\n};\n\n/**\n * Compresses the TLSPlaintext record into a TLSCompressed record using the\n * deflate algorithm.\n *\n * @param c the TLS connection.\n * @param record the TLSPlaintext record to compress.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nvar deflate = function(c, record, s) {\n var rval = false;\n\n try {\n var bytes = c.deflate(record.fragment.getBytes());\n record.fragment = forge.util.createBuffer(bytes);\n record.length = bytes.length;\n rval = true;\n } catch(ex) {\n // deflate error, fail out\n }\n\n return rval;\n};\n\n/**\n * Decompresses the TLSCompressed record into a TLSPlaintext record using the\n * deflate algorithm.\n *\n * @param c the TLS connection.\n * @param record the TLSCompressed record to decompress.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nvar inflate = function(c, record, s) {\n var rval = false;\n\n try {\n var bytes = c.inflate(record.fragment.getBytes());\n record.fragment = forge.util.createBuffer(bytes);\n record.length = bytes.length;\n rval = true;\n } catch(ex) {\n // inflate error, fail out\n }\n\n return rval;\n};\n\n/**\n * Reads a TLS variable-length vector from a byte buffer.\n *\n * Variable-length vectors are defined by specifying a subrange of legal\n * lengths, inclusively, using the notation . When these are\n * encoded, the actual length precedes the vector's contents in the byte\n * stream. The length will be in the form of a number consuming as many bytes\n * as required to hold the vector's specified maximum (ceiling) length. A\n * variable-length vector with an actual length field of zero is referred to\n * as an empty vector.\n *\n * @param b the byte buffer.\n * @param lenBytes the number of bytes required to store the length.\n *\n * @return the resulting byte buffer.\n */\nvar readVector = function(b, lenBytes) {\n var len = 0;\n switch(lenBytes) {\n case 1:\n len = b.getByte();\n break;\n case 2:\n len = b.getInt16();\n break;\n case 3:\n len = b.getInt24();\n break;\n case 4:\n len = b.getInt32();\n break;\n }\n\n // read vector bytes into a new buffer\n return forge.util.createBuffer(b.getBytes(len));\n};\n\n/**\n * Writes a TLS variable-length vector to a byte buffer.\n *\n * @param b the byte buffer.\n * @param lenBytes the number of bytes required to store the length.\n * @param v the byte buffer vector.\n */\nvar writeVector = function(b, lenBytes, v) {\n // encode length at the start of the vector, where the number of bytes for\n // the length is the maximum number of bytes it would take to encode the\n // vector's ceiling\n b.putInt(v.length(), lenBytes << 3);\n b.putBuffer(v);\n};\n\n/**\n * The tls implementation.\n */\nvar tls = {};\n\n/**\n * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and\n * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time\n * of this implementation so TLS 1.0 was implemented instead.\n */\ntls.Versions = {\n TLS_1_0: {major: 3, minor: 1},\n TLS_1_1: {major: 3, minor: 2},\n TLS_1_2: {major: 3, minor: 3}\n};\ntls.SupportedVersions = [\n tls.Versions.TLS_1_1,\n tls.Versions.TLS_1_0\n];\ntls.Version = tls.SupportedVersions[0];\n\n/**\n * Maximum fragment size. True maximum is 16384, but we fragment before that\n * to allow for unusual small increases during compression.\n */\ntls.MaxFragment = 16384 - 1024;\n\n/**\n * Whether this entity is considered the \"client\" or \"server\".\n * enum { server, client } ConnectionEnd;\n */\ntls.ConnectionEnd = {\n server: 0,\n client: 1\n};\n\n/**\n * Pseudo-random function algorithm used to generate keys from the master\n * secret.\n * enum { tls_prf_sha256 } PRFAlgorithm;\n */\ntls.PRFAlgorithm = {\n tls_prf_sha256: 0\n};\n\n/**\n * Bulk encryption algorithms.\n * enum { null, rc4, des3, aes } BulkCipherAlgorithm;\n */\ntls.BulkCipherAlgorithm = {\n none: null,\n rc4: 0,\n des3: 1,\n aes: 2\n};\n\n/**\n * Cipher types.\n * enum { stream, block, aead } CipherType;\n */\ntls.CipherType = {\n stream: 0,\n block: 1,\n aead: 2\n};\n\n/**\n * MAC (Message Authentication Code) algorithms.\n * enum { null, hmac_md5, hmac_sha1, hmac_sha256,\n * hmac_sha384, hmac_sha512} MACAlgorithm;\n */\ntls.MACAlgorithm = {\n none: null,\n hmac_md5: 0,\n hmac_sha1: 1,\n hmac_sha256: 2,\n hmac_sha384: 3,\n hmac_sha512: 4\n};\n\n/**\n * Compression algorithms.\n * enum { null(0), deflate(1), (255) } CompressionMethod;\n */\ntls.CompressionMethod = {\n none: 0,\n deflate: 1\n};\n\n/**\n * TLS record content types.\n * enum {\n * change_cipher_spec(20), alert(21), handshake(22),\n * application_data(23), (255)\n * } ContentType;\n */\ntls.ContentType = {\n change_cipher_spec: 20,\n alert: 21,\n handshake: 22,\n application_data: 23,\n heartbeat: 24\n};\n\n/**\n * TLS handshake types.\n * enum {\n * hello_request(0), client_hello(1), server_hello(2),\n * certificate(11), server_key_exchange (12),\n * certificate_request(13), server_hello_done(14),\n * certificate_verify(15), client_key_exchange(16),\n * finished(20), (255)\n * } HandshakeType;\n */\ntls.HandshakeType = {\n hello_request: 0,\n client_hello: 1,\n server_hello: 2,\n certificate: 11,\n server_key_exchange: 12,\n certificate_request: 13,\n server_hello_done: 14,\n certificate_verify: 15,\n client_key_exchange: 16,\n finished: 20\n};\n\n/**\n * TLS Alert Protocol.\n *\n * enum { warning(1), fatal(2), (255) } AlertLevel;\n *\n * enum {\n * close_notify(0),\n * unexpected_message(10),\n * bad_record_mac(20),\n * decryption_failed(21),\n * record_overflow(22),\n * decompression_failure(30),\n * handshake_failure(40),\n * bad_certificate(42),\n * unsupported_certificate(43),\n * certificate_revoked(44),\n * certificate_expired(45),\n * certificate_unknown(46),\n * illegal_parameter(47),\n * unknown_ca(48),\n * access_denied(49),\n * decode_error(50),\n * decrypt_error(51),\n * export_restriction(60),\n * protocol_version(70),\n * insufficient_security(71),\n * internal_error(80),\n * user_canceled(90),\n * no_renegotiation(100),\n * (255)\n * } AlertDescription;\n *\n * struct {\n * AlertLevel level;\n * AlertDescription description;\n * } Alert;\n */\ntls.Alert = {};\ntls.Alert.Level = {\n warning: 1,\n fatal: 2\n};\ntls.Alert.Description = {\n close_notify: 0,\n unexpected_message: 10,\n bad_record_mac: 20,\n decryption_failed: 21,\n record_overflow: 22,\n decompression_failure: 30,\n handshake_failure: 40,\n bad_certificate: 42,\n unsupported_certificate: 43,\n certificate_revoked: 44,\n certificate_expired: 45,\n certificate_unknown: 46,\n illegal_parameter: 47,\n unknown_ca: 48,\n access_denied: 49,\n decode_error: 50,\n decrypt_error: 51,\n export_restriction: 60,\n protocol_version: 70,\n insufficient_security: 71,\n internal_error: 80,\n user_canceled: 90,\n no_renegotiation: 100\n};\n\n/**\n * TLS Heartbeat Message types.\n * enum {\n * heartbeat_request(1),\n * heartbeat_response(2),\n * (255)\n * } HeartbeatMessageType;\n */\ntls.HeartbeatMessageType = {\n heartbeat_request: 1,\n heartbeat_response: 2\n};\n\n/**\n * Supported cipher suites.\n */\ntls.CipherSuites = {};\n\n/**\n * Gets a supported cipher suite from its 2 byte ID.\n *\n * @param twoBytes two bytes in a string.\n *\n * @return the matching supported cipher suite or null.\n */\ntls.getCipherSuite = function(twoBytes) {\n var rval = null;\n for(var key in tls.CipherSuites) {\n var cs = tls.CipherSuites[key];\n if(cs.id[0] === twoBytes.charCodeAt(0) &&\n cs.id[1] === twoBytes.charCodeAt(1)) {\n rval = cs;\n break;\n }\n }\n return rval;\n};\n\n/**\n * Called when an unexpected record is encountered.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleUnexpected = function(c, record) {\n // if connection is client and closed, ignore unexpected messages\n var ignore = (!c.open && c.entity === tls.ConnectionEnd.client);\n if(!ignore) {\n c.error(c, {\n message: 'Unexpected message. Received TLS record out of order.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unexpected_message\n }\n });\n }\n};\n\n/**\n * Called when a client receives a HelloRequest record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleHelloRequest = function(c, record, length) {\n // ignore renegotiation requests from the server during a handshake, but\n // if handshaking, send a warning alert that renegotation is denied\n if(!c.handshaking && c.handshakes > 0) {\n // send alert warning\n tls.queue(c, tls.createAlert(c, {\n level: tls.Alert.Level.warning,\n description: tls.Alert.Description.no_renegotiation\n }));\n tls.flush(c);\n }\n\n // continue\n c.process();\n};\n\n/**\n * Parses a hello message from a ClientHello or ServerHello record.\n *\n * @param record the record to parse.\n *\n * @return the parsed message.\n */\ntls.parseHelloMessage = function(c, record, length) {\n var msg = null;\n\n var client = (c.entity === tls.ConnectionEnd.client);\n\n // minimum of 38 bytes in message\n if(length < 38) {\n c.error(c, {\n message: client ?\n 'Invalid ServerHello message. Message too short.' :\n 'Invalid ClientHello message. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n } else {\n // use 'remaining' to calculate # of remaining bytes in the message\n var b = record.fragment;\n var remaining = b.length();\n msg = {\n version: {\n major: b.getByte(),\n minor: b.getByte()\n },\n random: forge.util.createBuffer(b.getBytes(32)),\n session_id: readVector(b, 1),\n extensions: []\n };\n if(client) {\n msg.cipher_suite = b.getBytes(2);\n msg.compression_method = b.getByte();\n } else {\n msg.cipher_suites = readVector(b, 2);\n msg.compression_methods = readVector(b, 1);\n }\n\n // read extensions if there are any bytes left in the message\n remaining = length - (remaining - b.length());\n if(remaining > 0) {\n // parse extensions\n var exts = readVector(b, 2);\n while(exts.length() > 0) {\n msg.extensions.push({\n type: [exts.getByte(), exts.getByte()],\n data: readVector(exts, 2)\n });\n }\n\n // TODO: make extension support modular\n if(!client) {\n for(var i = 0; i < msg.extensions.length; ++i) {\n var ext = msg.extensions[i];\n\n // support SNI extension\n if(ext.type[0] === 0x00 && ext.type[1] === 0x00) {\n // get server name list\n var snl = readVector(ext.data, 2);\n while(snl.length() > 0) {\n // read server name type\n var snType = snl.getByte();\n\n // only HostName type (0x00) is known, break out if\n // another type is detected\n if(snType !== 0x00) {\n break;\n }\n\n // add host name to server name list\n c.session.extensions.server_name.serverNameList.push(\n readVector(snl, 2).getBytes());\n }\n }\n }\n }\n }\n\n // version already set, do not allow version change\n if(c.session.version) {\n if(msg.version.major !== c.session.version.major ||\n msg.version.minor !== c.session.version.minor) {\n return c.error(c, {\n message: 'TLS version change is disallowed during renegotiation.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n }\n\n // get the chosen (ServerHello) cipher suite\n if(client) {\n // FIXME: should be checking configured acceptable cipher suites\n c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite);\n } else {\n // get a supported preferred (ClientHello) cipher suite\n // choose the first supported cipher suite\n var tmp = forge.util.createBuffer(msg.cipher_suites.bytes());\n while(tmp.length() > 0) {\n // FIXME: should be checking configured acceptable suites\n // cipher suites take up 2 bytes\n c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2));\n if(c.session.cipherSuite !== null) {\n break;\n }\n }\n }\n\n // cipher suite not supported\n if(c.session.cipherSuite === null) {\n return c.error(c, {\n message: 'No cipher suites in common.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.handshake_failure\n },\n cipherSuite: forge.util.bytesToHex(msg.cipher_suite)\n });\n }\n\n // TODO: handle compression methods\n if(client) {\n c.session.compressionMethod = msg.compression_method;\n } else {\n // no compression\n c.session.compressionMethod = tls.CompressionMethod.none;\n }\n }\n\n return msg;\n};\n\n/**\n * Creates security parameters for the given connection based on the given\n * hello message.\n *\n * @param c the TLS connection.\n * @param msg the hello message.\n */\ntls.createSecurityParameters = function(c, msg) {\n /* Note: security params are from TLS 1.2, some values like prf_algorithm\n are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is\n used. */\n\n // TODO: handle other options from server when more supported\n\n // get client and server randoms\n var client = (c.entity === tls.ConnectionEnd.client);\n var msgRandom = msg.random.bytes();\n var cRandom = client ? c.session.sp.client_random : msgRandom;\n var sRandom = client ? msgRandom : tls.createRandom().getBytes();\n\n // create new security parameters\n c.session.sp = {\n entity: c.entity,\n prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256,\n bulk_cipher_algorithm: null,\n cipher_type: null,\n enc_key_length: null,\n block_length: null,\n fixed_iv_length: null,\n record_iv_length: null,\n mac_algorithm: null,\n mac_length: null,\n mac_key_length: null,\n compression_algorithm: c.session.compressionMethod,\n pre_master_secret: null,\n master_secret: null,\n client_random: cRandom,\n server_random: sRandom\n };\n};\n\n/**\n * Called when a client receives a ServerHello record.\n *\n * When a ServerHello message will be sent:\n * The server will send this message in response to a client hello message\n * when it was able to find an acceptable set of algorithms. If it cannot\n * find such a match, it will respond with a handshake failure alert.\n *\n * uint24 length;\n * struct {\n * ProtocolVersion server_version;\n * Random random;\n * SessionID session_id;\n * CipherSuite cipher_suite;\n * CompressionMethod compression_method;\n * select(extensions_present) {\n * case false:\n * struct {};\n * case true:\n * Extension extensions<0..2^16-1>;\n * };\n * } ServerHello;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerHello = function(c, record, length) {\n var msg = tls.parseHelloMessage(c, record, length);\n if(c.fail) {\n return;\n }\n\n // ensure server version is compatible\n if(msg.version.minor <= c.version.minor) {\n c.version.minor = msg.version.minor;\n } else {\n return c.error(c, {\n message: 'Incompatible TLS version.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n\n // indicate session version has been set\n c.session.version = c.version;\n\n // get the session ID from the message\n var sessionId = msg.session_id.bytes();\n\n // if the session ID is not blank and matches the cached one, resume\n // the session\n if(sessionId.length > 0 && sessionId === c.session.id) {\n // resuming session, expect a ChangeCipherSpec next\n c.expect = SCC;\n c.session.resuming = true;\n\n // get new server random\n c.session.sp.server_random = msg.random.bytes();\n } else {\n // not resuming, expect a server Certificate message next\n c.expect = SCE;\n c.session.resuming = false;\n\n // create new security parameters\n tls.createSecurityParameters(c, msg);\n }\n\n // set new session ID\n c.session.id = sessionId;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a server receives a ClientHello record.\n *\n * When a ClientHello message will be sent:\n * When a client first connects to a server it is required to send the\n * client hello as its first message. The client can also send a client\n * hello in response to a hello request or on its own initiative in order\n * to renegotiate the security parameters in an existing connection.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleClientHello = function(c, record, length) {\n var msg = tls.parseHelloMessage(c, record, length);\n if(c.fail) {\n return;\n }\n\n // get the session ID from the message\n var sessionId = msg.session_id.bytes();\n\n // see if the given session ID is in the cache\n var session = null;\n if(c.sessionCache) {\n session = c.sessionCache.getSession(sessionId);\n if(session === null) {\n // session ID not found\n sessionId = '';\n } else if(session.version.major !== msg.version.major ||\n session.version.minor > msg.version.minor) {\n // if session version is incompatible with client version, do not resume\n session = null;\n sessionId = '';\n }\n }\n\n // no session found to resume, generate a new session ID\n if(sessionId.length === 0) {\n sessionId = forge.random.getBytes(32);\n }\n\n // update session\n c.session.id = sessionId;\n c.session.clientHelloVersion = msg.version;\n c.session.sp = {};\n if(session) {\n // use version and security parameters from resumed session\n c.version = c.session.version = session.version;\n c.session.sp = session.sp;\n } else {\n // use highest compatible minor version\n var version;\n for(var i = 1; i < tls.SupportedVersions.length; ++i) {\n version = tls.SupportedVersions[i];\n if(version.minor <= msg.version.minor) {\n break;\n }\n }\n c.version = {major: version.major, minor: version.minor};\n c.session.version = c.version;\n }\n\n // if a session is set, resume it\n if(session !== null) {\n // resuming session, expect a ChangeCipherSpec next\n c.expect = CCC;\n c.session.resuming = true;\n\n // get new client random\n c.session.sp.client_random = msg.random.bytes();\n } else {\n // not resuming, expect a Certificate or ClientKeyExchange\n c.expect = (c.verifyClient !== false) ? CCE : CKE;\n c.session.resuming = false;\n\n // create new security parameters\n tls.createSecurityParameters(c, msg);\n }\n\n // connection now open\n c.open = true;\n\n // queue server hello\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerHello(c)\n }));\n\n if(c.session.resuming) {\n // queue change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // create pending state\n c.state.pending = tls.createConnectionState(c);\n\n // change current write state to pending write state\n c.state.current.write = c.state.pending.write;\n\n // queue finished\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n } else {\n // queue server certificate\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificate(c)\n }));\n\n if(!c.fail) {\n // queue server key exchange\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerKeyExchange(c)\n }));\n\n // request client certificate if set\n if(c.verifyClient !== false) {\n // queue certificate request\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificateRequest(c)\n }));\n }\n\n // queue server hello done\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerHelloDone(c)\n }));\n }\n }\n\n // send records\n tls.flush(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a Certificate record.\n *\n * When this message will be sent:\n * The server must send a certificate whenever the agreed-upon key exchange\n * method is not an anonymous one. This message will always immediately\n * follow the server hello message.\n *\n * Meaning of this message:\n * The certificate type must be appropriate for the selected cipher suite's\n * key exchange algorithm, and is generally an X.509v3 certificate. It must\n * contain a key which matches the key exchange method, as follows. Unless\n * otherwise specified, the signing algorithm for the certificate must be\n * the same as the algorithm for the certificate key. Unless otherwise\n * specified, the public key may be of any length.\n *\n * opaque ASN.1Cert<1..2^24-1>;\n * struct {\n * ASN.1Cert certificate_list<1..2^24-1>;\n * } Certificate;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificate = function(c, record, length) {\n // minimum of 3 bytes in message\n if(length < 3) {\n return c.error(c, {\n message: 'Invalid Certificate message. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n var b = record.fragment;\n var msg = {\n certificate_list: readVector(b, 3)\n };\n\n /* The sender's certificate will be first in the list (chain), each\n subsequent one that follows will certify the previous one, but root\n certificates (self-signed) that specify the certificate authority may\n be omitted under the assumption that clients must already possess it. */\n var cert, asn1;\n var certs = [];\n try {\n while(msg.certificate_list.length() > 0) {\n // each entry in msg.certificate_list is a vector with 3 len bytes\n cert = readVector(msg.certificate_list, 3);\n asn1 = forge.asn1.fromDer(cert);\n cert = forge.pki.certificateFromAsn1(asn1, true);\n certs.push(cert);\n }\n } catch(ex) {\n return c.error(c, {\n message: 'Could not parse certificate list.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n }\n });\n }\n\n // ensure at least 1 certificate was provided if in client-mode\n // or if verifyClient was set to true to require a certificate\n // (as opposed to 'optional')\n var client = (c.entity === tls.ConnectionEnd.client);\n if((client || c.verifyClient === true) && certs.length === 0) {\n // error, no certificate\n c.error(c, {\n message: client ?\n 'No server certificate provided.' :\n 'No client certificate provided.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n } else if(certs.length === 0) {\n // no certs to verify\n // expect a ServerKeyExchange or ClientKeyExchange message next\n c.expect = client ? SKE : CKE;\n } else {\n // save certificate in session\n if(client) {\n c.session.serverCertificate = certs[0];\n } else {\n c.session.clientCertificate = certs[0];\n }\n\n if(tls.verifyCertificateChain(c, certs)) {\n // expect a ServerKeyExchange or ClientKeyExchange message next\n c.expect = client ? SKE : CKE;\n }\n }\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ServerKeyExchange record.\n *\n * When this message will be sent:\n * This message will be sent immediately after the server certificate\n * message (or the server hello message, if this is an anonymous\n * negotiation).\n *\n * The server key exchange message is sent by the server only when the\n * server certificate message (if sent) does not contain enough data to\n * allow the client to exchange a premaster secret.\n *\n * Meaning of this message:\n * This message conveys cryptographic information to allow the client to\n * communicate the premaster secret: either an RSA public key to encrypt\n * the premaster secret with, or a Diffie-Hellman public key with which the\n * client can complete a key exchange (with the result being the premaster\n * secret.)\n *\n * enum {\n * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa\n * } KeyExchangeAlgorithm;\n *\n * struct {\n * opaque dh_p<1..2^16-1>;\n * opaque dh_g<1..2^16-1>;\n * opaque dh_Ys<1..2^16-1>;\n * } ServerDHParams;\n *\n * struct {\n * select(KeyExchangeAlgorithm) {\n * case dh_anon:\n * ServerDHParams params;\n * case dhe_dss:\n * case dhe_rsa:\n * ServerDHParams params;\n * digitally-signed struct {\n * opaque client_random[32];\n * opaque server_random[32];\n * ServerDHParams params;\n * } signed_params;\n * case rsa:\n * case dh_dss:\n * case dh_rsa:\n * struct {};\n * };\n * } ServerKeyExchange;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerKeyExchange = function(c, record, length) {\n // this implementation only supports RSA, no Diffie-Hellman support\n // so any length > 0 is invalid\n if(length > 0) {\n return c.error(c, {\n message: 'Invalid key parameters. Only RSA is supported.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unsupported_certificate\n }\n });\n }\n\n // expect an optional CertificateRequest message next\n c.expect = SCR;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ClientKeyExchange record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleClientKeyExchange = function(c, record, length) {\n // this implementation only supports RSA, no Diffie-Hellman support\n // so any length < 48 is invalid\n if(length < 48) {\n return c.error(c, {\n message: 'Invalid key parameters. Only RSA is supported.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unsupported_certificate\n }\n });\n }\n\n var b = record.fragment;\n var msg = {\n enc_pre_master_secret: readVector(b, 2).getBytes()\n };\n\n // do rsa decryption\n var privateKey = null;\n if(c.getPrivateKey) {\n try {\n privateKey = c.getPrivateKey(c, c.session.serverCertificate);\n privateKey = forge.pki.privateKeyFromPem(privateKey);\n } catch(ex) {\n c.error(c, {\n message: 'Could not get private key.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n }\n\n if(privateKey === null) {\n return c.error(c, {\n message: 'No private key set.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n\n try {\n // decrypt 48-byte pre-master secret\n var sp = c.session.sp;\n sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);\n\n // ensure client hello version matches first 2 bytes\n var version = c.session.clientHelloVersion;\n if(version.major !== sp.pre_master_secret.charCodeAt(0) ||\n version.minor !== sp.pre_master_secret.charCodeAt(1)) {\n // error, do not send alert (see BLEI attack below)\n throw new Error('TLS version rollback attack detected.');\n }\n } catch(ex) {\n /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a\n TLS server which is using PKCS#1 encoded RSA, so instead of\n failing here, we generate 48 random bytes and use that as\n the pre-master secret. */\n sp.pre_master_secret = forge.random.getBytes(48);\n }\n\n // expect a CertificateVerify message if a Certificate was received that\n // does not have fixed Diffie-Hellman params, otherwise expect\n // ChangeCipherSpec\n c.expect = CCC;\n if(c.session.clientCertificate !== null) {\n // only RSA support, so expect CertificateVerify\n // TODO: support Diffie-Hellman\n c.expect = CCV;\n }\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a CertificateRequest record.\n *\n * When this message will be sent:\n * A non-anonymous server can optionally request a certificate from the\n * client, if appropriate for the selected cipher suite. This message, if\n * sent, will immediately follow the Server Key Exchange message (if it is\n * sent; otherwise, the Server Certificate message).\n *\n * enum {\n * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),\n * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6),\n * fortezza_dms_RESERVED(20), (255)\n * } ClientCertificateType;\n *\n * opaque DistinguishedName<1..2^16-1>;\n *\n * struct {\n * ClientCertificateType certificate_types<1..2^8-1>;\n * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>;\n * DistinguishedName certificate_authorities<0..2^16-1>;\n * } CertificateRequest;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificateRequest = function(c, record, length) {\n // minimum of 3 bytes in message\n if(length < 3) {\n return c.error(c, {\n message: 'Invalid CertificateRequest. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // TODO: TLS 1.2+ has different format including\n // SignatureAndHashAlgorithm after cert types\n var b = record.fragment;\n var msg = {\n certificate_types: readVector(b, 1),\n certificate_authorities: readVector(b, 2)\n };\n\n // save certificate request in session\n c.session.certificateRequest = msg;\n\n // expect a ServerHelloDone message next\n c.expect = SHD;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a server receives a CertificateVerify record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificateVerify = function(c, record, length) {\n if(length < 2) {\n return c.error(c, {\n message: 'Invalid CertificateVerify. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // rewind to get full bytes for message so it can be manually\n // digested below (special case for CertificateVerify messages because\n // they must be digested *after* handling as opposed to all others)\n var b = record.fragment;\n b.read -= 4;\n var msgBytes = b.bytes();\n b.read += 4;\n\n var msg = {\n signature: readVector(b, 2).getBytes()\n };\n\n // TODO: add support for DSA\n\n // generate data to verify\n var verify = forge.util.createBuffer();\n verify.putBuffer(c.session.md5.digest());\n verify.putBuffer(c.session.sha1.digest());\n verify = verify.getBytes();\n\n try {\n var cert = c.session.clientCertificate;\n /*b = forge.pki.rsa.decrypt(\n msg.signature, cert.publicKey, true, verify.length);\n if(b !== verify) {*/\n if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) {\n throw new Error('CertificateVerify signature does not match.');\n }\n\n // digest message now that it has been handled\n c.session.md5.update(msgBytes);\n c.session.sha1.update(msgBytes);\n } catch(ex) {\n return c.error(c, {\n message: 'Bad signature in CertificateVerify.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.handshake_failure\n }\n });\n }\n\n // expect ChangeCipherSpec\n c.expect = CCC;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ServerHelloDone record.\n *\n * When this message will be sent:\n * The server hello done message is sent by the server to indicate the end\n * of the server hello and associated messages. After sending this message\n * the server will wait for a client response.\n *\n * Meaning of this message:\n * This message means that the server is done sending messages to support\n * the key exchange, and the client can proceed with its phase of the key\n * exchange.\n *\n * Upon receipt of the server hello done message the client should verify\n * that the server provided a valid certificate if required and check that\n * the server hello parameters are acceptable.\n *\n * struct {} ServerHelloDone;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerHelloDone = function(c, record, length) {\n // len must be 0 bytes\n if(length > 0) {\n return c.error(c, {\n message: 'Invalid ServerHelloDone message. Invalid length.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.record_overflow\n }\n });\n }\n\n if(c.serverCertificate === null) {\n // no server certificate was provided\n var error = {\n message: 'No server certificate provided. Not enough security.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.insufficient_security\n }\n };\n\n // call application callback\n var depth = 0;\n var ret = c.verify(c, error.alert.description, depth, []);\n if(ret !== true) {\n // check for custom alert info\n if(ret || ret === 0) {\n // set custom message and alert description\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.alert) {\n error.alert.description = ret.alert;\n }\n } else if(typeof ret === 'number') {\n // set custom alert description\n error.alert.description = ret;\n }\n }\n\n // send error\n return c.error(c, error);\n }\n }\n\n // create client certificate message if requested\n if(c.session.certificateRequest !== null) {\n record = tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificate(c)\n });\n tls.queue(c, record);\n }\n\n // create client key exchange message\n record = tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createClientKeyExchange(c)\n });\n tls.queue(c, record);\n\n // expect no messages until the following callback has been called\n c.expect = SER;\n\n // create callback to handle client signature (for client-certs)\n var callback = function(c, signature) {\n if(c.session.certificateRequest !== null &&\n c.session.clientCertificate !== null) {\n // create certificate verify message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificateVerify(c, signature)\n }));\n }\n\n // create change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // create pending state\n c.state.pending = tls.createConnectionState(c);\n\n // change current write state to pending write state\n c.state.current.write = c.state.pending.write;\n\n // create finished message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n\n // expect a server ChangeCipherSpec message next\n c.expect = SCC;\n\n // send records\n tls.flush(c);\n\n // continue\n c.process();\n };\n\n // if there is no certificate request or no client certificate, do\n // callback immediately\n if(c.session.certificateRequest === null ||\n c.session.clientCertificate === null) {\n return callback(c, null);\n }\n\n // otherwise get the client signature\n tls.getClientSignature(c, callback);\n};\n\n/**\n * Called when a ChangeCipherSpec record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleChangeCipherSpec = function(c, record) {\n if(record.fragment.getByte() !== 0x01) {\n return c.error(c, {\n message: 'Invalid ChangeCipherSpec message received.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // create pending state if:\n // 1. Resuming session in client mode OR\n // 2. NOT resuming session in server mode\n var client = (c.entity === tls.ConnectionEnd.client);\n if((c.session.resuming && client) || (!c.session.resuming && !client)) {\n c.state.pending = tls.createConnectionState(c);\n }\n\n // change current read state to pending read state\n c.state.current.read = c.state.pending.read;\n\n // clear pending state if:\n // 1. NOT resuming session in client mode OR\n // 2. resuming a session in server mode\n if((!c.session.resuming && client) || (c.session.resuming && !client)) {\n c.state.pending = null;\n }\n\n // expect a Finished record next\n c.expect = client ? SFI : CFI;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Finished record is received.\n *\n * When this message will be sent:\n * A finished message is always sent immediately after a change\n * cipher spec message to verify that the key exchange and\n * authentication processes were successful. It is essential that a\n * change cipher spec message be received between the other\n * handshake messages and the Finished message.\n *\n * Meaning of this message:\n * The finished message is the first protected with the just-\n * negotiated algorithms, keys, and secrets. Recipients of finished\n * messages must verify that the contents are correct. Once a side\n * has sent its Finished message and received and validated the\n * Finished message from its peer, it may begin to send and receive\n * application data over the connection.\n *\n * struct {\n * opaque verify_data[verify_data_length];\n * } Finished;\n *\n * verify_data\n * PRF(master_secret, finished_label, Hash(handshake_messages))\n * [0..verify_data_length-1];\n *\n * finished_label\n * For Finished messages sent by the client, the string\n * \"client finished\". For Finished messages sent by the server, the\n * string \"server finished\".\n *\n * verify_data_length depends on the cipher suite. If it is not specified\n * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used\n * 12 bytes.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleFinished = function(c, record, length) {\n // rewind to get full bytes for message so it can be manually\n // digested below (special case for Finished messages because they\n // must be digested *after* handling as opposed to all others)\n var b = record.fragment;\n b.read -= 4;\n var msgBytes = b.bytes();\n b.read += 4;\n\n // message contains only verify_data\n var vd = record.fragment.getBytes();\n\n // ensure verify data is correct\n b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n\n // set label based on entity type\n var client = (c.entity === tls.ConnectionEnd.client);\n var label = client ? 'server finished' : 'client finished';\n\n // TODO: determine prf function and verify length for TLS 1.2\n var sp = c.session.sp;\n var vdl = 12;\n var prf = prf_TLS1;\n b = prf(sp.master_secret, label, b.getBytes(), vdl);\n if(b.getBytes() !== vd) {\n return c.error(c, {\n message: 'Invalid verify_data in Finished message.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.decrypt_error\n }\n });\n }\n\n // digest finished message now that it has been handled\n c.session.md5.update(msgBytes);\n c.session.sha1.update(msgBytes);\n\n // resuming session as client or NOT resuming session as server\n if((c.session.resuming && client) || (!c.session.resuming && !client)) {\n // create change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // change current write state to pending write state, clear pending\n c.state.current.write = c.state.pending.write;\n c.state.pending = null;\n\n // create finished message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n }\n\n // expect application data next\n c.expect = client ? SAD : CAD;\n\n // handshake complete\n c.handshaking = false;\n ++c.handshakes;\n\n // save access to peer certificate\n c.peerCertificate = client ?\n c.session.serverCertificate : c.session.clientCertificate;\n\n // send records\n tls.flush(c);\n\n // now connected\n c.isConnected = true;\n c.connected(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when an Alert record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleAlert = function(c, record) {\n // read alert\n var b = record.fragment;\n var alert = {\n level: b.getByte(),\n description: b.getByte()\n };\n\n // TODO: consider using a table?\n // get appropriate message\n var msg;\n switch(alert.description) {\n case tls.Alert.Description.close_notify:\n msg = 'Connection closed.';\n break;\n case tls.Alert.Description.unexpected_message:\n msg = 'Unexpected message.';\n break;\n case tls.Alert.Description.bad_record_mac:\n msg = 'Bad record MAC.';\n break;\n case tls.Alert.Description.decryption_failed:\n msg = 'Decryption failed.';\n break;\n case tls.Alert.Description.record_overflow:\n msg = 'Record overflow.';\n break;\n case tls.Alert.Description.decompression_failure:\n msg = 'Decompression failed.';\n break;\n case tls.Alert.Description.handshake_failure:\n msg = 'Handshake failure.';\n break;\n case tls.Alert.Description.bad_certificate:\n msg = 'Bad certificate.';\n break;\n case tls.Alert.Description.unsupported_certificate:\n msg = 'Unsupported certificate.';\n break;\n case tls.Alert.Description.certificate_revoked:\n msg = 'Certificate revoked.';\n break;\n case tls.Alert.Description.certificate_expired:\n msg = 'Certificate expired.';\n break;\n case tls.Alert.Description.certificate_unknown:\n msg = 'Certificate unknown.';\n break;\n case tls.Alert.Description.illegal_parameter:\n msg = 'Illegal parameter.';\n break;\n case tls.Alert.Description.unknown_ca:\n msg = 'Unknown certificate authority.';\n break;\n case tls.Alert.Description.access_denied:\n msg = 'Access denied.';\n break;\n case tls.Alert.Description.decode_error:\n msg = 'Decode error.';\n break;\n case tls.Alert.Description.decrypt_error:\n msg = 'Decrypt error.';\n break;\n case tls.Alert.Description.export_restriction:\n msg = 'Export restriction.';\n break;\n case tls.Alert.Description.protocol_version:\n msg = 'Unsupported protocol version.';\n break;\n case tls.Alert.Description.insufficient_security:\n msg = 'Insufficient security.';\n break;\n case tls.Alert.Description.internal_error:\n msg = 'Internal error.';\n break;\n case tls.Alert.Description.user_canceled:\n msg = 'User canceled.';\n break;\n case tls.Alert.Description.no_renegotiation:\n msg = 'Renegotiation not supported.';\n break;\n default:\n msg = 'Unknown error.';\n break;\n }\n\n // close connection on close_notify, not an error\n if(alert.description === tls.Alert.Description.close_notify) {\n return c.close();\n }\n\n // call error handler\n c.error(c, {\n message: msg,\n send: false,\n // origin is the opposite end\n origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client',\n alert: alert\n });\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Handshake record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleHandshake = function(c, record) {\n // get the handshake type and message length\n var b = record.fragment;\n var type = b.getByte();\n var length = b.getInt24();\n\n // see if the record fragment doesn't yet contain the full message\n if(length > b.length()) {\n // cache the record, clear its fragment, and reset the buffer read\n // pointer before the type and length were read\n c.fragmented = record;\n record.fragment = forge.util.createBuffer();\n b.read -= 4;\n\n // continue\n return c.process();\n }\n\n // full message now available, clear cache, reset read pointer to\n // before type and length\n c.fragmented = null;\n b.read -= 4;\n\n // save the handshake bytes for digestion after handler is found\n // (include type and length of handshake msg)\n var bytes = b.bytes(length + 4);\n\n // restore read pointer\n b.read += 4;\n\n // handle expected message\n if(type in hsTable[c.entity][c.expect]) {\n // initialize server session\n if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) {\n c.handshaking = true;\n c.session = {\n version: null,\n extensions: {\n server_name: {\n serverNameList: []\n }\n },\n cipherSuite: null,\n compressionMethod: null,\n serverCertificate: null,\n clientCertificate: null,\n md5: forge.md.md5.create(),\n sha1: forge.md.sha1.create()\n };\n }\n\n /* Update handshake messages digest. Finished and CertificateVerify\n messages are not digested here. They can't be digested as part of\n the verify_data that they contain. These messages are manually\n digested in their handlers. HelloRequest messages are simply never\n included in the handshake message digest according to spec. */\n if(type !== tls.HandshakeType.hello_request &&\n type !== tls.HandshakeType.certificate_verify &&\n type !== tls.HandshakeType.finished) {\n c.session.md5.update(bytes);\n c.session.sha1.update(bytes);\n }\n\n // handle specific handshake type record\n hsTable[c.entity][c.expect][type](c, record, length);\n } else {\n // unexpected record\n tls.handleUnexpected(c, record);\n }\n};\n\n/**\n * Called when an ApplicationData record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleApplicationData = function(c, record) {\n // buffer data, notify that its ready\n c.data.putBuffer(record.fragment);\n c.dataReady(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Heartbeat record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleHeartbeat = function(c, record) {\n // get the heartbeat type and payload\n var b = record.fragment;\n var type = b.getByte();\n var length = b.getInt16();\n var payload = b.getBytes(length);\n\n if(type === tls.HeartbeatMessageType.heartbeat_request) {\n // discard request during handshake or if length is too large\n if(c.handshaking || length > payload.length) {\n // continue\n return c.process();\n }\n // retransmit payload\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.heartbeat,\n data: tls.createHeartbeat(\n tls.HeartbeatMessageType.heartbeat_response, payload)\n }));\n tls.flush(c);\n } else if(type === tls.HeartbeatMessageType.heartbeat_response) {\n // check payload against expected payload, discard heartbeat if no match\n if(payload !== c.expectedHeartbeatPayload) {\n // continue\n return c.process();\n }\n\n // notify that a valid heartbeat was received\n if(c.heartbeatReceived) {\n c.heartbeatReceived(c, forge.util.createBuffer(payload));\n }\n }\n\n // continue\n c.process();\n};\n\n/**\n * The transistional state tables for receiving TLS records. It maps the\n * current TLS engine state and a received record to a function to handle the\n * record and update the state.\n *\n * For instance, if the current state is SHE, then the TLS engine is expecting\n * a ServerHello record. Once a record is received, the handler function is\n * looked up using the state SHE and the record's content type.\n *\n * The resulting function will either be an error handler or a record handler.\n * The function will take whatever action is appropriate and update the state\n * for the next record.\n *\n * The states are all based on possible server record types. Note that the\n * client will never specifically expect to receive a HelloRequest or an alert\n * from the server so there is no state that reflects this. These messages may\n * occur at any time.\n *\n * There are two tables for mapping states because there is a second tier of\n * types for handshake messages. Once a record with a content type of handshake\n * is received, the handshake record handler will look up the handshake type in\n * the secondary map to get its appropriate handler.\n *\n * Valid message orders are as follows:\n *\n * =======================FULL HANDSHAKE======================\n * Client Server\n *\n * ClientHello -------->\n * ServerHello\n * Certificate*\n * ServerKeyExchange*\n * CertificateRequest*\n * <-------- ServerHelloDone\n * Certificate*\n * ClientKeyExchange\n * CertificateVerify*\n * [ChangeCipherSpec]\n * Finished -------->\n * [ChangeCipherSpec]\n * <-------- Finished\n * Application Data <-------> Application Data\n *\n * =====================SESSION RESUMPTION=====================\n * Client Server\n *\n * ClientHello -------->\n * ServerHello\n * [ChangeCipherSpec]\n * <-------- Finished\n * [ChangeCipherSpec]\n * Finished -------->\n * Application Data <-------> Application Data\n */\n// client expect states (indicate which records are expected to be received)\nvar SHE = 0; // rcv server hello\nvar SCE = 1; // rcv server certificate\nvar SKE = 2; // rcv server key exchange\nvar SCR = 3; // rcv certificate request\nvar SHD = 4; // rcv server hello done\nvar SCC = 5; // rcv change cipher spec\nvar SFI = 6; // rcv finished\nvar SAD = 7; // rcv application data\nvar SER = 8; // not expecting any messages at this point\n\n// server expect states\nvar CHE = 0; // rcv client hello\nvar CCE = 1; // rcv client certificate\nvar CKE = 2; // rcv client key exchange\nvar CCV = 3; // rcv certificate verify\nvar CCC = 4; // rcv change cipher spec\nvar CFI = 5; // rcv finished\nvar CAD = 6; // rcv application data\nvar CER = 7; // not expecting any messages at this point\n\n// map client current expect state and content type to function\nvar __ = tls.handleUnexpected;\nvar R0 = tls.handleChangeCipherSpec;\nvar R1 = tls.handleAlert;\nvar R2 = tls.handleHandshake;\nvar R3 = tls.handleApplicationData;\nvar R4 = tls.handleHeartbeat;\nvar ctTable = [];\nctTable[tls.ConnectionEnd.client] = [\n// CC,AL,HS,AD,HB\n/*SHE*/[__,R1,R2,__,R4],\n/*SCE*/[__,R1,R2,__,R4],\n/*SKE*/[__,R1,R2,__,R4],\n/*SCR*/[__,R1,R2,__,R4],\n/*SHD*/[__,R1,R2,__,R4],\n/*SCC*/[R0,R1,__,__,R4],\n/*SFI*/[__,R1,R2,__,R4],\n/*SAD*/[__,R1,R2,R3,R4],\n/*SER*/[__,R1,R2,__,R4]\n];\n\n// map server current expect state and content type to function\nctTable[tls.ConnectionEnd.server] = [\n// CC,AL,HS,AD\n/*CHE*/[__,R1,R2,__,R4],\n/*CCE*/[__,R1,R2,__,R4],\n/*CKE*/[__,R1,R2,__,R4],\n/*CCV*/[__,R1,R2,__,R4],\n/*CCC*/[R0,R1,__,__,R4],\n/*CFI*/[__,R1,R2,__,R4],\n/*CAD*/[__,R1,R2,R3,R4],\n/*CER*/[__,R1,R2,__,R4]\n];\n\n// map client current expect state and handshake type to function\nvar H0 = tls.handleHelloRequest;\nvar H1 = tls.handleServerHello;\nvar H2 = tls.handleCertificate;\nvar H3 = tls.handleServerKeyExchange;\nvar H4 = tls.handleCertificateRequest;\nvar H5 = tls.handleServerHelloDone;\nvar H6 = tls.handleFinished;\nvar hsTable = [];\nhsTable[tls.ConnectionEnd.client] = [\n// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI\n/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],\n/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],\n/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],\n/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],\n/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],\n/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]\n];\n\n// map server current expect state and handshake type to function\n// Note: CAD[CH] does not map to FB because renegotation is prohibited\nvar H7 = tls.handleClientHello;\nvar H8 = tls.handleClientKeyExchange;\nvar H9 = tls.handleCertificateVerify;\nhsTable[tls.ConnectionEnd.server] = [\n// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI\n/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],\n/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],\n/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],\n/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],\n/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]\n];\n\n/**\n * Generates the master_secret and keys using the given security parameters.\n *\n * The security parameters for a TLS connection state are defined as such:\n *\n * struct {\n * ConnectionEnd entity;\n * PRFAlgorithm prf_algorithm;\n * BulkCipherAlgorithm bulk_cipher_algorithm;\n * CipherType cipher_type;\n * uint8 enc_key_length;\n * uint8 block_length;\n * uint8 fixed_iv_length;\n * uint8 record_iv_length;\n * MACAlgorithm mac_algorithm;\n * uint8 mac_length;\n * uint8 mac_key_length;\n * CompressionMethod compression_algorithm;\n * opaque master_secret[48];\n * opaque client_random[32];\n * opaque server_random[32];\n * } SecurityParameters;\n *\n * Note that this definition is from TLS 1.2. In TLS 1.0 some of these\n * parameters are ignored because, for instance, the PRFAlgorithm is a\n * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0.\n *\n * The Record Protocol requires an algorithm to generate keys required by the\n * current connection state.\n *\n * The master secret is expanded into a sequence of secure bytes, which is then\n * split to a client write MAC key, a server write MAC key, a client write\n * encryption key, and a server write encryption key. In TLS 1.0 a client write\n * IV and server write IV are also generated. Each of these is generated from\n * the byte sequence in that order. Unused values are empty. In TLS 1.2, some\n * AEAD ciphers may additionally require a client write IV and a server write\n * IV (see Section 6.2.3.3).\n *\n * When keys, MAC keys, and IVs are generated, the master secret is used as an\n * entropy source.\n *\n * To generate the key material, compute:\n *\n * master_secret = PRF(pre_master_secret, \"master secret\",\n * ClientHello.random + ServerHello.random)\n *\n * key_block = PRF(SecurityParameters.master_secret,\n * \"key expansion\",\n * SecurityParameters.server_random +\n * SecurityParameters.client_random);\n *\n * until enough output has been generated. Then, the key_block is\n * partitioned as follows:\n *\n * client_write_MAC_key[SecurityParameters.mac_key_length]\n * server_write_MAC_key[SecurityParameters.mac_key_length]\n * client_write_key[SecurityParameters.enc_key_length]\n * server_write_key[SecurityParameters.enc_key_length]\n * client_write_IV[SecurityParameters.fixed_iv_length]\n * server_write_IV[SecurityParameters.fixed_iv_length]\n *\n * In TLS 1.2, the client_write_IV and server_write_IV are only generated for\n * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This\n * implementation uses TLS 1.0 so IVs are generated.\n *\n * Implementation note: The currently defined cipher suite which requires the\n * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32\n * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also\n * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material.\n *\n * @param c the connection.\n * @param sp the security parameters to use.\n *\n * @return the security keys.\n */\ntls.generateKeys = function(c, sp) {\n // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) &\n // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented\n // at present\n\n // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with\n // TLS 1.0 but we don't care right now because AES is better and we have\n // an implementation for it\n\n // TODO: TLS 1.2 implementation\n /*\n // determine the PRF\n var prf;\n switch(sp.prf_algorithm) {\n case tls.PRFAlgorithm.tls_prf_sha256:\n prf = prf_sha256;\n break;\n default:\n // should never happen\n throw new Error('Invalid PRF');\n }\n */\n\n // TLS 1.0/1.1 implementation\n var prf = prf_TLS1;\n\n // concatenate server and client random\n var random = sp.client_random + sp.server_random;\n\n // only create master secret if session is new\n if(!c.session.resuming) {\n // create master secret, clean up pre-master secret\n sp.master_secret = prf(\n sp.pre_master_secret, 'master secret', random, 48).bytes();\n sp.pre_master_secret = null;\n }\n\n // generate the amount of key material needed\n random = sp.server_random + sp.client_random;\n var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length;\n\n // include IV for TLS/1.0\n var tls10 = (c.version.major === tls.Versions.TLS_1_0.major &&\n c.version.minor === tls.Versions.TLS_1_0.minor);\n if(tls10) {\n length += 2 * sp.fixed_iv_length;\n }\n var km = prf(sp.master_secret, 'key expansion', random, length);\n\n // split the key material into the MAC and encryption keys\n var rval = {\n client_write_MAC_key: km.getBytes(sp.mac_key_length),\n server_write_MAC_key: km.getBytes(sp.mac_key_length),\n client_write_key: km.getBytes(sp.enc_key_length),\n server_write_key: km.getBytes(sp.enc_key_length)\n };\n\n // include TLS 1.0 IVs\n if(tls10) {\n rval.client_write_IV = km.getBytes(sp.fixed_iv_length);\n rval.server_write_IV = km.getBytes(sp.fixed_iv_length);\n }\n\n return rval;\n};\n\n/**\n * Creates a new initialized TLS connection state. A connection state has\n * a read mode and a write mode.\n *\n * compression state:\n * The current state of the compression algorithm.\n *\n * cipher state:\n * The current state of the encryption algorithm. This will consist of the\n * scheduled key for that connection. For stream ciphers, this will also\n * contain whatever state information is necessary to allow the stream to\n * continue to encrypt or decrypt data.\n *\n * MAC key:\n * The MAC key for the connection.\n *\n * sequence number:\n * Each connection state contains a sequence number, which is maintained\n * separately for read and write states. The sequence number MUST be set to\n * zero whenever a connection state is made the active state. Sequence\n * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do\n * not wrap. If a TLS implementation would need to wrap a sequence number,\n * it must renegotiate instead. A sequence number is incremented after each\n * record: specifically, the first record transmitted under a particular\n * connection state MUST use sequence number 0.\n *\n * @param c the connection.\n *\n * @return the new initialized TLS connection state.\n */\ntls.createConnectionState = function(c) {\n var client = (c.entity === tls.ConnectionEnd.client);\n\n var createMode = function() {\n var mode = {\n // two 32-bit numbers, first is most significant\n sequenceNumber: [0, 0],\n macKey: null,\n macLength: 0,\n macFunction: null,\n cipherState: null,\n cipherFunction: function(record) {return true;},\n compressionState: null,\n compressFunction: function(record) {return true;},\n updateSequenceNumber: function() {\n if(mode.sequenceNumber[1] === 0xFFFFFFFF) {\n mode.sequenceNumber[1] = 0;\n ++mode.sequenceNumber[0];\n } else {\n ++mode.sequenceNumber[1];\n }\n }\n };\n return mode;\n };\n var state = {\n read: createMode(),\n write: createMode()\n };\n\n // update function in read mode will decrypt then decompress a record\n state.read.update = function(c, record) {\n if(!state.read.cipherFunction(record, state.read)) {\n c.error(c, {\n message: 'Could not decrypt record or bad MAC.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n // doesn't matter if decryption failed or MAC was\n // invalid, return the same error so as not to reveal\n // which one occurred\n description: tls.Alert.Description.bad_record_mac\n }\n });\n } else if(!state.read.compressFunction(c, record, state.read)) {\n c.error(c, {\n message: 'Could not decompress record.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.decompression_failure\n }\n });\n }\n return !c.fail;\n };\n\n // update function in write mode will compress then encrypt a record\n state.write.update = function(c, record) {\n if(!state.write.compressFunction(c, record, state.write)) {\n // error, but do not send alert since it would require\n // compression as well\n c.error(c, {\n message: 'Could not compress record.',\n send: false,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n } else if(!state.write.cipherFunction(record, state.write)) {\n // error, but do not send alert since it would require\n // encryption as well\n c.error(c, {\n message: 'Could not encrypt record.',\n send: false,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n return !c.fail;\n };\n\n // handle security parameters\n if(c.session) {\n var sp = c.session.sp;\n c.session.cipherSuite.initSecurityParameters(sp);\n\n // generate keys\n sp.keys = tls.generateKeys(c, sp);\n state.read.macKey = client ?\n sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key;\n state.write.macKey = client ?\n sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key;\n\n // cipher suite setup\n c.session.cipherSuite.initConnectionState(state, c, sp);\n\n // compression setup\n switch(sp.compression_algorithm) {\n case tls.CompressionMethod.none:\n break;\n case tls.CompressionMethod.deflate:\n state.read.compressFunction = inflate;\n state.write.compressFunction = deflate;\n break;\n default:\n throw new Error('Unsupported compression algorithm.');\n }\n }\n\n return state;\n};\n\n/**\n * Creates a Random structure.\n *\n * struct {\n * uint32 gmt_unix_time;\n * opaque random_bytes[28];\n * } Random;\n *\n * gmt_unix_time:\n * The current time and date in standard UNIX 32-bit format (seconds since\n * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according\n * to the sender's internal clock. Clocks are not required to be set\n * correctly by the basic TLS protocol; higher-level or application\n * protocols may define additional requirements. Note that, for historical\n * reasons, the data element is named using GMT, the predecessor of the\n * current worldwide time base, UTC.\n * random_bytes:\n * 28 bytes generated by a secure random number generator.\n *\n * @return the Random structure as a byte array.\n */\ntls.createRandom = function() {\n // get UTC milliseconds\n var d = new Date();\n var utc = +d + d.getTimezoneOffset() * 60000;\n var rval = forge.util.createBuffer();\n rval.putInt32(utc);\n rval.putBytes(forge.random.getBytes(28));\n return rval;\n};\n\n/**\n * Creates a TLS record with the given type and data.\n *\n * @param c the connection.\n * @param options:\n * type: the record type.\n * data: the plain text data in a byte buffer.\n *\n * @return the created record.\n */\ntls.createRecord = function(c, options) {\n if(!options.data) {\n return null;\n }\n var record = {\n type: options.type,\n version: {\n major: c.version.major,\n minor: c.version.minor\n },\n length: options.data.length(),\n fragment: options.data\n };\n return record;\n};\n\n/**\n * Creates a TLS alert record.\n *\n * @param c the connection.\n * @param alert:\n * level: the TLS alert level.\n * description: the TLS alert description.\n *\n * @return the created alert record.\n */\ntls.createAlert = function(c, alert) {\n var b = forge.util.createBuffer();\n b.putByte(alert.level);\n b.putByte(alert.description);\n return tls.createRecord(c, {\n type: tls.ContentType.alert,\n data: b\n });\n};\n\n/* The structure of a TLS handshake message.\n *\n * struct {\n * HandshakeType msg_type; // handshake type\n * uint24 length; // bytes in message\n * select(HandshakeType) {\n * case hello_request: HelloRequest;\n * case client_hello: ClientHello;\n * case server_hello: ServerHello;\n * case certificate: Certificate;\n * case server_key_exchange: ServerKeyExchange;\n * case certificate_request: CertificateRequest;\n * case server_hello_done: ServerHelloDone;\n * case certificate_verify: CertificateVerify;\n * case client_key_exchange: ClientKeyExchange;\n * case finished: Finished;\n * } body;\n * } Handshake;\n */\n\n/**\n * Creates a ClientHello message.\n *\n * opaque SessionID<0..32>;\n * enum { null(0), deflate(1), (255) } CompressionMethod;\n * uint8 CipherSuite[2];\n *\n * struct {\n * ProtocolVersion client_version;\n * Random random;\n * SessionID session_id;\n * CipherSuite cipher_suites<2..2^16-2>;\n * CompressionMethod compression_methods<1..2^8-1>;\n * select(extensions_present) {\n * case false:\n * struct {};\n * case true:\n * Extension extensions<0..2^16-1>;\n * };\n * } ClientHello;\n *\n * The extension format for extended client hellos and server hellos is:\n *\n * struct {\n * ExtensionType extension_type;\n * opaque extension_data<0..2^16-1>;\n * } Extension;\n *\n * Here:\n *\n * - \"extension_type\" identifies the particular extension type.\n * - \"extension_data\" contains information specific to the particular\n * extension type.\n *\n * The extension types defined in this document are:\n *\n * enum {\n * server_name(0), max_fragment_length(1),\n * client_certificate_url(2), trusted_ca_keys(3),\n * truncated_hmac(4), status_request(5), (65535)\n * } ExtensionType;\n *\n * @param c the connection.\n *\n * @return the ClientHello byte buffer.\n */\ntls.createClientHello = function(c) {\n // save hello version\n c.session.clientHelloVersion = {\n major: c.version.major,\n minor: c.version.minor\n };\n\n // create supported cipher suites\n var cipherSuites = forge.util.createBuffer();\n for(var i = 0; i < c.cipherSuites.length; ++i) {\n var cs = c.cipherSuites[i];\n cipherSuites.putByte(cs.id[0]);\n cipherSuites.putByte(cs.id[1]);\n }\n var cSuites = cipherSuites.length();\n\n // create supported compression methods, null always supported, but\n // also support deflate if connection has inflate and deflate methods\n var compressionMethods = forge.util.createBuffer();\n compressionMethods.putByte(tls.CompressionMethod.none);\n // FIXME: deflate support disabled until issues with raw deflate data\n // without zlib headers are resolved\n /*\n if(c.inflate !== null && c.deflate !== null) {\n compressionMethods.putByte(tls.CompressionMethod.deflate);\n }\n */\n var cMethods = compressionMethods.length();\n\n // create TLS SNI (server name indication) extension if virtual host\n // has been specified, see RFC 3546\n var extensions = forge.util.createBuffer();\n if(c.virtualHost) {\n // create extension struct\n var ext = forge.util.createBuffer();\n ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes)\n ext.putByte(0x00);\n\n /* In order to provide the server name, clients MAY include an\n * extension of type \"server_name\" in the (extended) client hello.\n * The \"extension_data\" field of this extension SHALL contain\n * \"ServerNameList\" where:\n *\n * struct {\n * NameType name_type;\n * select(name_type) {\n * case host_name: HostName;\n * } name;\n * } ServerName;\n *\n * enum {\n * host_name(0), (255)\n * } NameType;\n *\n * opaque HostName<1..2^16-1>;\n *\n * struct {\n * ServerName server_name_list<1..2^16-1>\n * } ServerNameList;\n */\n var serverName = forge.util.createBuffer();\n serverName.putByte(0x00); // type host_name\n writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost));\n\n // ServerNameList is in extension_data\n var snList = forge.util.createBuffer();\n writeVector(snList, 2, serverName);\n writeVector(ext, 2, snList);\n extensions.putBuffer(ext);\n }\n var extLength = extensions.length();\n if(extLength > 0) {\n // add extension vector length\n extLength += 2;\n }\n\n // determine length of the handshake message\n // cipher suites and compression methods size will need to be\n // updated if more get added to the list\n var sessionId = c.session.id;\n var length =\n sessionId.length + 1 + // session ID vector\n 2 + // version (major + minor)\n 4 + 28 + // random time and random bytes\n 2 + cSuites + // cipher suites vector\n 1 + cMethods + // compression methods vector\n extLength; // extensions vector\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.client_hello);\n rval.putInt24(length); // handshake length\n rval.putByte(c.version.major); // major version\n rval.putByte(c.version.minor); // minor version\n rval.putBytes(c.session.sp.client_random); // random time + bytes\n writeVector(rval, 1, forge.util.createBuffer(sessionId));\n writeVector(rval, 2, cipherSuites);\n writeVector(rval, 1, compressionMethods);\n if(extLength > 0) {\n writeVector(rval, 2, extensions);\n }\n return rval;\n};\n\n/**\n * Creates a ServerHello message.\n *\n * @param c the connection.\n *\n * @return the ServerHello byte buffer.\n */\ntls.createServerHello = function(c) {\n // determine length of the handshake message\n var sessionId = c.session.id;\n var length =\n sessionId.length + 1 + // session ID vector\n 2 + // version (major + minor)\n 4 + 28 + // random time and random bytes\n 2 + // chosen cipher suite\n 1; // chosen compression method\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.server_hello);\n rval.putInt24(length); // handshake length\n rval.putByte(c.version.major); // major version\n rval.putByte(c.version.minor); // minor version\n rval.putBytes(c.session.sp.server_random); // random time + bytes\n writeVector(rval, 1, forge.util.createBuffer(sessionId));\n rval.putByte(c.session.cipherSuite.id[0]);\n rval.putByte(c.session.cipherSuite.id[1]);\n rval.putByte(c.session.compressionMethod);\n return rval;\n};\n\n/**\n * Creates a Certificate message.\n *\n * When this message will be sent:\n * This is the first message the client can send after receiving a server\n * hello done message and the first message the server can send after\n * sending a ServerHello. This client message is only sent if the server\n * requests a certificate. If no suitable certificate is available, the\n * client should send a certificate message containing no certificates. If\n * client authentication is required by the server for the handshake to\n * continue, it may respond with a fatal handshake failure alert.\n *\n * opaque ASN.1Cert<1..2^24-1>;\n *\n * struct {\n * ASN.1Cert certificate_list<0..2^24-1>;\n * } Certificate;\n *\n * @param c the connection.\n *\n * @return the Certificate byte buffer.\n */\ntls.createCertificate = function(c) {\n // TODO: check certificate request to ensure types are supported\n\n // get a certificate (a certificate as a PEM string)\n var client = (c.entity === tls.ConnectionEnd.client);\n var cert = null;\n if(c.getCertificate) {\n var hint;\n if(client) {\n hint = c.session.certificateRequest;\n } else {\n hint = c.session.extensions.server_name.serverNameList;\n }\n cert = c.getCertificate(c, hint);\n }\n\n // buffer to hold certificate list\n var certList = forge.util.createBuffer();\n if(cert !== null) {\n try {\n // normalize cert to a chain of certificates\n if(!forge.util.isArray(cert)) {\n cert = [cert];\n }\n var asn1 = null;\n for(var i = 0; i < cert.length; ++i) {\n var msg = forge.pem.decode(cert[i])[0];\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error('Could not convert certificate from PEM; PEM ' +\n 'header type is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or ' +\n '\"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n var der = forge.util.createBuffer(msg.body);\n if(asn1 === null) {\n asn1 = forge.asn1.fromDer(der.bytes(), false);\n }\n\n // certificate entry is itself a vector with 3 length bytes\n var certBuffer = forge.util.createBuffer();\n writeVector(certBuffer, 3, der);\n\n // add cert vector to cert list vector\n certList.putBuffer(certBuffer);\n }\n\n // save certificate\n cert = forge.pki.certificateFromAsn1(asn1);\n if(client) {\n c.session.clientCertificate = cert;\n } else {\n c.session.serverCertificate = cert;\n }\n } catch(ex) {\n return c.error(c, {\n message: 'Could not send certificate list.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n }\n });\n }\n }\n\n // determine length of the handshake message\n var length = 3 + certList.length(); // cert list vector\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate);\n rval.putInt24(length);\n writeVector(rval, 3, certList);\n return rval;\n};\n\n/**\n * Creates a ClientKeyExchange message.\n *\n * When this message will be sent:\n * This message is always sent by the client. It will immediately follow the\n * client certificate message, if it is sent. Otherwise it will be the first\n * message sent by the client after it receives the server hello done\n * message.\n *\n * Meaning of this message:\n * With this message, the premaster secret is set, either though direct\n * transmission of the RSA-encrypted secret, or by the transmission of\n * Diffie-Hellman parameters which will allow each side to agree upon the\n * same premaster secret. When the key exchange method is DH_RSA or DH_DSS,\n * client certification has been requested, and the client was able to\n * respond with a certificate which contained a Diffie-Hellman public key\n * whose parameters (group and generator) matched those specified by the\n * server in its certificate, this message will not contain any data.\n *\n * Meaning of this message:\n * If RSA is being used for key agreement and authentication, the client\n * generates a 48-byte premaster secret, encrypts it using the public key\n * from the server's certificate or the temporary RSA key provided in a\n * server key exchange message, and sends the result in an encrypted\n * premaster secret message. This structure is a variant of the client\n * key exchange message, not a message in itself.\n *\n * struct {\n * select(KeyExchangeAlgorithm) {\n * case rsa: EncryptedPreMasterSecret;\n * case diffie_hellman: ClientDiffieHellmanPublic;\n * } exchange_keys;\n * } ClientKeyExchange;\n *\n * struct {\n * ProtocolVersion client_version;\n * opaque random[46];\n * } PreMasterSecret;\n *\n * struct {\n * public-key-encrypted PreMasterSecret pre_master_secret;\n * } EncryptedPreMasterSecret;\n *\n * A public-key-encrypted element is encoded as a vector <0..2^16-1>.\n *\n * @param c the connection.\n *\n * @return the ClientKeyExchange byte buffer.\n */\ntls.createClientKeyExchange = function(c) {\n // create buffer to encrypt\n var b = forge.util.createBuffer();\n\n // add highest client-supported protocol to help server avoid version\n // rollback attacks\n b.putByte(c.session.clientHelloVersion.major);\n b.putByte(c.session.clientHelloVersion.minor);\n\n // generate and add 46 random bytes\n b.putBytes(forge.random.getBytes(46));\n\n // save pre-master secret\n var sp = c.session.sp;\n sp.pre_master_secret = b.getBytes();\n\n // RSA-encrypt the pre-master secret\n var key = c.session.serverCertificate.publicKey;\n b = key.encrypt(sp.pre_master_secret);\n\n /* Note: The encrypted pre-master secret will be stored in a\n public-key-encrypted opaque vector that has the length prefixed using\n 2 bytes, so include those 2 bytes in the handshake message length. This\n is done as a minor optimization instead of calling writeVector(). */\n\n // determine length of the handshake message\n var length = b.length + 2;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.client_key_exchange);\n rval.putInt24(length);\n // add vector length bytes\n rval.putInt16(b.length);\n rval.putBytes(b);\n return rval;\n};\n\n/**\n * Creates a ServerKeyExchange message.\n *\n * @param c the connection.\n *\n * @return the ServerKeyExchange byte buffer.\n */\ntls.createServerKeyExchange = function(c) {\n // this implementation only supports RSA, no Diffie-Hellman support,\n // so this record is empty\n\n // determine length of the handshake message\n var length = 0;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n if(length > 0) {\n rval.putByte(tls.HandshakeType.server_key_exchange);\n rval.putInt24(length);\n }\n return rval;\n};\n\n/**\n * Gets the signed data used to verify a client-side certificate. See\n * tls.createCertificateVerify() for details.\n *\n * @param c the connection.\n * @param callback the callback to call once the signed data is ready.\n */\ntls.getClientSignature = function(c, callback) {\n // generate data to RSA encrypt\n var b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n b = b.getBytes();\n\n // create default signing function as necessary\n c.getSignature = c.getSignature || function(c, b, callback) {\n // do rsa encryption, call callback\n var privateKey = null;\n if(c.getPrivateKey) {\n try {\n privateKey = c.getPrivateKey(c, c.session.clientCertificate);\n privateKey = forge.pki.privateKeyFromPem(privateKey);\n } catch(ex) {\n c.error(c, {\n message: 'Could not get private key.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n }\n if(privateKey === null) {\n c.error(c, {\n message: 'No private key set.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n } else {\n b = privateKey.sign(b, null);\n }\n callback(c, b);\n };\n\n // get client signature\n c.getSignature(c, b, callback);\n};\n\n/**\n * Creates a CertificateVerify message.\n *\n * Meaning of this message:\n * This structure conveys the client's Diffie-Hellman public value\n * (Yc) if it was not already included in the client's certificate.\n * The encoding used for Yc is determined by the enumerated\n * PublicValueEncoding. This structure is a variant of the client\n * key exchange message, not a message in itself.\n *\n * When this message will be sent:\n * This message is used to provide explicit verification of a client\n * certificate. This message is only sent following a client\n * certificate that has signing capability (i.e. all certificates\n * except those containing fixed Diffie-Hellman parameters). When\n * sent, it will immediately follow the client key exchange message.\n *\n * struct {\n * Signature signature;\n * } CertificateVerify;\n *\n * CertificateVerify.signature.md5_hash\n * MD5(handshake_messages);\n *\n * Certificate.signature.sha_hash\n * SHA(handshake_messages);\n *\n * Here handshake_messages refers to all handshake messages sent or\n * received starting at client hello up to but not including this\n * message, including the type and length fields of the handshake\n * messages.\n *\n * select(SignatureAlgorithm) {\n * case anonymous: struct { };\n * case rsa:\n * digitally-signed struct {\n * opaque md5_hash[16];\n * opaque sha_hash[20];\n * };\n * case dsa:\n * digitally-signed struct {\n * opaque sha_hash[20];\n * };\n * } Signature;\n *\n * In digital signing, one-way hash functions are used as input for a\n * signing algorithm. A digitally-signed element is encoded as an opaque\n * vector <0..2^16-1>, where the length is specified by the signing\n * algorithm and key.\n *\n * In RSA signing, a 36-byte structure of two hashes (one SHA and one\n * MD5) is signed (encrypted with the private key). It is encoded with\n * PKCS #1 block type 0 or type 1 as described in [PKCS1].\n *\n * In DSS, the 20 bytes of the SHA hash are run directly through the\n * Digital Signing Algorithm with no additional hashing.\n *\n * @param c the connection.\n * @param signature the signature to include in the message.\n *\n * @return the CertificateVerify byte buffer.\n */\ntls.createCertificateVerify = function(c, signature) {\n /* Note: The signature will be stored in a \"digitally-signed\" opaque\n vector that has the length prefixed using 2 bytes, so include those\n 2 bytes in the handshake message length. This is done as a minor\n optimization instead of calling writeVector(). */\n\n // determine length of the handshake message\n var length = signature.length + 2;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate_verify);\n rval.putInt24(length);\n // add vector length bytes\n rval.putInt16(signature.length);\n rval.putBytes(signature);\n return rval;\n};\n\n/**\n * Creates a CertificateRequest message.\n *\n * @param c the connection.\n *\n * @return the CertificateRequest byte buffer.\n */\ntls.createCertificateRequest = function(c) {\n // TODO: support other certificate types\n var certTypes = forge.util.createBuffer();\n\n // common RSA certificate type\n certTypes.putByte(0x01);\n\n // add distinguished names from CA store\n var cAs = forge.util.createBuffer();\n for(var key in c.caStore.certs) {\n var cert = c.caStore.certs[key];\n var dn = forge.pki.distinguishedNameToAsn1(cert.subject);\n var byteBuffer = forge.asn1.toDer(dn);\n cAs.putInt16(byteBuffer.length());\n cAs.putBuffer(byteBuffer);\n }\n\n // TODO: TLS 1.2+ has a different format\n\n // determine length of the handshake message\n var length =\n 1 + certTypes.length() +\n 2 + cAs.length();\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate_request);\n rval.putInt24(length);\n writeVector(rval, 1, certTypes);\n writeVector(rval, 2, cAs);\n return rval;\n};\n\n/**\n * Creates a ServerHelloDone message.\n *\n * @param c the connection.\n *\n * @return the ServerHelloDone byte buffer.\n */\ntls.createServerHelloDone = function(c) {\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.server_hello_done);\n rval.putInt24(0);\n return rval;\n};\n\n/**\n * Creates a ChangeCipherSpec message.\n *\n * The change cipher spec protocol exists to signal transitions in\n * ciphering strategies. The protocol consists of a single message,\n * which is encrypted and compressed under the current (not the pending)\n * connection state. The message consists of a single byte of value 1.\n *\n * struct {\n * enum { change_cipher_spec(1), (255) } type;\n * } ChangeCipherSpec;\n *\n * @return the ChangeCipherSpec byte buffer.\n */\ntls.createChangeCipherSpec = function() {\n var rval = forge.util.createBuffer();\n rval.putByte(0x01);\n return rval;\n};\n\n/**\n * Creates a Finished message.\n *\n * struct {\n * opaque verify_data[12];\n * } Finished;\n *\n * verify_data\n * PRF(master_secret, finished_label, MD5(handshake_messages) +\n * SHA-1(handshake_messages)) [0..11];\n *\n * finished_label\n * For Finished messages sent by the client, the string \"client\n * finished\". For Finished messages sent by the server, the\n * string \"server finished\".\n *\n * handshake_messages\n * All of the data from all handshake messages up to but not\n * including this message. This is only data visible at the\n * handshake layer and does not include record layer headers.\n * This is the concatenation of all the Handshake structures as\n * defined in 7.4 exchanged thus far.\n *\n * @param c the connection.\n *\n * @return the Finished byte buffer.\n */\ntls.createFinished = function(c) {\n // generate verify_data\n var b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n\n // TODO: determine prf function and verify length for TLS 1.2\n var client = (c.entity === tls.ConnectionEnd.client);\n var sp = c.session.sp;\n var vdl = 12;\n var prf = prf_TLS1;\n var label = client ? 'client finished' : 'server finished';\n b = prf(sp.master_secret, label, b.getBytes(), vdl);\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.finished);\n rval.putInt24(b.length());\n rval.putBuffer(b);\n return rval;\n};\n\n/**\n * Creates a HeartbeatMessage (See RFC 6520).\n *\n * struct {\n * HeartbeatMessageType type;\n * uint16 payload_length;\n * opaque payload[HeartbeatMessage.payload_length];\n * opaque padding[padding_length];\n * } HeartbeatMessage;\n *\n * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or\n * max_fragment_length when negotiated as defined in [RFC6066].\n *\n * type: The message type, either heartbeat_request or heartbeat_response.\n *\n * payload_length: The length of the payload.\n *\n * payload: The payload consists of arbitrary content.\n *\n * padding: The padding is random content that MUST be ignored by the\n * receiver. The length of a HeartbeatMessage is TLSPlaintext.length\n * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the\n * length of the type field is 1 byte, and the length of the\n * payload_length is 2. Therefore, the padding_length is\n * TLSPlaintext.length - payload_length - 3 for TLS and\n * DTLSPlaintext.length - payload_length - 3 for DTLS. The\n * padding_length MUST be at least 16.\n *\n * The sender of a HeartbeatMessage MUST use a random padding of at\n * least 16 bytes. The padding of a received HeartbeatMessage message\n * MUST be ignored.\n *\n * If the payload_length of a received HeartbeatMessage is too large,\n * the received HeartbeatMessage MUST be discarded silently.\n *\n * @param c the connection.\n * @param type the tls.HeartbeatMessageType.\n * @param payload the heartbeat data to send as the payload.\n * @param [payloadLength] the payload length to use, defaults to the\n * actual payload length.\n *\n * @return the HeartbeatRequest byte buffer.\n */\ntls.createHeartbeat = function(type, payload, payloadLength) {\n if(typeof payloadLength === 'undefined') {\n payloadLength = payload.length;\n }\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(type); // heartbeat message type\n rval.putInt16(payloadLength); // payload length\n rval.putBytes(payload); // payload\n // padding\n var plaintextLength = rval.length();\n var paddingLength = Math.max(16, plaintextLength - payloadLength - 3);\n rval.putBytes(forge.random.getBytes(paddingLength));\n return rval;\n};\n\n/**\n * Fragments, compresses, encrypts, and queues a record for delivery.\n *\n * @param c the connection.\n * @param record the record to queue.\n */\ntls.queue = function(c, record) {\n // error during record creation\n if(!record) {\n return;\n }\n\n if(record.fragment.length() === 0) {\n if(record.type === tls.ContentType.handshake ||\n record.type === tls.ContentType.alert ||\n record.type === tls.ContentType.change_cipher_spec) {\n // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent.\n return;\n }\n }\n\n // if the record is a handshake record, update handshake hashes\n if(record.type === tls.ContentType.handshake) {\n var bytes = record.fragment.bytes();\n c.session.md5.update(bytes);\n c.session.sha1.update(bytes);\n bytes = null;\n }\n\n // handle record fragmentation\n var records;\n if(record.fragment.length() <= tls.MaxFragment) {\n records = [record];\n } else {\n // fragment data as long as it is too long\n records = [];\n var data = record.fragment.bytes();\n while(data.length > tls.MaxFragment) {\n records.push(tls.createRecord(c, {\n type: record.type,\n data: forge.util.createBuffer(data.slice(0, tls.MaxFragment))\n }));\n data = data.slice(tls.MaxFragment);\n }\n // add last record\n if(data.length > 0) {\n records.push(tls.createRecord(c, {\n type: record.type,\n data: forge.util.createBuffer(data)\n }));\n }\n }\n\n // compress and encrypt all fragmented records\n for(var i = 0; i < records.length && !c.fail; ++i) {\n // update the record using current write state\n var rec = records[i];\n var s = c.state.current.write;\n if(s.update(c, rec)) {\n // store record\n c.records.push(rec);\n }\n }\n};\n\n/**\n * Flushes all queued records to the output buffer and calls the\n * tlsDataReady() handler on the given connection.\n *\n * @param c the connection.\n *\n * @return true on success, false on failure.\n */\ntls.flush = function(c) {\n for(var i = 0; i < c.records.length; ++i) {\n var record = c.records[i];\n\n // add record header and fragment\n c.tlsData.putByte(record.type);\n c.tlsData.putByte(record.version.major);\n c.tlsData.putByte(record.version.minor);\n c.tlsData.putInt16(record.fragment.length());\n c.tlsData.putBuffer(c.records[i].fragment);\n }\n c.records = [];\n return c.tlsDataReady(c);\n};\n\n/**\n * Maps a pki.certificateError to a tls.Alert.Description.\n *\n * @param error the error to map.\n *\n * @return the alert description.\n */\nvar _certErrorToAlertDesc = function(error) {\n switch(error) {\n case true:\n return true;\n case forge.pki.certificateError.bad_certificate:\n return tls.Alert.Description.bad_certificate;\n case forge.pki.certificateError.unsupported_certificate:\n return tls.Alert.Description.unsupported_certificate;\n case forge.pki.certificateError.certificate_revoked:\n return tls.Alert.Description.certificate_revoked;\n case forge.pki.certificateError.certificate_expired:\n return tls.Alert.Description.certificate_expired;\n case forge.pki.certificateError.certificate_unknown:\n return tls.Alert.Description.certificate_unknown;\n case forge.pki.certificateError.unknown_ca:\n return tls.Alert.Description.unknown_ca;\n default:\n return tls.Alert.Description.bad_certificate;\n }\n};\n\n/**\n * Maps a tls.Alert.Description to a pki.certificateError.\n *\n * @param desc the alert description.\n *\n * @return the certificate error.\n */\nvar _alertDescToCertError = function(desc) {\n switch(desc) {\n case true:\n return true;\n case tls.Alert.Description.bad_certificate:\n return forge.pki.certificateError.bad_certificate;\n case tls.Alert.Description.unsupported_certificate:\n return forge.pki.certificateError.unsupported_certificate;\n case tls.Alert.Description.certificate_revoked:\n return forge.pki.certificateError.certificate_revoked;\n case tls.Alert.Description.certificate_expired:\n return forge.pki.certificateError.certificate_expired;\n case tls.Alert.Description.certificate_unknown:\n return forge.pki.certificateError.certificate_unknown;\n case tls.Alert.Description.unknown_ca:\n return forge.pki.certificateError.unknown_ca;\n default:\n return forge.pki.certificateError.bad_certificate;\n }\n};\n\n/**\n * Verifies a certificate chain against the given connection's\n * Certificate Authority store.\n *\n * @param c the TLS connection.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end.\n *\n * @return true if successful, false if not.\n */\ntls.verifyCertificateChain = function(c, chain) {\n try {\n // Make a copy of c.verifyOptions so that we can modify options.verify\n // without modifying c.verifyOptions.\n var options = {};\n for (var key in c.verifyOptions) {\n options[key] = c.verifyOptions[key];\n }\n\n options.verify = function(vfd, depth, chain) {\n // convert pki.certificateError to tls alert description\n var desc = _certErrorToAlertDesc(vfd);\n\n // call application callback\n var ret = c.verify(c, vfd, depth, chain);\n if(ret !== true) {\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n // throw custom error\n var error = new Error('The application rejected the certificate.');\n error.send = true;\n error.alert = {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n };\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.alert) {\n error.alert.description = ret.alert;\n }\n throw error;\n }\n\n // convert tls alert description to pki.certificateError\n if(ret !== vfd) {\n ret = _alertDescToCertError(ret);\n }\n }\n\n return ret;\n };\n\n // verify chain\n forge.pki.verifyCertificateChain(c.caStore, chain, options);\n } catch(ex) {\n // build tls error if not already customized\n var err = ex;\n if(typeof err !== 'object' || forge.util.isArray(err)) {\n err = {\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: _certErrorToAlertDesc(ex)\n }\n };\n }\n if(!('send' in err)) {\n err.send = true;\n }\n if(!('alert' in err)) {\n err.alert = {\n level: tls.Alert.Level.fatal,\n description: _certErrorToAlertDesc(err.error)\n };\n }\n\n // send error\n c.error(c, err);\n }\n\n return !c.fail;\n};\n\n/**\n * Creates a new TLS session cache.\n *\n * @param cache optional map of session ID to cached session.\n * @param capacity the maximum size for the cache (default: 100).\n *\n * @return the new TLS session cache.\n */\ntls.createSessionCache = function(cache, capacity) {\n var rval = null;\n\n // assume input is already a session cache object\n if(cache && cache.getSession && cache.setSession && cache.order) {\n rval = cache;\n } else {\n // create cache\n rval = {};\n rval.cache = cache || {};\n rval.capacity = Math.max(capacity || 100, 1);\n rval.order = [];\n\n // store order for sessions, delete session overflow\n for(var key in cache) {\n if(rval.order.length <= capacity) {\n rval.order.push(key);\n } else {\n delete cache[key];\n }\n }\n\n // get a session from a session ID (or get any session)\n rval.getSession = function(sessionId) {\n var session = null;\n var key = null;\n\n // if session ID provided, use it\n if(sessionId) {\n key = forge.util.bytesToHex(sessionId);\n } else if(rval.order.length > 0) {\n // get first session from cache\n key = rval.order[0];\n }\n\n if(key !== null && key in rval.cache) {\n // get cached session and remove from cache\n session = rval.cache[key];\n delete rval.cache[key];\n for(var i in rval.order) {\n if(rval.order[i] === key) {\n rval.order.splice(i, 1);\n break;\n }\n }\n }\n\n return session;\n };\n\n // set a session in the cache\n rval.setSession = function(sessionId, session) {\n // remove session from cache if at capacity\n if(rval.order.length === rval.capacity) {\n var key = rval.order.shift();\n delete rval.cache[key];\n }\n // add session to cache\n var key = forge.util.bytesToHex(sessionId);\n rval.order.push(key);\n rval.cache[key] = session;\n };\n }\n\n return rval;\n};\n\n/**\n * Creates a new TLS connection.\n *\n * See public createConnection() docs for more details.\n *\n * @param options the options for this connection.\n *\n * @return the new TLS connection.\n */\ntls.createConnection = function(options) {\n var caStore = null;\n if(options.caStore) {\n // if CA store is an array, convert it to a CA store object\n if(forge.util.isArray(options.caStore)) {\n caStore = forge.pki.createCaStore(options.caStore);\n } else {\n caStore = options.caStore;\n }\n } else {\n // create empty CA store\n caStore = forge.pki.createCaStore();\n }\n\n // setup default cipher suites\n var cipherSuites = options.cipherSuites || null;\n if(cipherSuites === null) {\n cipherSuites = [];\n for(var key in tls.CipherSuites) {\n cipherSuites.push(tls.CipherSuites[key]);\n }\n }\n\n // set default entity\n var entity = (options.server || false) ?\n tls.ConnectionEnd.server : tls.ConnectionEnd.client;\n\n // create session cache if requested\n var sessionCache = options.sessionCache ?\n tls.createSessionCache(options.sessionCache) : null;\n\n // create TLS connection\n var c = {\n version: {major: tls.Version.major, minor: tls.Version.minor},\n entity: entity,\n sessionId: options.sessionId,\n caStore: caStore,\n sessionCache: sessionCache,\n cipherSuites: cipherSuites,\n connected: options.connected,\n virtualHost: options.virtualHost || null,\n verifyClient: options.verifyClient || false,\n verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;},\n verifyOptions: options.verifyOptions || {},\n getCertificate: options.getCertificate || null,\n getPrivateKey: options.getPrivateKey || null,\n getSignature: options.getSignature || null,\n input: forge.util.createBuffer(),\n tlsData: forge.util.createBuffer(),\n data: forge.util.createBuffer(),\n tlsDataReady: options.tlsDataReady,\n dataReady: options.dataReady,\n heartbeatReceived: options.heartbeatReceived,\n closed: options.closed,\n error: function(c, ex) {\n // set origin if not set\n ex.origin = ex.origin ||\n ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server');\n\n // send TLS alert\n if(ex.send) {\n tls.queue(c, tls.createAlert(c, ex.alert));\n tls.flush(c);\n }\n\n // error is fatal by default\n var fatal = (ex.fatal !== false);\n if(fatal) {\n // set fail flag\n c.fail = true;\n }\n\n // call error handler first\n options.error(c, ex);\n\n if(fatal) {\n // fatal error, close connection, do not clear fail\n c.close(false);\n }\n },\n deflate: options.deflate || null,\n inflate: options.inflate || null\n };\n\n /**\n * Resets a closed TLS connection for reuse. Called in c.close().\n *\n * @param clearFail true to clear the fail flag (default: true).\n */\n c.reset = function(clearFail) {\n c.version = {major: tls.Version.major, minor: tls.Version.minor};\n c.record = null;\n c.session = null;\n c.peerCertificate = null;\n c.state = {\n pending: null,\n current: null\n };\n c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE;\n c.fragmented = null;\n c.records = [];\n c.open = false;\n c.handshakes = 0;\n c.handshaking = false;\n c.isConnected = false;\n c.fail = !(clearFail || typeof(clearFail) === 'undefined');\n c.input.clear();\n c.tlsData.clear();\n c.data.clear();\n c.state.current = tls.createConnectionState(c);\n };\n\n // do initial reset of connection\n c.reset();\n\n /**\n * Updates the current TLS engine state based on the given record.\n *\n * @param c the TLS connection.\n * @param record the TLS record to act on.\n */\n var _update = function(c, record) {\n // get record handler (align type in table by subtracting lowest)\n var aligned = record.type - tls.ContentType.change_cipher_spec;\n var handlers = ctTable[c.entity][c.expect];\n if(aligned in handlers) {\n handlers[aligned](c, record);\n } else {\n // unexpected record\n tls.handleUnexpected(c, record);\n }\n };\n\n /**\n * Reads the record header and initializes the next record on the given\n * connection.\n *\n * @param c the TLS connection with the next record.\n *\n * @return 0 if the input data could be processed, otherwise the\n * number of bytes required for data to be processed.\n */\n var _readRecordHeader = function(c) {\n var rval = 0;\n\n // get input buffer and its length\n var b = c.input;\n var len = b.length();\n\n // need at least 5 bytes to initialize a record\n if(len < 5) {\n rval = 5 - len;\n } else {\n // enough bytes for header\n // initialize record\n c.record = {\n type: b.getByte(),\n version: {\n major: b.getByte(),\n minor: b.getByte()\n },\n length: b.getInt16(),\n fragment: forge.util.createBuffer(),\n ready: false\n };\n\n // check record version\n var compatibleVersion = (c.record.version.major === c.version.major);\n if(compatibleVersion && c.session && c.session.version) {\n // session version already set, require same minor version\n compatibleVersion = (c.record.version.minor === c.version.minor);\n }\n if(!compatibleVersion) {\n c.error(c, {\n message: 'Incompatible TLS version.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n }\n\n return rval;\n };\n\n /**\n * Reads the next record's contents and appends its message to any\n * previously fragmented message.\n *\n * @param c the TLS connection with the next record.\n *\n * @return 0 if the input data could be processed, otherwise the\n * number of bytes required for data to be processed.\n */\n var _readRecord = function(c) {\n var rval = 0;\n\n // ensure there is enough input data to get the entire record\n var b = c.input;\n var len = b.length();\n if(len < c.record.length) {\n // not enough data yet, return how much is required\n rval = c.record.length - len;\n } else {\n // there is enough data to parse the pending record\n // fill record fragment and compact input buffer\n c.record.fragment.putBytes(b.getBytes(c.record.length));\n b.compact();\n\n // update record using current read state\n var s = c.state.current.read;\n if(s.update(c, c.record)) {\n // see if there is a previously fragmented message that the\n // new record's message fragment should be appended to\n if(c.fragmented !== null) {\n // if the record type matches a previously fragmented\n // record, append the record fragment to it\n if(c.fragmented.type === c.record.type) {\n // concatenate record fragments\n c.fragmented.fragment.putBuffer(c.record.fragment);\n c.record = c.fragmented;\n } else {\n // error, invalid fragmented record\n c.error(c, {\n message: 'Invalid fragmented record.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description:\n tls.Alert.Description.unexpected_message\n }\n });\n }\n }\n\n // record is now ready\n c.record.ready = true;\n }\n }\n\n return rval;\n };\n\n /**\n * Performs a handshake using the TLS Handshake Protocol, as a client.\n *\n * This method should only be called if the connection is in client mode.\n *\n * @param sessionId the session ID to use, null to start a new one.\n */\n c.handshake = function(sessionId) {\n // error to call this in non-client mode\n if(c.entity !== tls.ConnectionEnd.client) {\n // not fatal error\n c.error(c, {\n message: 'Cannot initiate handshake as a server.',\n fatal: false\n });\n } else if(c.handshaking) {\n // handshake is already in progress, fail but not fatal error\n c.error(c, {\n message: 'Handshake already in progress.',\n fatal: false\n });\n } else {\n // clear fail flag on reuse\n if(c.fail && !c.open && c.handshakes === 0) {\n c.fail = false;\n }\n\n // now handshaking\n c.handshaking = true;\n\n // default to blank (new session)\n sessionId = sessionId || '';\n\n // if a session ID was specified, try to find it in the cache\n var session = null;\n if(sessionId.length > 0) {\n if(c.sessionCache) {\n session = c.sessionCache.getSession(sessionId);\n }\n\n // matching session not found in cache, clear session ID\n if(session === null) {\n sessionId = '';\n }\n }\n\n // no session given, grab a session from the cache, if available\n if(sessionId.length === 0 && c.sessionCache) {\n session = c.sessionCache.getSession();\n if(session !== null) {\n sessionId = session.id;\n }\n }\n\n // set up session\n c.session = {\n id: sessionId,\n version: null,\n cipherSuite: null,\n compressionMethod: null,\n serverCertificate: null,\n certificateRequest: null,\n clientCertificate: null,\n sp: {},\n md5: forge.md.md5.create(),\n sha1: forge.md.sha1.create()\n };\n\n // use existing session information\n if(session) {\n // only update version on connection, session version not yet set\n c.version = session.version;\n c.session.sp = session.sp;\n }\n\n // generate new client random\n c.session.sp.client_random = tls.createRandom().getBytes();\n\n // connection now open\n c.open = true;\n\n // send hello\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createClientHello(c)\n }));\n tls.flush(c);\n }\n };\n\n /**\n * Called when TLS protocol data has been received from somewhere and should\n * be processed by the TLS engine.\n *\n * @param data the TLS protocol data, as a string, to process.\n *\n * @return 0 if the data could be processed, otherwise the number of bytes\n * required for data to be processed.\n */\n c.process = function(data) {\n var rval = 0;\n\n // buffer input data\n if(data) {\n c.input.putBytes(data);\n }\n\n // process next record if no failure, process will be called after\n // each record is handled (since handling can be asynchronous)\n if(!c.fail) {\n // reset record if ready and now empty\n if(c.record !== null &&\n c.record.ready && c.record.fragment.isEmpty()) {\n c.record = null;\n }\n\n // if there is no pending record, try to read record header\n if(c.record === null) {\n rval = _readRecordHeader(c);\n }\n\n // read the next record (if record not yet ready)\n if(!c.fail && c.record !== null && !c.record.ready) {\n rval = _readRecord(c);\n }\n\n // record ready to be handled, update engine state\n if(!c.fail && c.record !== null && c.record.ready) {\n _update(c, c.record);\n }\n }\n\n return rval;\n };\n\n /**\n * Requests that application data be packaged into a TLS record. The\n * tlsDataReady handler will be called when the TLS record(s) have been\n * prepared.\n *\n * @param data the application data, as a raw 'binary' encoded string, to\n * be sent; to send utf-16/utf-8 string data, use the return value\n * of util.encodeUtf8(str).\n *\n * @return true on success, false on failure.\n */\n c.prepare = function(data) {\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.application_data,\n data: forge.util.createBuffer(data)\n }));\n return tls.flush(c);\n };\n\n /**\n * Requests that a heartbeat request be packaged into a TLS record for\n * transmission. The tlsDataReady handler will be called when TLS record(s)\n * have been prepared.\n *\n * When a heartbeat response has been received, the heartbeatReceived\n * handler will be called with the matching payload. This handler can\n * be used to clear a retransmission timer, etc.\n *\n * @param payload the heartbeat data to send as the payload in the message.\n * @param [payloadLength] the payload length to use, defaults to the\n * actual payload length.\n *\n * @return true on success, false on failure.\n */\n c.prepareHeartbeatRequest = function(payload, payloadLength) {\n if(payload instanceof forge.util.ByteBuffer) {\n payload = payload.bytes();\n }\n if(typeof payloadLength === 'undefined') {\n payloadLength = payload.length;\n }\n c.expectedHeartbeatPayload = payload;\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.heartbeat,\n data: tls.createHeartbeat(\n tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength)\n }));\n return tls.flush(c);\n };\n\n /**\n * Closes the connection (sends a close_notify alert).\n *\n * @param clearFail true to clear the fail flag (default: true).\n */\n c.close = function(clearFail) {\n // save session if connection didn't fail\n if(!c.fail && c.sessionCache && c.session) {\n // only need to preserve session ID, version, and security params\n var session = {\n id: c.session.id,\n version: c.session.version,\n sp: c.session.sp\n };\n session.sp.keys = null;\n c.sessionCache.setSession(session.id, session);\n }\n\n if(c.open) {\n // connection no longer open, clear input\n c.open = false;\n c.input.clear();\n\n // if connected or handshaking, send an alert\n if(c.isConnected || c.handshaking) {\n c.isConnected = c.handshaking = false;\n\n // send close_notify alert\n tls.queue(c, tls.createAlert(c, {\n level: tls.Alert.Level.warning,\n description: tls.Alert.Description.close_notify\n }));\n tls.flush(c);\n }\n\n // call handler\n c.closed(c);\n }\n\n // reset TLS connection, do not clear fail flag\n c.reset(clearFail);\n };\n\n return c;\n};\n\n/* TLS API */\nmodule.exports = forge.tls = forge.tls || {};\n\n// expose non-functions\nfor(var key in tls) {\n if(typeof tls[key] !== 'function') {\n forge.tls[key] = tls[key];\n }\n}\n\n// expose prf_tls1 for testing\nforge.tls.prf_tls1 = prf_TLS1;\n\n// expose sha1 hmac method\nforge.tls.hmac_sha1 = hmac_sha1;\n\n// expose session cache creation\nforge.tls.createSessionCache = tls.createSessionCache;\n\n/**\n * Creates a new TLS connection. This does not make any assumptions about the\n * transport layer that TLS is working on top of, ie: it does not assume there\n * is a TCP/IP connection or establish one. A TLS connection is totally\n * abstracted away from the layer is runs on top of, it merely establishes a\n * secure channel between a client\" and a \"server\".\n *\n * A TLS connection contains 4 connection states: pending read and write, and\n * current read and write.\n *\n * At initialization, the current read and write states will be null. Only once\n * the security parameters have been set and the keys have been generated can\n * the pending states be converted into current states. Current states will be\n * updated for each record processed.\n *\n * A custom certificate verify callback may be provided to check information\n * like the common name on the server's certificate. It will be called for\n * every certificate in the chain. It has the following signature:\n *\n * variable func(c, certs, index, preVerify)\n * Where:\n * c The TLS connection\n * verified Set to true if certificate was verified, otherwise the alert\n * tls.Alert.Description for why the certificate failed.\n * depth The current index in the chain, where 0 is the server's cert.\n * certs The certificate chain, *NOTE* if the server was anonymous then\n * the chain will be empty.\n *\n * The function returns true on success and on failure either the appropriate\n * tls.Alert.Description or an object with 'alert' set to the appropriate\n * tls.Alert.Description and 'message' set to a custom error message. If true\n * is not returned then the connection will abort using, in order of\n * availability, first the returned alert description, second the preVerify\n * alert description, and lastly the default 'bad_certificate'.\n *\n * There are three callbacks that can be used to make use of client-side\n * certificates where each takes the TLS connection as the first parameter:\n *\n * getCertificate(conn, hint)\n * The second parameter is a hint as to which certificate should be\n * returned. If the connection entity is a client, then the hint will be\n * the CertificateRequest message from the server that is part of the\n * TLS protocol. If the connection entity is a server, then it will be\n * the servername list provided via an SNI extension the ClientHello, if\n * one was provided (empty array if not). The hint can be examined to\n * determine which certificate to use (advanced). Most implementations\n * will just return a certificate. The return value must be a\n * PEM-formatted certificate or an array of PEM-formatted certificates\n * that constitute a certificate chain, with the first in the array/chain\n * being the client's certificate.\n * getPrivateKey(conn, certificate)\n * The second parameter is an forge.pki X.509 certificate object that\n * is associated with the requested private key. The return value must\n * be a PEM-formatted private key.\n * getSignature(conn, bytes, callback)\n * This callback can be used instead of getPrivateKey if the private key\n * is not directly accessible in javascript or should not be. For\n * instance, a secure external web service could provide the signature\n * in exchange for appropriate credentials. The second parameter is a\n * string of bytes to be signed that are part of the TLS protocol. These\n * bytes are used to verify that the private key for the previously\n * provided client-side certificate is accessible to the client. The\n * callback is a function that takes 2 parameters, the TLS connection\n * and the RSA encrypted (signed) bytes as a string. This callback must\n * be called once the signature is ready.\n *\n * @param options the options for this connection:\n * server: true if the connection is server-side, false for client.\n * sessionId: a session ID to reuse, null for a new connection.\n * caStore: an array of certificates to trust.\n * sessionCache: a session cache to use.\n * cipherSuites: an optional array of cipher suites to use,\n * see tls.CipherSuites.\n * connected: function(conn) called when the first handshake completes.\n * virtualHost: the virtual server name to use in a TLS SNI extension.\n * verifyClient: true to require a client certificate in server mode,\n * 'optional' to request one, false not to (default: false).\n * verify: a handler used to custom verify certificates in the chain.\n * verifyOptions: an object with options for the certificate chain validation.\n * See documentation of pki.verifyCertificateChain for possible options.\n * verifyOptions.verify is ignored. If you wish to specify a verify handler\n * use the verify key.\n * getCertificate: an optional callback used to get a certificate or\n * a chain of certificates (as an array).\n * getPrivateKey: an optional callback used to get a private key.\n * getSignature: an optional callback used to get a signature.\n * tlsDataReady: function(conn) called when TLS protocol data has been\n * prepared and is ready to be used (typically sent over a socket\n * connection to its destination), read from conn.tlsData buffer.\n * dataReady: function(conn) called when application data has\n * been parsed from a TLS record and should be consumed by the\n * application, read from conn.data buffer.\n * closed: function(conn) called when the connection has been closed.\n * error: function(conn, error) called when there was an error.\n * deflate: function(inBytes) if provided, will deflate TLS records using\n * the deflate algorithm if the server supports it.\n * inflate: function(inBytes) if provided, will inflate TLS records using\n * the deflate algorithm if the server supports it.\n *\n * @return the new TLS connection.\n */\nforge.tls.createConnection = tls.createConnection;\n","/**\n * A Javascript implementation of AES Cipher Suites for TLS.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2015 Digital Bazaar, Inc.\n *\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./tls');\n\nvar tls = module.exports = forge.tls;\n\n/**\n * Supported cipher suites.\n */\ntls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = {\n id: [0x00, 0x2f],\n name: 'TLS_RSA_WITH_AES_128_CBC_SHA',\n initSecurityParameters: function(sp) {\n sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;\n sp.cipher_type = tls.CipherType.block;\n sp.enc_key_length = 16;\n sp.block_length = 16;\n sp.fixed_iv_length = 16;\n sp.record_iv_length = 16;\n sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;\n sp.mac_length = 20;\n sp.mac_key_length = 20;\n },\n initConnectionState: initConnectionState\n};\ntls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = {\n id: [0x00, 0x35],\n name: 'TLS_RSA_WITH_AES_256_CBC_SHA',\n initSecurityParameters: function(sp) {\n sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;\n sp.cipher_type = tls.CipherType.block;\n sp.enc_key_length = 32;\n sp.block_length = 16;\n sp.fixed_iv_length = 16;\n sp.record_iv_length = 16;\n sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;\n sp.mac_length = 20;\n sp.mac_key_length = 20;\n },\n initConnectionState: initConnectionState\n};\n\nfunction initConnectionState(state, c, sp) {\n var client = (c.entity === forge.tls.ConnectionEnd.client);\n\n // cipher setup\n state.read.cipherState = {\n init: false,\n cipher: forge.cipher.createDecipher('AES-CBC', client ?\n sp.keys.server_write_key : sp.keys.client_write_key),\n iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV\n };\n state.write.cipherState = {\n init: false,\n cipher: forge.cipher.createCipher('AES-CBC', client ?\n sp.keys.client_write_key : sp.keys.server_write_key),\n iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV\n };\n state.read.cipherFunction = decrypt_aes_cbc_sha1;\n state.write.cipherFunction = encrypt_aes_cbc_sha1;\n\n // MAC setup\n state.read.macLength = state.write.macLength = sp.mac_length;\n state.read.macFunction = state.write.macFunction = tls.hmac_sha1;\n}\n\n/**\n * Encrypts the TLSCompressed record into a TLSCipherText record using AES\n * in CBC mode.\n *\n * @param record the TLSCompressed record to encrypt.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nfunction encrypt_aes_cbc_sha1(record, s) {\n var rval = false;\n\n // append MAC to fragment, update sequence number\n var mac = s.macFunction(s.macKey, s.sequenceNumber, record);\n record.fragment.putBytes(mac);\n s.updateSequenceNumber();\n\n // TLS 1.1+ use an explicit IV every time to protect against CBC attacks\n var iv;\n if(record.version.minor === tls.Versions.TLS_1_0.minor) {\n // use the pre-generated IV when initializing for TLS 1.0, otherwise use\n // the residue from the previous encryption\n iv = s.cipherState.init ? null : s.cipherState.iv;\n } else {\n iv = forge.random.getBytesSync(16);\n }\n\n s.cipherState.init = true;\n\n // start cipher\n var cipher = s.cipherState.cipher;\n cipher.start({iv: iv});\n\n // TLS 1.1+ write IV into output\n if(record.version.minor >= tls.Versions.TLS_1_1.minor) {\n cipher.output.putBytes(iv);\n }\n\n // do encryption (default padding is appropriate)\n cipher.update(record.fragment);\n if(cipher.finish(encrypt_aes_cbc_sha1_padding)) {\n // set record fragment to encrypted output\n record.fragment = cipher.output;\n record.length = record.fragment.length();\n rval = true;\n }\n\n return rval;\n}\n\n/**\n * Handles padding for aes_cbc_sha1 in encrypt mode.\n *\n * @param blockSize the block size.\n * @param input the input buffer.\n * @param decrypt true in decrypt mode, false in encrypt mode.\n *\n * @return true on success, false on failure.\n */\nfunction encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) {\n /* The encrypted data length (TLSCiphertext.length) is one more than the sum\n of SecurityParameters.block_length, TLSCompressed.length,\n SecurityParameters.mac_length, and padding_length.\n\n The padding may be any length up to 255 bytes long, as long as it results in\n the TLSCiphertext.length being an integral multiple of the block length.\n Lengths longer than necessary might be desirable to frustrate attacks on a\n protocol based on analysis of the lengths of exchanged messages. Each uint8\n in the padding data vector must be filled with the padding length value.\n\n The padding length should be such that the total size of the\n GenericBlockCipher structure is a multiple of the cipher's block length.\n Legal values range from zero to 255, inclusive. This length specifies the\n length of the padding field exclusive of the padding_length field itself.\n\n This is slightly different from PKCS#7 because the padding value is 1\n less than the actual number of padding bytes if you include the\n padding_length uint8 itself as a padding byte. */\n if(!decrypt) {\n // get the number of padding bytes required to reach the blockSize and\n // subtract 1 for the padding value (to make room for the padding_length\n // uint8)\n var padding = blockSize - (input.length() % blockSize);\n input.fillWithByte(padding - 1, padding);\n }\n return true;\n}\n\n/**\n * Handles padding for aes_cbc_sha1 in decrypt mode.\n *\n * @param blockSize the block size.\n * @param output the output buffer.\n * @param decrypt true in decrypt mode, false in encrypt mode.\n *\n * @return true on success, false on failure.\n */\nfunction decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {\n var rval = true;\n if(decrypt) {\n /* The last byte in the output specifies the number of padding bytes not\n including itself. Each of the padding bytes has the same value as that\n last byte (known as the padding_length). Here we check all padding\n bytes to ensure they have the value of padding_length even if one of\n them is bad in order to ward-off timing attacks. */\n var len = output.length();\n var paddingLength = output.last();\n for(var i = len - 1 - paddingLength; i < len - 1; ++i) {\n rval = rval && (output.at(i) == paddingLength);\n }\n if(rval) {\n // trim off padding bytes and last padding length byte\n output.truncate(paddingLength + 1);\n }\n }\n return rval;\n}\n\n/**\n * Decrypts a TLSCipherText record into a TLSCompressed record using\n * AES in CBC mode.\n *\n * @param record the TLSCipherText record to decrypt.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nfunction decrypt_aes_cbc_sha1(record, s) {\n var rval = false;\n\n var iv;\n if(record.version.minor === tls.Versions.TLS_1_0.minor) {\n // use pre-generated IV when initializing for TLS 1.0, otherwise use the\n // residue from the previous decryption\n iv = s.cipherState.init ? null : s.cipherState.iv;\n } else {\n // TLS 1.1+ use an explicit IV every time to protect against CBC attacks\n // that is appended to the record fragment\n iv = record.fragment.getBytes(16);\n }\n\n s.cipherState.init = true;\n\n // start cipher\n var cipher = s.cipherState.cipher;\n cipher.start({iv: iv});\n\n // do decryption\n cipher.update(record.fragment);\n rval = cipher.finish(decrypt_aes_cbc_sha1_padding);\n\n // even if decryption fails, keep going to minimize timing attacks\n\n // decrypted data:\n // first (len - 20) bytes = application data\n // last 20 bytes = MAC\n var macLen = s.macLength;\n\n // create a random MAC to check against should the mac length check fail\n // Note: do this regardless of the failure to keep timing consistent\n var mac = forge.random.getBytesSync(macLen);\n\n // get fragment and mac\n var len = cipher.output.length();\n if(len >= macLen) {\n record.fragment = cipher.output.getBytes(len - macLen);\n mac = cipher.output.getBytes(macLen);\n } else {\n // bad data, but get bytes anyway to try to keep timing consistent\n record.fragment = cipher.output.getBytes();\n }\n record.fragment = forge.util.createBuffer(record.fragment);\n record.length = record.fragment.length();\n\n // see if data integrity checks out, update sequence number\n var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record);\n s.updateSequenceNumber();\n rval = compareMacs(s.macKey, mac, mac2) && rval;\n return rval;\n}\n\n/**\n * Safely compare two MACs. This function will compare two MACs in a way\n * that protects against timing attacks.\n *\n * TODO: Expose elsewhere as a utility API.\n *\n * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/\n *\n * @param key the MAC key to use.\n * @param mac1 as a binary-encoded string of bytes.\n * @param mac2 as a binary-encoded string of bytes.\n *\n * @return true if the MACs are the same, false if not.\n */\nfunction compareMacs(key, mac1, mac2) {\n var hmac = forge.hmac.create();\n\n hmac.start('SHA1', key);\n hmac.update(mac1);\n mac1 = hmac.digest().getBytes();\n\n hmac.start(null, null);\n hmac.update(mac2);\n mac2 = hmac.digest().getBytes();\n\n return mac1 === mac2;\n}\n","/**\n * Debugging support for web applications.\n *\n * @author David I. Lehn \n *\n * Copyright 2008-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\n/* DEBUG API */\nmodule.exports = forge.debug = forge.debug || {};\n\n// Private storage for debugging.\n// Useful to expose data that is otherwise unviewable behind closures.\n// NOTE: remember that this can hold references to data and cause leaks!\n// format is \"forge._debug.. = data\"\n// Example:\n// (function() {\n// var cat = 'forge.test.Test'; // debugging category\n// var sState = {...}; // local state\n// forge.debug.set(cat, 'sState', sState);\n// })();\nforge.debug.storage = {};\n\n/**\n * Gets debug data. Omit name for all cat data Omit name and cat for\n * all data.\n *\n * @param cat name of debugging category.\n * @param name name of data to get (optional).\n * @return object with requested debug data or undefined.\n */\nforge.debug.get = function(cat, name) {\n var rval;\n if(typeof(cat) === 'undefined') {\n rval = forge.debug.storage;\n } else if(cat in forge.debug.storage) {\n if(typeof(name) === 'undefined') {\n rval = forge.debug.storage[cat];\n } else {\n rval = forge.debug.storage[cat][name];\n }\n }\n return rval;\n};\n\n/**\n * Sets debug data.\n *\n * @param cat name of debugging category.\n * @param name name of data to set.\n * @param data data to set.\n */\nforge.debug.set = function(cat, name, data) {\n if(!(cat in forge.debug.storage)) {\n forge.debug.storage[cat] = {};\n }\n forge.debug.storage[cat][name] = data;\n};\n\n/**\n * Clears debug data. Omit name for all cat data. Omit name and cat for\n * all data.\n *\n * @param cat name of debugging category.\n * @param name name of data to clear or omit to clear entire category.\n */\nforge.debug.clear = function(cat, name) {\n if(typeof(cat) === 'undefined') {\n forge.debug.storage = {};\n } else if(cat in forge.debug.storage) {\n if(typeof(name) === 'undefined') {\n delete forge.debug.storage[cat];\n } else {\n delete forge.debug.storage[cat][name];\n }\n }\n};\n","/**\n * Secure Hash Algorithm with a 1024-bit block size implementation.\n *\n * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For\n * SHA-256 (block size 512 bits), see sha256.js.\n *\n * See FIPS 180-4 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha512 = module.exports = forge.sha512 = forge.sha512 || {};\n\n// SHA-512\nforge.md.sha512 = forge.md.algorithms.sha512 = sha512;\n\n// SHA-384\nvar sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};\nsha384.create = function() {\n return sha512.create('SHA-384');\n};\nforge.md.sha384 = forge.md.algorithms.sha384 = sha384;\n\n// SHA-512/256\nforge.sha512.sha256 = forge.sha512.sha256 || {\n create: function() {\n return sha512.create('SHA-512/256');\n }\n};\nforge.md['sha512/256'] = forge.md.algorithms['sha512/256'] =\n forge.sha512.sha256;\n\n// SHA-512/224\nforge.sha512.sha224 = forge.sha512.sha224 || {\n create: function() {\n return sha512.create('SHA-512/224');\n }\n};\nforge.md['sha512/224'] = forge.md.algorithms['sha512/224'] =\n forge.sha512.sha224;\n\n/**\n * Creates a SHA-2 message digest object.\n *\n * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,\n * SHA-512/256).\n *\n * @return a message digest object.\n */\nsha512.create = function(algorithm) {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n if(typeof algorithm === 'undefined') {\n algorithm = 'SHA-512';\n }\n\n if(!(algorithm in _states)) {\n throw new Error('Invalid SHA-512 algorithm: ' + algorithm);\n }\n\n // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)\n var _state = _states[algorithm];\n var _h = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for 64-bit word storage\n var _w = new Array(80);\n for(var wi = 0; wi < 80; ++wi) {\n _w[wi] = new Array(2);\n }\n\n // determine digest length by algorithm name (default)\n var digestLength = 64;\n switch(algorithm) {\n case 'SHA-384':\n digestLength = 48;\n break;\n case 'SHA-512/256':\n digestLength = 32;\n break;\n case 'SHA-512/224':\n digestLength = 28;\n break;\n }\n\n // message digest object\n var md = {\n // SHA-512 => sha512\n algorithm: algorithm.replace('-', '').toLowerCase(),\n blockLength: 128,\n digestLength: digestLength,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 16\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength128 for backwards-compatibility)\n md.fullMessageLength = md.messageLength128 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _h = new Array(_state.length);\n for(var i = 0; i < _state.length; ++i) {\n _h[i] = _state[i].slice(0);\n }\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_h, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-512 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 896 mod 1024. In other words,\n the data to be digested must be a multiple of 1024 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 16 bytes (128\n bits), that means that the last segment of the data must have 112 bytes\n (896 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 896 mod 1024 because\n 1024 - 128 = 896.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 896 mod 1024, then 1024 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var h = new Array(_h.length);\n for(var i = 0; i < _h.length; ++i) {\n h[i] = _h[i].slice(0);\n }\n _update(h, _w, finalBlock);\n var rval = forge.util.createBuffer();\n var hlen;\n if(algorithm === 'SHA-512') {\n hlen = h.length;\n } else if(algorithm === 'SHA-384') {\n hlen = h.length - 2;\n } else {\n hlen = h.length - 4;\n }\n for(var i = 0; i < hlen; ++i) {\n rval.putInt32(h[i][0]);\n if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {\n rval.putInt32(h[i][1]);\n }\n }\n return rval;\n };\n\n return md;\n};\n\n// sha-512 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n// initial hash states\nvar _states = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 128);\n\n // create K table for SHA-512\n _k = [\n [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd],\n [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc],\n [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019],\n [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118],\n [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe],\n [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2],\n [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1],\n [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694],\n [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3],\n [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65],\n [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483],\n [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5],\n [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210],\n [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4],\n [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725],\n [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70],\n [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926],\n [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df],\n [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8],\n [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b],\n [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001],\n [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30],\n [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910],\n [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8],\n [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53],\n [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8],\n [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb],\n [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3],\n [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60],\n [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec],\n [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9],\n [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b],\n [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207],\n [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178],\n [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6],\n [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b],\n [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493],\n [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c],\n [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a],\n [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817]\n ];\n\n // initial hash states\n _states = {};\n _states['SHA-512'] = [\n [0x6a09e667, 0xf3bcc908],\n [0xbb67ae85, 0x84caa73b],\n [0x3c6ef372, 0xfe94f82b],\n [0xa54ff53a, 0x5f1d36f1],\n [0x510e527f, 0xade682d1],\n [0x9b05688c, 0x2b3e6c1f],\n [0x1f83d9ab, 0xfb41bd6b],\n [0x5be0cd19, 0x137e2179]\n ];\n _states['SHA-384'] = [\n [0xcbbb9d5d, 0xc1059ed8],\n [0x629a292a, 0x367cd507],\n [0x9159015a, 0x3070dd17],\n [0x152fecd8, 0xf70e5939],\n [0x67332667, 0xffc00b31],\n [0x8eb44a87, 0x68581511],\n [0xdb0c2e0d, 0x64f98fa7],\n [0x47b5481d, 0xbefa4fa4]\n ];\n _states['SHA-512/256'] = [\n [0x22312194, 0xFC2BF72C],\n [0x9F555FA3, 0xC84C64C2],\n [0x2393B86B, 0x6F53B151],\n [0x96387719, 0x5940EABD],\n [0x96283EE2, 0xA88EFFE3],\n [0xBE5E1E25, 0x53863992],\n [0x2B0199FC, 0x2C85B8AA],\n [0x0EB72DDC, 0x81C52CA2]\n ];\n _states['SHA-512/224'] = [\n [0x8C3D37C8, 0x19544DA2],\n [0x73E19966, 0x89DCD4D6],\n [0x1DFAB7AE, 0x32FF9C82],\n [0x679DD514, 0x582F9FCF],\n [0x0F6D2B69, 0x7BD44DA8],\n [0x77E36F73, 0x04C48942],\n [0x3F9D85A8, 0x6A1D36C8],\n [0x1112E6AD, 0x91D692A1]\n ];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-512 state with the given byte buffer.\n *\n * @param s the SHA-512 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (128 byte) chunks\n var t1_hi, t1_lo;\n var t2_hi, t2_lo;\n var s0_hi, s0_lo;\n var s1_hi, s1_lo;\n var ch_hi, ch_lo;\n var maj_hi, maj_lo;\n var a_hi, a_lo;\n var b_hi, b_lo;\n var c_hi, c_lo;\n var d_hi, d_lo;\n var e_hi, e_lo;\n var f_hi, f_lo;\n var g_hi, g_lo;\n var h_hi, h_lo;\n var i, hi, lo, w2, w7, w15, w16;\n var len = bytes.length();\n while(len >= 128) {\n // the w array will be populated with sixteen 64-bit big-endian words\n // and then extended into 64 64-bit words according to SHA-512\n for(i = 0; i < 16; ++i) {\n w[i][0] = bytes.getInt32() >>> 0;\n w[i][1] = bytes.getInt32() >>> 0;\n }\n for(; i < 80; ++i) {\n // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)\n w2 = w[i - 2];\n hi = w2[0];\n lo = w2[1];\n\n // high bits\n t1_hi = (\n ((hi >>> 19) | (lo << 13)) ^ // ROTR 19\n ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)\n (hi >>> 6)) >>> 0; // SHR 6\n // low bits\n t1_lo = (\n ((hi << 13) | (lo >>> 19)) ^ // ROTR 19\n ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)\n ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6\n\n // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)\n w15 = w[i - 15];\n hi = w15[0];\n lo = w15[1];\n\n // high bits\n t2_hi = (\n ((hi >>> 1) | (lo << 31)) ^ // ROTR 1\n ((hi >>> 8) | (lo << 24)) ^ // ROTR 8\n (hi >>> 7)) >>> 0; // SHR 7\n // low bits\n t2_lo = (\n ((hi << 31) | (lo >>> 1)) ^ // ROTR 1\n ((hi << 24) | (lo >>> 8)) ^ // ROTR 8\n ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7\n\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)\n w7 = w[i - 7];\n w16 = w[i - 16];\n lo = (t1_lo + w7[1] + t2_lo + w16[1]);\n w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n w[i][1] = lo >>> 0;\n }\n\n // initialize hash value for this chunk\n a_hi = s[0][0];\n a_lo = s[0][1];\n b_hi = s[1][0];\n b_lo = s[1][1];\n c_hi = s[2][0];\n c_lo = s[2][1];\n d_hi = s[3][0];\n d_lo = s[3][1];\n e_hi = s[4][0];\n e_lo = s[4][1];\n f_hi = s[5][0];\n f_lo = s[5][1];\n g_hi = s[6][0];\n g_lo = s[6][1];\n h_hi = s[7][0];\n h_lo = s[7][1];\n\n // round function\n for(i = 0; i < 80; ++i) {\n // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)\n s1_hi = (\n ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14\n ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18\n ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)\n s1_lo = (\n ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14\n ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18\n ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)\n\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;\n ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;\n\n // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)\n s0_hi = (\n ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28\n ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)\n s0_lo = (\n ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28\n ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)\n\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;\n maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;\n\n // main algorithm\n // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)\n lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);\n t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n t1_lo = lo >>> 0;\n\n // t2 = s0 + maj modulo 2^64 (carry lo overflow)\n lo = s0_lo + maj_lo;\n t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n t2_lo = lo >>> 0;\n\n h_hi = g_hi;\n h_lo = g_lo;\n\n g_hi = f_hi;\n g_lo = f_lo;\n\n f_hi = e_hi;\n f_lo = e_lo;\n\n // e = (d + t1) modulo 2^64 (carry lo overflow)\n lo = d_lo + t1_lo;\n e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n e_lo = lo >>> 0;\n\n d_hi = c_hi;\n d_lo = c_lo;\n\n c_hi = b_hi;\n c_lo = b_lo;\n\n b_hi = a_hi;\n b_lo = a_lo;\n\n // a = (t1 + t2) modulo 2^64 (carry lo overflow)\n lo = t1_lo + t2_lo;\n a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n a_lo = lo >>> 0;\n }\n\n // update hash state (additional modulo 2^64)\n lo = s[0][1] + a_lo;\n s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[0][1] = lo >>> 0;\n\n lo = s[1][1] + b_lo;\n s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[1][1] = lo >>> 0;\n\n lo = s[2][1] + c_lo;\n s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[2][1] = lo >>> 0;\n\n lo = s[3][1] + d_lo;\n s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[3][1] = lo >>> 0;\n\n lo = s[4][1] + e_lo;\n s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[4][1] = lo >>> 0;\n\n lo = s[5][1] + f_lo;\n s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[5][1] = lo >>> 0;\n\n lo = s[6][1] + g_lo;\n s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[6][1] = lo >>> 0;\n\n lo = s[7][1] + h_lo;\n s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[7][1] = lo >>> 0;\n\n len -= 128;\n }\n}\n","/**\n * Copyright (c) 2019 Digital Bazaar, Inc.\n */\n\nvar forge = require('./forge');\nrequire('./asn1');\nvar asn1 = forge.asn1;\n\nexports.privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\nexports.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n },\n // capture group for ed25519PublicKey\n {\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n composed: true,\n captureBitStringValue: 'ed25519PublicKey'\n }\n // FIXME: this is capture group for rsaPublicKey, use it in this API or\n // discard?\n /* {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n } */\n ]\n};\n","/**\n * JavaScript implementation of Ed25519.\n *\n * Copyright (c) 2017-2019 Digital Bazaar, Inc.\n *\n * This implementation is based on the most excellent TweetNaCl which is\n * in the public domain. Many thanks to its contributors:\n *\n * https://github.com/dchest/tweetnacl-js\n */\nvar forge = require('./forge');\nrequire('./jsbn');\nrequire('./random');\nrequire('./sha512');\nrequire('./util');\nvar asn1Validator = require('./asn1-validator');\nvar publicKeyValidator = asn1Validator.publicKeyValidator;\nvar privateKeyValidator = asn1Validator.privateKeyValidator;\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar ByteBuffer = forge.util.ByteBuffer;\nvar NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer;\n\n/*\n * Ed25519 algorithms, see RFC 8032:\n * https://tools.ietf.org/html/rfc8032\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {};\nvar ed25519 = forge.ed25519;\n\ned25519.constants = {};\ned25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32;\ned25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64;\ned25519.constants.SEED_BYTE_LENGTH = 32;\ned25519.constants.SIGN_BYTE_LENGTH = 64;\ned25519.constants.HASH_BYTE_LENGTH = 64;\n\ned25519.generateKeyPair = function(options) {\n options = options || {};\n var seed = options.seed;\n if(seed === undefined) {\n // generate seed\n seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);\n } else if(typeof seed === 'string') {\n if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) {\n throw new TypeError(\n '\"seed\" must be ' + ed25519.constants.SEED_BYTE_LENGTH +\n ' bytes in length.');\n }\n } else if(!(seed instanceof Uint8Array)) {\n throw new TypeError(\n '\"seed\" must be a node.js Buffer, Uint8Array, or a binary string.');\n }\n\n seed = messageToNativeBuffer({message: seed, encoding: 'binary'});\n\n var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n for(var i = 0; i < 32; ++i) {\n sk[i] = seed[i];\n }\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, privateKey: sk};\n};\n\n/**\n * Converts a private key from a RFC8410 ASN.1 encoding.\n *\n * @param obj - The asn1 representation of a private key.\n *\n * @returns {Object} keyInfo - The key information.\n * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes.\n */\ned25519.privateKeyFromAsn1 = function(obj) {\n var capture = {};\n var errors = [];\n var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors);\n if(!valid) {\n var error = new Error('Invalid Key.');\n error.errors = errors;\n throw error;\n }\n var oid = forge.asn1.derToOid(capture.privateKeyOid);\n var ed25519Oid = forge.oids.EdDSA25519;\n if(oid !== ed25519Oid) {\n throw new Error('Invalid OID \"' + oid + '\"; OID must be \"' +\n ed25519Oid + '\".');\n }\n var privateKey = capture.privateKey;\n // manually extract the private key bytes from nested octet string, see FIXME:\n // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542\n var privateKeyBytes = messageToNativeBuffer({\n message: forge.asn1.fromDer(privateKey).value,\n encoding: 'binary'\n });\n // TODO: RFC8410 specifies a format for encoding the public key bytes along\n // with the private key bytes. `publicKeyBytes` can be returned in the\n // future. https://tools.ietf.org/html/rfc8410#section-10.3\n return {privateKeyBytes: privateKeyBytes};\n};\n\n/**\n * Converts a public key from a RFC8410 ASN.1 encoding.\n *\n * @param obj - The asn1 representation of a public key.\n *\n * @return {Buffer|Uint8Array} - 32 public key bytes.\n */\ned25519.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors);\n if(!valid) {\n var error = new Error('Invalid Key.');\n error.errors = errors;\n throw error;\n }\n var oid = forge.asn1.derToOid(capture.publicKeyOid);\n var ed25519Oid = forge.oids.EdDSA25519;\n if(oid !== ed25519Oid) {\n throw new Error('Invalid OID \"' + oid + '\"; OID must be \"' +\n ed25519Oid + '\".');\n }\n var publicKeyBytes = capture.ed25519PublicKey;\n if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {\n throw new Error('Key length is invalid.');\n }\n return messageToNativeBuffer({\n message: publicKeyBytes,\n encoding: 'binary'\n });\n};\n\ned25519.publicKeyFromPrivateKey = function(options) {\n options = options || {};\n var privateKey = messageToNativeBuffer({\n message: options.privateKey, encoding: 'binary'\n });\n if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.privateKey\" must have a byte length of ' +\n ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n }\n\n var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n for(var i = 0; i < pk.length; ++i) {\n pk[i] = privateKey[32 + i];\n }\n return pk;\n};\n\ned25519.sign = function(options) {\n options = options || {};\n var msg = messageToNativeBuffer(options);\n var privateKey = messageToNativeBuffer({\n message: options.privateKey,\n encoding: 'binary'\n });\n if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) {\n var keyPair = ed25519.generateKeyPair({seed: privateKey});\n privateKey = keyPair.privateKey;\n } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.privateKey\" must have a byte length of ' +\n ed25519.constants.SEED_BYTE_LENGTH + ' or ' +\n ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n }\n\n var signedMsg = new NativeBuffer(\n ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n crypto_sign(signedMsg, msg, msg.length, privateKey);\n\n var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);\n for(var i = 0; i < sig.length; ++i) {\n sig[i] = signedMsg[i];\n }\n return sig;\n};\n\ned25519.verify = function(options) {\n options = options || {};\n var msg = messageToNativeBuffer(options);\n if(options.signature === undefined) {\n throw new TypeError(\n '\"options.signature\" must be a node.js Buffer, a Uint8Array, a forge ' +\n 'ByteBuffer, or a binary string.');\n }\n var sig = messageToNativeBuffer({\n message: options.signature,\n encoding: 'binary'\n });\n if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.signature\" must have a byte length of ' +\n ed25519.constants.SIGN_BYTE_LENGTH);\n }\n var publicKey = messageToNativeBuffer({\n message: options.publicKey,\n encoding: 'binary'\n });\n if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.publicKey\" must have a byte length of ' +\n ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n }\n\n var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n var i;\n for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) {\n sm[i] = sig[i];\n }\n for(i = 0; i < msg.length; ++i) {\n sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i];\n }\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nfunction messageToNativeBuffer(options) {\n var message = options.message;\n if(message instanceof Uint8Array || message instanceof NativeBuffer) {\n return message;\n }\n\n var encoding = options.encoding;\n if(message === undefined) {\n if(options.md) {\n // TODO: more rigorous validation that `md` is a MessageDigest\n message = options.md.digest().getBytes();\n encoding = 'binary';\n } else {\n throw new TypeError('\"options.message\" or \"options.md\" not specified.');\n }\n }\n\n if(typeof message === 'string' && !encoding) {\n throw new TypeError('\"options.encoding\" must be \"binary\" or \"utf8\".');\n }\n\n if(typeof message === 'string') {\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(message, encoding);\n }\n message = new ByteBuffer(message, encoding);\n } else if(!(message instanceof ByteBuffer)) {\n throw new TypeError(\n '\"options.message\" must be a node.js Buffer, a Uint8Array, a forge ' +\n 'ByteBuffer, or a string with \"options.encoding\" specifying its ' +\n 'encoding.');\n }\n\n // convert to native buffer\n var buffer = new NativeBuffer(message.length());\n for(var i = 0; i < buffer.length; ++i) {\n buffer[i] = message.at(i);\n }\n return buffer;\n}\n\nvar gf0 = gf();\nvar gf1 = gf([1]);\nvar D = gf([\n 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,\n 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]);\nvar D2 = gf([\n 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,\n 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]);\nvar X = gf([\n 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,\n 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]);\nvar Y = gf([\n 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,\n 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]);\nvar L = new Float64Array([\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,\n 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\nvar I = gf([\n 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,\n 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\n// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`,\n// whichever is available, to improve performance\nfunction sha512(msg, msgLen) {\n // Note: `out` and `msg` are NativeBuffer\n var md = forge.md.sha512.create();\n var buffer = new ByteBuffer(msg);\n md.update(buffer.getBytes(msgLen), 'binary');\n var hash = md.digest().getBytes();\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(hash, 'binary');\n }\n var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);\n for(var i = 0; i < 64; ++i) {\n out[i] = hash.charCodeAt(i);\n }\n return out;\n}\n\nfunction crypto_sign_keypair(pk, sk) {\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n var d = sha512(sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for(i = 0; i < 32; ++i) {\n sk[i + 32] = pk[i];\n }\n return 0;\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n var d = sha512(sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for(i = 0; i < n; ++i) {\n sm[64 + i] = m[i];\n }\n for(i = 0; i < 32; ++i) {\n sm[32 + i] = d[32 + i];\n }\n\n var r = sha512(sm.subarray(32), n + 32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for(i = 32; i < 64; ++i) {\n sm[i] = sk[i];\n }\n var h = sha512(sm, n + 64);\n reduce(h);\n\n for(i = 32; i < 64; ++i) {\n x[i] = 0;\n }\n for(i = 0; i < 32; ++i) {\n x[i] = r[i];\n }\n for(i = 0; i < 32; ++i) {\n for(j = 0; j < 32; j++) {\n x[i + j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i, mlen;\n var t = new NativeBuffer(32);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n mlen = -1;\n if(n < 64) {\n return -1;\n }\n\n if(unpackneg(q, pk)) {\n return -1;\n }\n\n for(i = 0; i < n; ++i) {\n m[i] = sm[i];\n }\n for(i = 0; i < 32; ++i) {\n m[i + 32] = pk[i];\n }\n var h = sha512(m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if(crypto_verify_32(sm, 0, t, 0)) {\n for(i = 0; i < n; ++i) {\n m[i] = 0;\n }\n return -1;\n }\n\n for(i = 0; i < n; ++i) {\n m[i] = sm[i + 64];\n }\n mlen = n;\n return mlen;\n}\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for(i = 63; i >= 32; --i) {\n carry = 0;\n for(j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = (x[j] + 128) >> 8;\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for(j = 0; j < 32; ++j) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for(j = 0; j < 32; ++j) {\n x[j] -= carry * L[j];\n }\n for(i = 0; i < 32; ++i) {\n x[i + 1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64);\n for(var i = 0; i < 64; ++i) {\n x[i] = r[i];\n r[i] = 0;\n }\n modL(r, x);\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n for(var i = 0; i < 4; ++i) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for(i = 0; i < 16; ++i) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for(j = 0; j < 2; ++j) {\n m[0] = t[0] - 0xffed;\n for(i = 1; i < 15; ++i) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if(neq25519(chk, num)) {\n M(r[0], r[0], I);\n }\n\n S(chk, r[0]);\n M(chk, chk, den);\n if(neq25519(chk, num)) {\n return -1;\n }\n\n if(par25519(r[0]) === (p[31] >> 7)) {\n Z(r[0], gf0, r[0]);\n }\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for(i = 0; i < 16; ++i) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for(a = 0; a < 16; ++a) {\n c[a] = i[a];\n }\n for(a = 250; a >= 0; --a) {\n S(c, c);\n if(a !== 1) {\n M(c, c, i);\n }\n }\n for(a = 0; a < 16; ++a) {\n o[a] = c[a];\n }\n}\n\nfunction neq25519(a, b) {\n var c = new NativeBuffer(32);\n var d = new NativeBuffer(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x, xi, y, yi, 32);\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i, d = 0;\n for(i = 0; i < n; ++i) {\n d |= x[xi + i] ^ y[yi + i];\n }\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction par25519(a) {\n var d = new NativeBuffer(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for(i = 255; i >= 0; --i) {\n b = (s[(i / 8)|0] >> (i & 7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction set25519(r, a) {\n var i;\n for(i = 0; i < 16; i++) {\n r[i] = a[i] | 0;\n }\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for(a = 0; a < 16; ++a) {\n c[a] = i[a];\n }\n for(a = 253; a >= 0; --a) {\n S(c, c);\n if(a !== 2 && a !== 4) {\n M(c, c, i);\n }\n }\n for(a = 0; a < 16; ++a) {\n o[a] = c[a];\n }\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for(i = 0; i < 16; ++i) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b - 1);\n for(var i = 0; i < 16; ++i) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction gf(init) {\n var i, r = new Float64Array(16);\n if(init) {\n for(i = 0; i < init.length; ++i) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\nfunction A(o, a, b) {\n for(var i = 0; i < 16; ++i) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction Z(o, a, b) {\n for(var i = 0; i < 16; ++i) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n","/**\n * Javascript implementation of RSA-KEM.\n *\n * @author Lautaro Cozzani Rodriguez\n * @author Dave Longley\n *\n * Copyright (c) 2014 Lautaro Cozzani \n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./jsbn');\n\nmodule.exports = forge.kem = forge.kem || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n/**\n * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2.\n */\nforge.kem.rsa = {};\n\n/**\n * Creates an RSA KEM API object for generating a secret asymmetric key.\n *\n * The symmetric key may be generated via a call to 'encrypt', which will\n * produce a ciphertext to be transmitted to the recipient and a key to be\n * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which\n * will produce the same secret key for the recipient to use to decrypt a\n * message that was encrypted with the secret key.\n *\n * @param kdf the KDF API to use (eg: new forge.kem.kdf1()).\n * @param options the options to use.\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n */\nforge.kem.rsa.create = function(kdf, options) {\n options = options || {};\n var prng = options.prng || forge.random;\n\n var kem = {};\n\n /**\n * Generates a secret key and its encapsulation.\n *\n * @param publicKey the RSA public key to encrypt with.\n * @param keyLength the length, in bytes, of the secret key to generate.\n *\n * @return an object with:\n * encapsulation: the ciphertext for generating the secret key, as a\n * binary-encoded string of bytes.\n * key: the secret key to use for encrypting a message.\n */\n kem.encrypt = function(publicKey, keyLength) {\n // generate a random r where 1 < r < n\n var byteLength = Math.ceil(publicKey.n.bitLength() / 8);\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(prng.getBytesSync(byteLength)),\n 16).mod(publicKey.n);\n } while(r.compareTo(BigInteger.ONE) <= 0);\n\n // prepend r with zeros\n r = forge.util.hexToBytes(r.toString(16));\n var zeros = byteLength - r.length;\n if(zeros > 0) {\n r = forge.util.fillString(String.fromCharCode(0), zeros) + r;\n }\n\n // encrypt the random\n var encapsulation = publicKey.encrypt(r, 'NONE');\n\n // generate the secret key\n var key = kdf.generate(r, keyLength);\n\n return {encapsulation: encapsulation, key: key};\n };\n\n /**\n * Decrypts an encapsulated secret key.\n *\n * @param privateKey the RSA private key to decrypt with.\n * @param encapsulation the ciphertext for generating the secret key, as\n * a binary-encoded string of bytes.\n * @param keyLength the length, in bytes, of the secret key to generate.\n *\n * @return the secret key as a binary-encoded string of bytes.\n */\n kem.decrypt = function(privateKey, encapsulation, keyLength) {\n // decrypt the encapsulation and generate the secret key\n var r = privateKey.decrypt(encapsulation, 'NONE');\n return kdf.generate(r, keyLength);\n };\n\n return kem;\n};\n\n// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API?\n\n/**\n * Creates a key derivation API object that implements KDF1 per ISO 18033-2.\n *\n * @param md the hash API to use.\n * @param [digestLength] an optional digest length that must be positive and\n * less than or equal to md.digestLength.\n *\n * @return a KDF1 API object.\n */\nforge.kem.kdf1 = function(md, digestLength) {\n _createKDF(this, md, 0, digestLength || md.digestLength);\n};\n\n/**\n * Creates a key derivation API object that implements KDF2 per ISO 18033-2.\n *\n * @param md the hash API to use.\n * @param [digestLength] an optional digest length that must be positive and\n * less than or equal to md.digestLength.\n *\n * @return a KDF2 API object.\n */\nforge.kem.kdf2 = function(md, digestLength) {\n _createKDF(this, md, 1, digestLength || md.digestLength);\n};\n\n/**\n * Creates a KDF1 or KDF2 API object.\n *\n * @param md the hash API to use.\n * @param counterStart the starting index for the counter.\n * @param digestLength the digest length to use.\n *\n * @return the KDF API object.\n */\nfunction _createKDF(kdf, md, counterStart, digestLength) {\n /**\n * Generate a key of the specified length.\n *\n * @param x the binary-encoded byte string to generate a key from.\n * @param length the number of bytes to generate (the size of the key).\n *\n * @return the key as a binary-encoded string.\n */\n kdf.generate = function(x, length) {\n var key = new forge.util.ByteBuffer();\n\n // run counter from counterStart to ceil(length / Hash.len)\n var k = Math.ceil(length / digestLength) + counterStart;\n\n var c = new forge.util.ByteBuffer();\n for(var i = counterStart; i < k; ++i) {\n // I2OSP(i, 4): convert counter to an octet string of 4 octets\n c.putInt32(i);\n\n // digest 'x' and the counter and add the result to the key\n md.start();\n md.update(x + c.getBytes());\n var hash = md.digest();\n key.putBytes(hash.getBytes(digestLength));\n }\n\n // truncate to the correct key length\n key.truncate(key.length() - length);\n return key.getBytes();\n };\n}\n","/**\n * Cross-browser support for logging in a web application.\n *\n * @author David I. Lehn \n *\n * Copyright (c) 2008-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n/* LOG API */\nmodule.exports = forge.log = forge.log || {};\n\n/**\n * Application logging system.\n *\n * Each logger level available as it's own function of the form:\n * forge.log.level(category, args...)\n * The category is an arbitrary string, and the args are the same as\n * Firebug's console.log API. By default the call will be output as:\n * 'LEVEL [category] , args[1], ...'\n * This enables proper % formatting via the first argument.\n * Each category is enabled by default but can be enabled or disabled with\n * the setCategoryEnabled() function.\n */\n// list of known levels\nforge.log.levels = [\n 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max'];\n// info on the levels indexed by name:\n// index: level index\n// name: uppercased display name\nvar sLevelInfo = {};\n// list of loggers\nvar sLoggers = [];\n/**\n * Standard console logger. If no console support is enabled this will\n * remain null. Check before using.\n */\nvar sConsoleLogger = null;\n\n// logger flags\n/**\n * Lock the level at the current value. Used in cases where user config may\n * set the level such that only critical messages are seen but more verbose\n * messages are needed for debugging or other purposes.\n */\nforge.log.LEVEL_LOCKED = (1 << 1);\n/**\n * Always call log function. By default, the logging system will check the\n * message level against logger.level before calling the log function. This\n * flag allows the function to do its own check.\n */\nforge.log.NO_LEVEL_CHECK = (1 << 2);\n/**\n * Perform message interpolation with the passed arguments. \"%\" style\n * fields in log messages will be replaced by arguments as needed. Some\n * loggers, such as Firebug, may do this automatically. The original log\n * message will be available as 'message' and the interpolated version will\n * be available as 'fullMessage'.\n */\nforge.log.INTERPOLATE = (1 << 3);\n\n// setup each log level\nfor(var i = 0; i < forge.log.levels.length; ++i) {\n var level = forge.log.levels[i];\n sLevelInfo[level] = {\n index: i,\n name: level.toUpperCase()\n };\n}\n\n/**\n * Message logger. Will dispatch a message to registered loggers as needed.\n *\n * @param message message object\n */\nforge.log.logMessage = function(message) {\n var messageLevelIndex = sLevelInfo[message.level].index;\n for(var i = 0; i < sLoggers.length; ++i) {\n var logger = sLoggers[i];\n if(logger.flags & forge.log.NO_LEVEL_CHECK) {\n logger.f(message);\n } else {\n // get logger level\n var loggerLevelIndex = sLevelInfo[logger.level].index;\n // check level\n if(messageLevelIndex <= loggerLevelIndex) {\n // message critical enough, call logger\n logger.f(logger, message);\n }\n }\n }\n};\n\n/**\n * Sets the 'standard' key on a message object to:\n * \"LEVEL [category] \" + message\n *\n * @param message a message log object\n */\nforge.log.prepareStandard = function(message) {\n if(!('standard' in message)) {\n message.standard =\n sLevelInfo[message.level].name +\n //' ' + +message.timestamp +\n ' [' + message.category + '] ' +\n message.message;\n }\n};\n\n/**\n * Sets the 'full' key on a message object to the original message\n * interpolated via % formatting with the message arguments.\n *\n * @param message a message log object.\n */\nforge.log.prepareFull = function(message) {\n if(!('full' in message)) {\n // copy args and insert message at the front\n var args = [message.message];\n args = args.concat([] || message['arguments']);\n // format the message\n message.full = forge.util.format.apply(this, args);\n }\n};\n\n/**\n * Applies both preparseStandard() and prepareFull() to a message object and\n * store result in 'standardFull'.\n *\n * @param message a message log object.\n */\nforge.log.prepareStandardFull = function(message) {\n if(!('standardFull' in message)) {\n // FIXME implement 'standardFull' logging\n forge.log.prepareStandard(message);\n message.standardFull = message.standard;\n }\n};\n\n// create log level functions\nif(true) {\n // levels for which we want functions\n var levels = ['error', 'warning', 'info', 'debug', 'verbose'];\n for(var i = 0; i < levels.length; ++i) {\n // wrap in a function to ensure proper level var is passed\n (function(level) {\n // create function for this level\n forge.log[level] = function(category, message/*, args...*/) {\n // convert arguments to real array, remove category and message\n var args = Array.prototype.slice.call(arguments).slice(2);\n // create message object\n // Note: interpolation and standard formatting is done lazily\n var msg = {\n timestamp: new Date(),\n level: level,\n category: category,\n message: message,\n 'arguments': args\n /*standard*/\n /*full*/\n /*fullMessage*/\n };\n // process this message\n forge.log.logMessage(msg);\n };\n })(levels[i]);\n }\n}\n\n/**\n * Creates a new logger with specified custom logging function.\n *\n * The logging function has a signature of:\n * function(logger, message)\n * logger: current logger\n * message: object:\n * level: level id\n * category: category\n * message: string message\n * arguments: Array of extra arguments\n * fullMessage: interpolated message and arguments if INTERPOLATE flag set\n *\n * @param logFunction a logging function which takes a log message object\n * as a parameter.\n *\n * @return a logger object.\n */\nforge.log.makeLogger = function(logFunction) {\n var logger = {\n flags: 0,\n f: logFunction\n };\n forge.log.setLevel(logger, 'none');\n return logger;\n};\n\n/**\n * Sets the current log level on a logger.\n *\n * @param logger the target logger.\n * @param level the new maximum log level as a string.\n *\n * @return true if set, false if not.\n */\nforge.log.setLevel = function(logger, level) {\n var rval = false;\n if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) {\n for(var i = 0; i < forge.log.levels.length; ++i) {\n var aValidLevel = forge.log.levels[i];\n if(level == aValidLevel) {\n // set level\n logger.level = level;\n rval = true;\n break;\n }\n }\n }\n\n return rval;\n};\n\n/**\n * Locks the log level at its current value.\n *\n * @param logger the target logger.\n * @param lock boolean lock value, default to true.\n */\nforge.log.lock = function(logger, lock) {\n if(typeof lock === 'undefined' || lock) {\n logger.flags |= forge.log.LEVEL_LOCKED;\n } else {\n logger.flags &= ~forge.log.LEVEL_LOCKED;\n }\n};\n\n/**\n * Adds a logger.\n *\n * @param logger the logger object.\n */\nforge.log.addLogger = function(logger) {\n sLoggers.push(logger);\n};\n\n// setup the console logger if possible, else create fake console.log\nif(typeof(console) !== 'undefined' && 'log' in console) {\n var logger;\n if(console.error && console.warn && console.info && console.debug) {\n // looks like Firebug-style logging is available\n // level handlers map\n var levelHandlers = {\n error: console.error,\n warning: console.warn,\n info: console.info,\n debug: console.debug,\n verbose: console.debug\n };\n var f = function(logger, message) {\n forge.log.prepareStandard(message);\n var handler = levelHandlers[message.level];\n // prepend standard message and concat args\n var args = [message.standard];\n args = args.concat(message['arguments'].slice());\n // apply to low-level console function\n handler.apply(console, args);\n };\n logger = forge.log.makeLogger(f);\n } else {\n // only appear to have basic console.log\n var f = function(logger, message) {\n forge.log.prepareStandardFull(message);\n console.log(message.standardFull);\n };\n logger = forge.log.makeLogger(f);\n }\n forge.log.setLevel(logger, 'debug');\n forge.log.addLogger(logger);\n sConsoleLogger = logger;\n} else {\n // define fake console.log to avoid potential script errors on\n // browsers that do not have console logging\n console = {\n log: function() {}\n };\n}\n\n/*\n * Check for logging control query vars.\n *\n * console.level=\n * Set's the console log level by name. Useful to override defaults and\n * allow more verbose logging before a user config is loaded.\n *\n * console.lock=\n * Lock the console log level at whatever level it is set at. This is run\n * after console.level is processed. Useful to force a level of verbosity\n * that could otherwise be limited by a user config.\n */\nif(sConsoleLogger !== null) {\n var query = forge.util.getQueryVariables();\n if('console.level' in query) {\n // set with last value\n forge.log.setLevel(\n sConsoleLogger, query['console.level'].slice(-1)[0]);\n }\n if('console.lock' in query) {\n // set with last value\n var lock = query['console.lock'].slice(-1)[0];\n if(lock == 'true') {\n forge.log.lock(sConsoleLogger);\n }\n }\n}\n\n// provide public access to console logger\nforge.log.consoleLogger = sConsoleLogger;\n","/**\n * Javascript implementation of PKCS#7 v1.5.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n *\n * Currently this implementation only supports ContentType of EnvelopedData,\n * EncryptedData, or SignedData at the root level. The top level elements may\n * contain only a ContentInfo of ContentType Data, i.e. plain data. Further\n * nesting is not (yet) supported.\n *\n * The Forge validators for PKCS #7's ASN.1 structures are available from\n * a separate file pkcs7asn1.js, since those are referenced from other\n * PKCS standards like PKCS #12.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./oids');\nrequire('./pem');\nrequire('./pkcs7asn1');\nrequire('./random');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};\n\n/**\n * Converts a PKCS#7 message from PEM format.\n *\n * @param pem the PEM-formatted PKCS#7 message.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PKCS7') {\n var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +\n 'header type is not \"PKCS#7\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return p7.messageFromAsn1(obj);\n};\n\n/**\n * Converts a PKCS#7 message to PEM format.\n *\n * @param msg The PKCS#7 message object\n * @param maxline The maximum characters per line, defaults to 64.\n *\n * @return The PEM-formatted PKCS#7 message.\n */\np7.messageToPem = function(msg, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var pemObj = {\n type: 'PKCS7',\n body: asn1.toDer(msg.toAsn1()).getBytes()\n };\n return forge.pem.encode(pemObj, {maxline: maxline});\n};\n\n/**\n * Converts a PKCS#7 message from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a ContentInfo.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromAsn1 = function(obj) {\n // validate root level ContentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not an PKCS#7 ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var contentType = asn1.derToOid(capture.contentType);\n var msg;\n\n switch(contentType) {\n case forge.pki.oids.envelopedData:\n msg = p7.createEnvelopedData();\n break;\n\n case forge.pki.oids.encryptedData:\n msg = p7.createEncryptedData();\n break;\n\n case forge.pki.oids.signedData:\n msg = p7.createSignedData();\n break;\n\n default:\n throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +\n contentType + ' is not (yet) supported.');\n }\n\n msg.fromAsn1(capture.content.value[0]);\n return msg;\n};\n\np7.createSignedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.signedData,\n version: 1,\n certificates: [],\n crls: [],\n // TODO: add json-formatted signer stuff here?\n signers: [],\n // populated during sign()\n digestAlgorithmIdentifiers: [],\n contentInfo: null,\n signerInfos: [],\n\n fromAsn1: function(obj) {\n // validate SignedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.signedDataValidator);\n msg.certificates = [];\n msg.crls = [];\n msg.digestAlgorithmIdentifiers = [];\n msg.contentInfo = null;\n msg.signerInfos = [];\n\n if(msg.rawCapture.certificates) {\n var certs = msg.rawCapture.certificates.value;\n for(var i = 0; i < certs.length; ++i) {\n msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));\n }\n }\n\n // TODO: parse crls\n },\n\n toAsn1: function() {\n // degenerate case with no content\n if(!msg.contentInfo) {\n msg.sign();\n }\n\n var certs = [];\n for(var i = 0; i < msg.certificates.length; ++i) {\n certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));\n }\n\n var crls = [];\n // TODO: implement CRLs\n\n // [0] SignedData\n var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // DigestAlgorithmIdentifiers\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.digestAlgorithmIdentifiers),\n // ContentInfo\n msg.contentInfo\n ])\n ]);\n if(certs.length > 0) {\n // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));\n }\n if(crls.length > 0) {\n // [1] IMPLICIT CertificateRevocationLists OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));\n }\n // SignerInfos\n signedData.value[0].value.push(\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.signerInfos));\n\n // ContentInfo\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] SignedData\n signedData\n ]);\n },\n\n /**\n * Add (another) entity to list of signers.\n *\n * Note: If authenticatedAttributes are provided, then, per RFC 2315,\n * they must include at least two attributes: content type and\n * message digest. The message digest attribute value will be\n * auto-calculated during signing and will be ignored if provided.\n *\n * Here's an example of providing these two attributes:\n *\n * forge.pkcs7.createSignedData();\n * p7.addSigner({\n * issuer: cert.issuer.attributes,\n * serialNumber: cert.serialNumber,\n * key: privateKey,\n * digestAlgorithm: forge.pki.oids.sha1,\n * authenticatedAttributes: [{\n * type: forge.pki.oids.contentType,\n * value: forge.pki.oids.data\n * }, {\n * type: forge.pki.oids.messageDigest\n * }]\n * });\n *\n * TODO: Support [subjectKeyIdentifier] as signer's ID.\n *\n * @param signer the signer information:\n * key the signer's private key.\n * [certificate] a certificate containing the public key\n * associated with the signer's private key; use this option as\n * an alternative to specifying signer.issuer and\n * signer.serialNumber.\n * [issuer] the issuer attributes (eg: cert.issuer.attributes).\n * [serialNumber] the signer's certificate's serial number in\n * hexadecimal (eg: cert.serialNumber).\n * [digestAlgorithm] the message digest OID, as a string, to use\n * (eg: forge.pki.oids.sha1).\n * [authenticatedAttributes] an optional array of attributes\n * to also sign along with the content.\n */\n addSigner: function(signer) {\n var issuer = signer.issuer;\n var serialNumber = signer.serialNumber;\n if(signer.certificate) {\n var cert = signer.certificate;\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n issuer = cert.issuer.attributes;\n serialNumber = cert.serialNumber;\n }\n var key = signer.key;\n if(!key) {\n throw new Error(\n 'Could not add PKCS#7 signer; no private key specified.');\n }\n if(typeof key === 'string') {\n key = forge.pki.privateKeyFromPem(key);\n }\n\n // ensure OID known for digest algorithm\n var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;\n switch(digestAlgorithm) {\n case forge.pki.oids.sha1:\n case forge.pki.oids.sha256:\n case forge.pki.oids.sha384:\n case forge.pki.oids.sha512:\n case forge.pki.oids.md5:\n break;\n default:\n throw new Error(\n 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +\n digestAlgorithm);\n }\n\n // if authenticatedAttributes is present, then the attributes\n // must contain at least PKCS #9 content-type and message-digest\n var authenticatedAttributes = signer.authenticatedAttributes || [];\n if(authenticatedAttributes.length > 0) {\n var contentType = false;\n var messageDigest = false;\n for(var i = 0; i < authenticatedAttributes.length; ++i) {\n var attr = authenticatedAttributes[i];\n if(!contentType && attr.type === forge.pki.oids.contentType) {\n contentType = true;\n if(messageDigest) {\n break;\n }\n continue;\n }\n if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {\n messageDigest = true;\n if(contentType) {\n break;\n }\n continue;\n }\n }\n\n if(!contentType || !messageDigest) {\n throw new Error('Invalid signer.authenticatedAttributes. If ' +\n 'signer.authenticatedAttributes is specified, then it must ' +\n 'contain at least two attributes, PKCS #9 content-type and ' +\n 'PKCS #9 message-digest.');\n }\n }\n\n msg.signers.push({\n key: key,\n version: 1,\n issuer: issuer,\n serialNumber: serialNumber,\n digestAlgorithm: digestAlgorithm,\n signatureAlgorithm: forge.pki.oids.rsaEncryption,\n signature: null,\n authenticatedAttributes: authenticatedAttributes,\n unauthenticatedAttributes: []\n });\n },\n\n /**\n * Signs the content.\n * @param options Options to apply when signing:\n * [detached] boolean. If signing should be done in detached mode. Defaults to false.\n */\n sign: function(options) {\n options = options || {};\n // auto-generate content info\n if(typeof msg.content !== 'object' || msg.contentInfo === null) {\n // use Data ContentInfo\n msg.contentInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes())\n ]);\n\n // add actual content, if present\n if('content' in msg) {\n var content;\n if(msg.content instanceof forge.util.ByteBuffer) {\n content = msg.content.bytes();\n } else if(typeof msg.content === 'string') {\n content = forge.util.encodeUtf8(msg.content);\n }\n\n if (options.detached) {\n msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);\n } else {\n msg.contentInfo.value.push(\n // [0] EXPLICIT content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n content)\n ]));\n }\n }\n }\n\n // no signers, return early (degenerate case for certificate container)\n if(msg.signers.length === 0) {\n return;\n }\n\n // generate digest algorithm identifiers\n var mds = addDigestAlgorithmIds();\n\n // generate signerInfos\n addSignerInfos(mds);\n },\n\n verify: function() {\n throw new Error('PKCS#7 signature verification not yet implemented.');\n },\n\n /**\n * Add a certificate.\n *\n * @param cert the certificate to add.\n */\n addCertificate: function(cert) {\n // convert from PEM\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n msg.certificates.push(cert);\n },\n\n /**\n * Add a certificate revokation list.\n *\n * @param crl the certificate revokation list to add.\n */\n addCertificateRevokationList: function(crl) {\n throw new Error('PKCS#7 CRL support not yet implemented.');\n }\n };\n return msg;\n\n function addDigestAlgorithmIds() {\n var mds = {};\n\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n var oid = signer.digestAlgorithm;\n if(!(oid in mds)) {\n // content digest\n mds[oid] = forge.md[forge.pki.oids[oid]].create();\n }\n if(signer.authenticatedAttributes.length === 0) {\n // no custom attributes to digest; use content message digest\n signer.md = mds[oid];\n } else {\n // custom attributes to be digested; use own message digest\n // TODO: optimize to just copy message digest state if that\n // feature is ever supported with message digests\n signer.md = forge.md[forge.pki.oids[oid]].create();\n }\n }\n\n // add unique digest algorithm identifiers\n msg.digestAlgorithmIdentifiers = [];\n for(var oid in mds) {\n msg.digestAlgorithmIdentifiers.push(\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oid).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n\n return mds;\n }\n\n function addSignerInfos(mds) {\n var content;\n\n if (msg.detachedContent) {\n // Signature has been made in detached mode.\n content = msg.detachedContent;\n } else {\n // Note: ContentInfo is a SEQUENCE with 2 values, second value is\n // the content field and is optional for a ContentInfo but required here\n // since signers are present\n // get ContentInfo content\n content = msg.contentInfo.value[1];\n // skip [0] EXPLICIT content wrapper\n content = content.value[0];\n }\n\n if(!content) {\n throw new Error(\n 'Could not sign PKCS#7 message; there is no content to sign.');\n }\n\n // get ContentInfo content type\n var contentType = asn1.derToOid(msg.contentInfo.value[0].value);\n\n // serialize content\n var bytes = asn1.toDer(content);\n\n // skip identifier and length per RFC 2315 9.3\n // skip identifier (1 byte)\n bytes.getByte();\n // read and discard length bytes\n asn1.getBerValueLength(bytes);\n bytes = bytes.getBytes();\n\n // digest content DER value bytes\n for(var oid in mds) {\n mds[oid].start().update(bytes);\n }\n\n // sign content\n var signingTime = new Date();\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n\n if(signer.authenticatedAttributes.length === 0) {\n // if ContentInfo content type is not \"Data\", then\n // authenticatedAttributes must be present per RFC 2315\n if(contentType !== forge.pki.oids.data) {\n throw new Error(\n 'Invalid signer; authenticatedAttributes must be present ' +\n 'when the ContentInfo content type is not PKCS#7 Data.');\n }\n } else {\n // process authenticated attributes\n // [0] IMPLICIT\n signer.authenticatedAttributesAsn1 = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // per RFC 2315, attributes are to be digested using a SET container\n // not the above [0] IMPLICIT container\n var attrsAsn1 = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);\n\n for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {\n var attr = signer.authenticatedAttributes[ai];\n if(attr.type === forge.pki.oids.messageDigest) {\n // use content message digest as value\n attr.value = mds[signer.digestAlgorithm].digest();\n } else if(attr.type === forge.pki.oids.signingTime) {\n // auto-populate signing time if not already set\n if(!attr.value) {\n attr.value = signingTime;\n }\n }\n\n // convert to ASN.1 and push onto Attributes SET (for signing) and\n // onto authenticatedAttributesAsn1 to complete SignedData ASN.1\n // TODO: optimize away duplication\n attrsAsn1.value.push(_attributeToAsn1(attr));\n signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));\n }\n\n // DER-serialize and digest SET OF attributes only\n bytes = asn1.toDer(attrsAsn1).getBytes();\n signer.md.start().update(bytes);\n }\n\n // sign digest\n signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');\n }\n\n // add signer info\n msg.signerInfos = _signersToAsn1(msg.signers);\n }\n};\n\n/**\n * Creates an empty PKCS#7 message of type EncryptedData.\n *\n * @return the message.\n */\np7.createEncryptedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.encryptedData,\n version: 0,\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EncryptedData content block (in ASN.1 format)\n *\n * @param obj The ASN.1 representation of the EncryptedData content block\n */\n fromAsn1: function(obj) {\n // Validate EncryptedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);\n },\n\n /**\n * Decrypt encrypted content\n *\n * @param key The (symmetric) key as a byte buffer\n */\n decrypt: function(key) {\n if(key !== undefined) {\n msg.encryptedContent.key = key;\n }\n _decryptContent(msg);\n }\n };\n return msg;\n};\n\n/**\n * Creates an empty PKCS#7 message of type EnvelopedData.\n *\n * @return the message.\n */\np7.createEnvelopedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.envelopedData,\n version: 0,\n recipients: [],\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EnvelopedData content block (in ASN.1 format)\n *\n * @param obj the ASN.1 representation of the EnvelopedData content block.\n */\n fromAsn1: function(obj) {\n // validate EnvelopedData content block and capture data\n var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);\n msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);\n },\n\n toAsn1: function() {\n // ContentInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] EnvelopedData\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // RecipientInfos\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n _recipientsToAsn1(msg.recipients)),\n // EncryptedContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,\n _encryptedContentToAsn1(msg.encryptedContent))\n ])\n ])\n ]);\n },\n\n /**\n * Find recipient by X.509 certificate's issuer.\n *\n * @param cert the certificate with the issuer to look for.\n *\n * @return the recipient object.\n */\n findRecipient: function(cert) {\n var sAttr = cert.issuer.attributes;\n\n for(var i = 0; i < msg.recipients.length; ++i) {\n var r = msg.recipients[i];\n var rAttr = r.issuer;\n\n if(r.serialNumber !== cert.serialNumber) {\n continue;\n }\n\n if(rAttr.length !== sAttr.length) {\n continue;\n }\n\n var match = true;\n for(var j = 0; j < sAttr.length; ++j) {\n if(rAttr[j].type !== sAttr[j].type ||\n rAttr[j].value !== sAttr[j].value) {\n match = false;\n break;\n }\n }\n\n if(match) {\n return r;\n }\n }\n\n return null;\n },\n\n /**\n * Decrypt enveloped content\n *\n * @param recipient The recipient object related to the private key\n * @param privKey The (RSA) private key object\n */\n decrypt: function(recipient, privKey) {\n if(msg.encryptedContent.key === undefined && recipient !== undefined &&\n privKey !== undefined) {\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n case forge.pki.oids.desCBC:\n var key = privKey.decrypt(recipient.encryptedContent.content);\n msg.encryptedContent.key = forge.util.createBuffer(key);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, ' +\n 'OID ' + recipient.encryptedContent.algorithm);\n }\n }\n\n _decryptContent(msg);\n },\n\n /**\n * Add (another) entity to list of recipients.\n *\n * @param cert The certificate of the entity to add.\n */\n addRecipient: function(cert) {\n msg.recipients.push({\n version: 0,\n issuer: cert.issuer.attributes,\n serialNumber: cert.serialNumber,\n encryptedContent: {\n // We simply assume rsaEncryption here, since forge.pki only\n // supports RSA so far. If the PKI module supports other\n // ciphers one day, we need to modify this one as well.\n algorithm: forge.pki.oids.rsaEncryption,\n key: cert.publicKey\n }\n });\n },\n\n /**\n * Encrypt enveloped content.\n *\n * This function supports two optional arguments, cipher and key, which\n * can be used to influence symmetric encryption. Unless cipher is\n * provided, the cipher specified in encryptedContent.algorithm is used\n * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key\n * is (re-)used. If that one's not set, a random key will be generated\n * automatically.\n *\n * @param [key] The key to be used for symmetric encryption.\n * @param [cipher] The OID of the symmetric cipher to use.\n */\n encrypt: function(key, cipher) {\n // Part 1: Symmetric encryption\n if(msg.encryptedContent.content === undefined) {\n cipher = cipher || msg.encryptedContent.algorithm;\n key = key || msg.encryptedContent.key;\n\n var keyLen, ivLen, ciphFn;\n switch(cipher) {\n case forge.pki.oids['aes128-CBC']:\n keyLen = 16;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes192-CBC']:\n keyLen = 24;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes256-CBC']:\n keyLen = 32;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['des-EDE3-CBC']:\n keyLen = 24;\n ivLen = 8;\n ciphFn = forge.des.createEncryptionCipher;\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' + cipher);\n }\n\n if(key === undefined) {\n key = forge.util.createBuffer(forge.random.getBytes(keyLen));\n } else if(key.length() != keyLen) {\n throw new Error('Symmetric key has wrong length; ' +\n 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');\n }\n\n // Keep a copy of the key & IV in the object, so the caller can\n // use it for whatever reason.\n msg.encryptedContent.algorithm = cipher;\n msg.encryptedContent.key = key;\n msg.encryptedContent.parameter = forge.util.createBuffer(\n forge.random.getBytes(ivLen));\n\n var ciph = ciphFn(key);\n ciph.start(msg.encryptedContent.parameter.copy());\n ciph.update(msg.content);\n\n // The finish function does PKCS#7 padding by default, therefore\n // no action required by us.\n if(!ciph.finish()) {\n throw new Error('Symmetric encryption failed.');\n }\n\n msg.encryptedContent.content = ciph.output;\n }\n\n // Part 2: asymmetric encryption for each recipient\n for(var i = 0; i < msg.recipients.length; ++i) {\n var recipient = msg.recipients[i];\n\n // Nothing to do, encryption already done.\n if(recipient.encryptedContent.content !== undefined) {\n continue;\n }\n\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n recipient.encryptedContent.content =\n recipient.encryptedContent.key.encrypt(\n msg.encryptedContent.key.data);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, OID ' +\n recipient.encryptedContent.algorithm);\n }\n }\n }\n };\n return msg;\n};\n\n/**\n * Converts a single recipient from an ASN.1 object.\n *\n * @param obj the ASN.1 RecipientInfo.\n *\n * @return the recipient object.\n */\nfunction _recipientFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +\n 'ASN.1 object is not an PKCS#7 RecipientInfo.');\n error.errors = errors;\n throw error;\n }\n\n return {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n encryptedContent: {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: capture.encParameter.value,\n content: capture.encKey\n }\n };\n}\n\n/**\n * Converts a single recipient object to an ASN.1 object.\n *\n * @param obj the recipient object.\n *\n * @return the ASN.1 RecipientInfo.\n */\nfunction _recipientToAsn1(obj) {\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // IssuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // Serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // KeyEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),\n // Parameter, force NULL, only RSA supported for now.\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // EncryptedKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n obj.encryptedContent.content)\n ]);\n}\n\n/**\n * Map a set of RecipientInfo ASN.1 objects to recipient objects.\n *\n * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).\n *\n * @return an array of recipient objects.\n */\nfunction _recipientsFromAsn1(infos) {\n var ret = [];\n for(var i = 0; i < infos.length; ++i) {\n ret.push(_recipientFromAsn1(infos[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of recipient objects to ASN.1 RecipientInfo objects.\n *\n * @param recipients an array of recipientInfo objects.\n *\n * @return an array of ASN.1 RecipientInfos.\n */\nfunction _recipientsToAsn1(recipients) {\n var ret = [];\n for(var i = 0; i < recipients.length; ++i) {\n ret.push(_recipientToAsn1(recipients[i]));\n }\n return ret;\n}\n\n/**\n * Converts a single signer from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a SignerInfo.\n *\n * @return the signer object.\n */\nfunction _signerFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 SignerInfo. ' +\n 'ASN.1 object is not an PKCS#7 SignerInfo.');\n error.errors = errors;\n throw error;\n }\n\n var rval = {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),\n signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),\n signature: capture.signature,\n authenticatedAttributes: [],\n unauthenticatedAttributes: []\n };\n\n // TODO: convert attributes\n var authenticatedAttributes = capture.authenticatedAttributes || [];\n var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];\n\n return rval;\n}\n\n/**\n * Converts a single signerInfo object to an ASN.1 object.\n *\n * @param obj the signerInfo object.\n *\n * @return the ASN.1 representation of a SignerInfo.\n */\nfunction _signerToAsn1(obj) {\n // SignerInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // issuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.digestAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]);\n\n // authenticatedAttributes (OPTIONAL)\n if(obj.authenticatedAttributesAsn1) {\n // add ASN.1 previously generated during signing\n rval.value.push(obj.authenticatedAttributesAsn1);\n }\n\n // digestEncryptionAlgorithm\n rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.signatureAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n\n // encryptedDigest\n rval.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));\n\n // unauthenticatedAttributes (OPTIONAL)\n if(obj.unauthenticatedAttributes.length > 0) {\n // [1] IMPLICIT\n var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);\n for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {\n var attr = obj.unauthenticatedAttributes[i];\n attrsAsn1.values.push(_attributeToAsn1(attr));\n }\n rval.value.push(attrsAsn1);\n }\n\n return rval;\n}\n\n/**\n * Map a set of SignerInfo ASN.1 objects to an array of signer objects.\n *\n * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF).\n *\n * @return an array of signers objects.\n */\nfunction _signersFromAsn1(signerInfoAsn1s) {\n var ret = [];\n for(var i = 0; i < signerInfoAsn1s.length; ++i) {\n ret.push(_signerFromAsn1(signerInfoAsn1s[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of signer objects to ASN.1 objects.\n *\n * @param signers an array of signer objects.\n *\n * @return an array of ASN.1 SignerInfos.\n */\nfunction _signersToAsn1(signers) {\n var ret = [];\n for(var i = 0; i < signers.length; ++i) {\n ret.push(_signerToAsn1(signers[i]));\n }\n return ret;\n}\n\n/**\n * Convert an attribute object to an ASN.1 Attribute.\n *\n * @param attr the attribute object.\n *\n * @return the ASN.1 Attribute.\n */\nfunction _attributeToAsn1(attr) {\n var value;\n\n // TODO: generalize to support more attributes\n if(attr.type === forge.pki.oids.contentType) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.value).getBytes());\n } else if(attr.type === forge.pki.oids.messageDigest) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n attr.value.bytes());\n } else if(attr.type === forge.pki.oids.signingTime) {\n /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049\n (inclusive) MUST be encoded as UTCTime. Any dates with year values\n before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]\n UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST\n include seconds (i.e., times are YYMMDDHHMMSSZ), even where the\n number of seconds is zero. Midnight (GMT) must be represented as\n \"YYMMDD000000Z\". */\n // TODO: make these module-level constants\n var jan_1_1950 = new Date('1950-01-01T00:00:00Z');\n var jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n var date = attr.value;\n if(typeof date === 'string') {\n // try to parse date\n var timestamp = Date.parse(date);\n if(!isNaN(timestamp)) {\n date = new Date(timestamp);\n } else if(date.length === 13) {\n // YYMMDDHHMMSSZ (13 chars for UTCTime)\n date = asn1.utcTimeToDate(date);\n } else {\n // assume generalized time\n date = asn1.generalizedTimeToDate(date);\n }\n }\n\n if(date >= jan_1_1950 && date < jan_1_2050) {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n }\n\n // TODO: expose as common API call\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n value\n ])\n ]);\n}\n\n/**\n * Map messages encrypted content to ASN.1 objects.\n *\n * @param ec The encryptedContent object of the message.\n *\n * @return ASN.1 representation of the encryptedContent object (SEQUENCE).\n */\nfunction _encryptedContentToAsn1(ec) {\n return [\n // ContentType, always Data for the moment\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes()),\n // ContentEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ec.algorithm).getBytes()),\n // Parameters (IV)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.parameter.getBytes())\n ]),\n // [0] EncryptedContent\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.content.getBytes())\n ])\n ];\n}\n\n/**\n * Reads the \"common part\" of an PKCS#7 content block (in ASN.1 format)\n *\n * This function reads the \"common part\" of the PKCS#7 content blocks\n * EncryptedData and EnvelopedData, i.e. version number and symmetrically\n * encrypted content block.\n *\n * The result of the ASN.1 validate and capture process is returned\n * to allow the caller to extract further data, e.g. the list of recipients\n * in case of a EnvelopedData object.\n *\n * @param msg the PKCS#7 object to read the data to.\n * @param obj the ASN.1 representation of the content block.\n * @param validator the ASN.1 structure validator object to use.\n *\n * @return the value map captured by validator object.\n */\nfunction _fromAsn1(msg, obj, validator) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not a supported PKCS#7 message.');\n error.errors = error;\n throw error;\n }\n\n // Check contentType, so far we only support (raw) Data.\n var contentType = asn1.derToOid(capture.contentType);\n if(contentType !== forge.pki.oids.data) {\n throw new Error('Unsupported PKCS#7 message. ' +\n 'Only wrapped ContentType Data supported.');\n }\n\n if(capture.encryptedContent) {\n var content = '';\n if(forge.util.isArray(capture.encryptedContent)) {\n for(var i = 0; i < capture.encryptedContent.length; ++i) {\n if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting encrypted ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.encryptedContent[i].value;\n }\n } else {\n content = capture.encryptedContent;\n }\n msg.encryptedContent = {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: forge.util.createBuffer(capture.encParameter.value),\n content: forge.util.createBuffer(content)\n };\n }\n\n if(capture.content) {\n var content = '';\n if(forge.util.isArray(capture.content)) {\n for(var i = 0; i < capture.content.length; ++i) {\n if(capture.content[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.content[i].value;\n }\n } else {\n content = capture.content;\n }\n msg.content = forge.util.createBuffer(content);\n }\n\n msg.version = capture.version.charCodeAt(0);\n msg.rawCapture = capture;\n\n return capture;\n}\n\n/**\n * Decrypt the symmetrically encrypted content block of the PKCS#7 message.\n *\n * Decryption is skipped in case the PKCS#7 message object already has a\n * (decrypted) content attribute. The algorithm, key and cipher parameters\n * (probably the iv) are taken from the encryptedContent attribute of the\n * message object.\n *\n * @param The PKCS#7 message object.\n */\nfunction _decryptContent(msg) {\n if(msg.encryptedContent.key === undefined) {\n throw new Error('Symmetric key not available.');\n }\n\n if(msg.content === undefined) {\n var ciph;\n\n switch(msg.encryptedContent.algorithm) {\n case forge.pki.oids['aes128-CBC']:\n case forge.pki.oids['aes192-CBC']:\n case forge.pki.oids['aes256-CBC']:\n ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n case forge.pki.oids['desCBC']:\n case forge.pki.oids['des-EDE3-CBC']:\n ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' +\n msg.encryptedContent.algorithm);\n }\n ciph.start(msg.encryptedContent.parameter);\n ciph.update(msg.encryptedContent.content);\n\n if(!ciph.finish()) {\n throw new Error('Symmetric decryption failed.');\n }\n\n msg.content = ciph.output;\n }\n}\n","/**\n * Functions to output keys in SSH-friendly formats.\n *\n * This is part of the Forge project which may be used under the terms of\n * either the BSD License or the GNU General Public License (GPL) Version 2.\n *\n * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE\n *\n * @author https://github.com/shellac\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./hmac');\nrequire('./md5');\nrequire('./sha1');\nrequire('./util');\n\nvar ssh = module.exports = forge.ssh = forge.ssh || {};\n\n/**\n * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file.\n *\n * @param privateKey the key.\n * @param passphrase a passphrase to protect the key (falsy for no encryption).\n * @param comment a comment to include in the key file.\n *\n * @return the PPK file as a string.\n */\nssh.privateKeyToPutty = function(privateKey, passphrase, comment) {\n comment = comment || '';\n passphrase = passphrase || '';\n var algorithm = 'ssh-rsa';\n var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc';\n\n var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\\r\\n';\n ppk += 'Encryption: ' + encryptionAlgorithm + '\\r\\n';\n ppk += 'Comment: ' + comment + '\\r\\n';\n\n // public key into buffer for ppk\n var pubbuffer = forge.util.createBuffer();\n _addStringToBuffer(pubbuffer, algorithm);\n _addBigIntegerToBuffer(pubbuffer, privateKey.e);\n _addBigIntegerToBuffer(pubbuffer, privateKey.n);\n\n // write public key\n var pub = forge.util.encode64(pubbuffer.bytes(), 64);\n var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \\r\\n\n ppk += 'Public-Lines: ' + length + '\\r\\n';\n ppk += pub;\n\n // private key into a buffer\n var privbuffer = forge.util.createBuffer();\n _addBigIntegerToBuffer(privbuffer, privateKey.d);\n _addBigIntegerToBuffer(privbuffer, privateKey.p);\n _addBigIntegerToBuffer(privbuffer, privateKey.q);\n _addBigIntegerToBuffer(privbuffer, privateKey.qInv);\n\n // optionally encrypt the private key\n var priv;\n if(!passphrase) {\n // use the unencrypted buffer\n priv = forge.util.encode64(privbuffer.bytes(), 64);\n } else {\n // encrypt RSA key using passphrase\n var encLen = privbuffer.length() + 16 - 1;\n encLen -= encLen % 16;\n\n // pad private key with sha1-d data -- needs to be a multiple of 16\n var padding = _sha1(privbuffer.bytes());\n\n padding.truncate(padding.length() - encLen + privbuffer.length());\n privbuffer.putBuffer(padding);\n\n var aeskey = forge.util.createBuffer();\n aeskey.putBuffer(_sha1('\\x00\\x00\\x00\\x00', passphrase));\n aeskey.putBuffer(_sha1('\\x00\\x00\\x00\\x01', passphrase));\n\n // encrypt some bytes using CBC mode\n // key is 40 bytes, so truncate *by* 8 bytes\n var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC');\n cipher.start(forge.util.createBuffer().fillWithByte(0, 16));\n cipher.update(privbuffer.copy());\n cipher.finish();\n var encrypted = cipher.output;\n\n // Note: this appears to differ from Putty -- is forge wrong, or putty?\n // due to padding we finish as an exact multiple of 16\n encrypted.truncate(16); // all padding\n\n priv = forge.util.encode64(encrypted.bytes(), 64);\n }\n\n // output private key\n length = Math.floor(priv.length / 66) + 1; // 64 + \\r\\n\n ppk += '\\r\\nPrivate-Lines: ' + length + '\\r\\n';\n ppk += priv;\n\n // MAC\n var mackey = _sha1('putty-private-key-file-mac-key', passphrase);\n\n var macbuffer = forge.util.createBuffer();\n _addStringToBuffer(macbuffer, algorithm);\n _addStringToBuffer(macbuffer, encryptionAlgorithm);\n _addStringToBuffer(macbuffer, comment);\n macbuffer.putInt32(pubbuffer.length());\n macbuffer.putBuffer(pubbuffer);\n macbuffer.putInt32(privbuffer.length());\n macbuffer.putBuffer(privbuffer);\n\n var hmac = forge.hmac.create();\n hmac.start('sha1', mackey);\n hmac.update(macbuffer.bytes());\n\n ppk += '\\r\\nPrivate-MAC: ' + hmac.digest().toHex() + '\\r\\n';\n\n return ppk;\n};\n\n/**\n * Encodes a public RSA key as an OpenSSH file.\n *\n * @param key the key.\n * @param comment a comment.\n *\n * @return the public key in OpenSSH format.\n */\nssh.publicKeyToOpenSSH = function(key, comment) {\n var type = 'ssh-rsa';\n comment = comment || '';\n\n var buffer = forge.util.createBuffer();\n _addStringToBuffer(buffer, type);\n _addBigIntegerToBuffer(buffer, key.e);\n _addBigIntegerToBuffer(buffer, key.n);\n\n return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment;\n};\n\n/**\n * Encodes a private RSA key as an OpenSSH file.\n *\n * @param key the key.\n * @param passphrase a passphrase to protect the key (falsy for no encryption).\n *\n * @return the public key in OpenSSH format.\n */\nssh.privateKeyToOpenSSH = function(privateKey, passphrase) {\n if(!passphrase) {\n return forge.pki.privateKeyToPem(privateKey);\n }\n // OpenSSH private key is just a legacy format, it seems\n return forge.pki.encryptRsaPrivateKey(privateKey, passphrase,\n {legacy: true, algorithm: 'aes128'});\n};\n\n/**\n * Gets the SSH fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.md5).\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\nssh.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.md5.create();\n\n var type = 'ssh-rsa';\n var buffer = forge.util.createBuffer();\n _addStringToBuffer(buffer, type);\n _addBigIntegerToBuffer(buffer, key.e);\n _addBigIntegerToBuffer(buffer, key.n);\n\n // hash public key bytes\n md.start();\n md.update(buffer.getBytes());\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Adds len(val) then val to a buffer.\n *\n * @param buffer the buffer to add to.\n * @param val a big integer.\n */\nfunction _addBigIntegerToBuffer(buffer, val) {\n var hexVal = val.toString(16);\n // ensure 2s complement +ve\n if(hexVal[0] >= '8') {\n hexVal = '00' + hexVal;\n }\n var bytes = forge.util.hexToBytes(hexVal);\n buffer.putInt32(bytes.length);\n buffer.putBytes(bytes);\n}\n\n/**\n * Adds len(val) then val to a buffer.\n *\n * @param buffer the buffer to add to.\n * @param val a string.\n */\nfunction _addStringToBuffer(buffer, val) {\n buffer.putInt32(val.length);\n buffer.putString(val);\n}\n\n/**\n * Hashes the arguments into one value using SHA-1.\n *\n * @return the sha1 hash of the provided arguments.\n */\nfunction _sha1() {\n var sha = forge.md.sha1.create();\n var num = arguments.length;\n for (var i = 0; i < num; ++i) {\n sha.update(arguments[i]);\n }\n return sha.digest();\n}\n","/**\n * Support for concurrent task management and synchronization in web\n * applications.\n *\n * @author Dave Longley\n * @author David I. Lehn \n *\n * Copyright (c) 2009-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./debug');\nrequire('./log');\nrequire('./util');\n\n// logging category\nvar cat = 'forge.task';\n\n// verbose level\n// 0: off, 1: a little, 2: a whole lot\n// Verbose debug logging is surrounded by a level check to avoid the\n// performance issues with even calling the logging code regardless if it\n// is actually logged. For performance reasons this should not be set to 2\n// for production use.\n// ex: if(sVL >= 2) forge.log.verbose(....)\nvar sVL = 0;\n\n// track tasks for debugging\nvar sTasks = {};\nvar sNextTaskId = 0;\n// debug access\nforge.debug.set(cat, 'tasks', sTasks);\n\n// a map of task type to task queue\nvar sTaskQueues = {};\n// debug access\nforge.debug.set(cat, 'queues', sTaskQueues);\n\n// name for unnamed tasks\nvar sNoTaskName = '?';\n\n// maximum number of doNext() recursions before a context swap occurs\n// FIXME: might need to tweak this based on the browser\nvar sMaxRecursions = 30;\n\n// time slice for doing tasks before a context swap occurs\n// FIXME: might need to tweak this based on the browser\nvar sTimeSlice = 20;\n\n/**\n * Task states.\n *\n * READY: ready to start processing\n * RUNNING: task or a subtask is running\n * BLOCKED: task is waiting to acquire N permits to continue\n * SLEEPING: task is sleeping for a period of time\n * DONE: task is done\n * ERROR: task has an error\n */\nvar READY = 'ready';\nvar RUNNING = 'running';\nvar BLOCKED = 'blocked';\nvar SLEEPING = 'sleeping';\nvar DONE = 'done';\nvar ERROR = 'error';\n\n/**\n * Task actions. Used to control state transitions.\n *\n * STOP: stop processing\n * START: start processing tasks\n * BLOCK: block task from continuing until 1 or more permits are released\n * UNBLOCK: release one or more permits\n * SLEEP: sleep for a period of time\n * WAKEUP: wakeup early from SLEEPING state\n * CANCEL: cancel further tasks\n * FAIL: a failure occured\n */\nvar STOP = 'stop';\nvar START = 'start';\nvar BLOCK = 'block';\nvar UNBLOCK = 'unblock';\nvar SLEEP = 'sleep';\nvar WAKEUP = 'wakeup';\nvar CANCEL = 'cancel';\nvar FAIL = 'fail';\n\n/**\n * State transition table.\n *\n * nextState = sStateTable[currentState][action]\n */\nvar sStateTable = {};\n\nsStateTable[READY] = {};\nsStateTable[READY][STOP] = READY;\nsStateTable[READY][START] = RUNNING;\nsStateTable[READY][CANCEL] = DONE;\nsStateTable[READY][FAIL] = ERROR;\n\nsStateTable[RUNNING] = {};\nsStateTable[RUNNING][STOP] = READY;\nsStateTable[RUNNING][START] = RUNNING;\nsStateTable[RUNNING][BLOCK] = BLOCKED;\nsStateTable[RUNNING][UNBLOCK] = RUNNING;\nsStateTable[RUNNING][SLEEP] = SLEEPING;\nsStateTable[RUNNING][WAKEUP] = RUNNING;\nsStateTable[RUNNING][CANCEL] = DONE;\nsStateTable[RUNNING][FAIL] = ERROR;\n\nsStateTable[BLOCKED] = {};\nsStateTable[BLOCKED][STOP] = BLOCKED;\nsStateTable[BLOCKED][START] = BLOCKED;\nsStateTable[BLOCKED][BLOCK] = BLOCKED;\nsStateTable[BLOCKED][UNBLOCK] = BLOCKED;\nsStateTable[BLOCKED][SLEEP] = BLOCKED;\nsStateTable[BLOCKED][WAKEUP] = BLOCKED;\nsStateTable[BLOCKED][CANCEL] = DONE;\nsStateTable[BLOCKED][FAIL] = ERROR;\n\nsStateTable[SLEEPING] = {};\nsStateTable[SLEEPING][STOP] = SLEEPING;\nsStateTable[SLEEPING][START] = SLEEPING;\nsStateTable[SLEEPING][BLOCK] = SLEEPING;\nsStateTable[SLEEPING][UNBLOCK] = SLEEPING;\nsStateTable[SLEEPING][SLEEP] = SLEEPING;\nsStateTable[SLEEPING][WAKEUP] = SLEEPING;\nsStateTable[SLEEPING][CANCEL] = DONE;\nsStateTable[SLEEPING][FAIL] = ERROR;\n\nsStateTable[DONE] = {};\nsStateTable[DONE][STOP] = DONE;\nsStateTable[DONE][START] = DONE;\nsStateTable[DONE][BLOCK] = DONE;\nsStateTable[DONE][UNBLOCK] = DONE;\nsStateTable[DONE][SLEEP] = DONE;\nsStateTable[DONE][WAKEUP] = DONE;\nsStateTable[DONE][CANCEL] = DONE;\nsStateTable[DONE][FAIL] = ERROR;\n\nsStateTable[ERROR] = {};\nsStateTable[ERROR][STOP] = ERROR;\nsStateTable[ERROR][START] = ERROR;\nsStateTable[ERROR][BLOCK] = ERROR;\nsStateTable[ERROR][UNBLOCK] = ERROR;\nsStateTable[ERROR][SLEEP] = ERROR;\nsStateTable[ERROR][WAKEUP] = ERROR;\nsStateTable[ERROR][CANCEL] = ERROR;\nsStateTable[ERROR][FAIL] = ERROR;\n\n/**\n * Creates a new task.\n *\n * @param options options for this task\n * run: the run function for the task (required)\n * name: the run function for the task (optional)\n * parent: parent of this task (optional)\n *\n * @return the empty task.\n */\nvar Task = function(options) {\n // task id\n this.id = -1;\n\n // task name\n this.name = options.name || sNoTaskName;\n\n // task has no parent\n this.parent = options.parent || null;\n\n // save run function\n this.run = options.run;\n\n // create a queue of subtasks to run\n this.subtasks = [];\n\n // error flag\n this.error = false;\n\n // state of the task\n this.state = READY;\n\n // number of times the task has been blocked (also the number\n // of permits needed to be released to continue running)\n this.blocks = 0;\n\n // timeout id when sleeping\n this.timeoutId = null;\n\n // no swap time yet\n this.swapTime = null;\n\n // no user data\n this.userData = null;\n\n // initialize task\n // FIXME: deal with overflow\n this.id = sNextTaskId++;\n sTasks[this.id] = this;\n if(sVL >= 1) {\n forge.log.verbose(cat, '[%s][%s] init', this.id, this.name, this);\n }\n};\n\n/**\n * Logs debug information on this task and the system state.\n */\nTask.prototype.debug = function(msg) {\n msg = msg || '';\n forge.log.debug(cat, msg,\n '[%s][%s] task:', this.id, this.name, this,\n 'subtasks:', this.subtasks.length,\n 'queue:', sTaskQueues);\n};\n\n/**\n * Adds a subtask to run after task.doNext() or task.fail() is called.\n *\n * @param name human readable name for this task (optional).\n * @param subrun a function to run that takes the current task as\n * its first parameter.\n *\n * @return the current task (useful for chaining next() calls).\n */\nTask.prototype.next = function(name, subrun) {\n // juggle parameters if it looks like no name is given\n if(typeof(name) === 'function') {\n subrun = name;\n\n // inherit parent's name\n name = this.name;\n }\n // create subtask, set parent to this task, propagate callbacks\n var subtask = new Task({\n run: subrun,\n name: name,\n parent: this\n });\n // start subtasks running\n subtask.state = RUNNING;\n subtask.type = this.type;\n subtask.successCallback = this.successCallback || null;\n subtask.failureCallback = this.failureCallback || null;\n\n // queue a new subtask\n this.subtasks.push(subtask);\n\n return this;\n};\n\n/**\n * Adds subtasks to run in parallel after task.doNext() or task.fail()\n * is called.\n *\n * @param name human readable name for this task (optional).\n * @param subrun functions to run that take the current task as\n * their first parameter.\n *\n * @return the current task (useful for chaining next() calls).\n */\nTask.prototype.parallel = function(name, subrun) {\n // juggle parameters if it looks like no name is given\n if(forge.util.isArray(name)) {\n subrun = name;\n\n // inherit parent's name\n name = this.name;\n }\n // Wrap parallel tasks in a regular task so they are started at the\n // proper time.\n return this.next(name, function(task) {\n // block waiting for subtasks\n var ptask = task;\n ptask.block(subrun.length);\n\n // we pass the iterator from the loop below as a parameter\n // to a function because it is otherwise included in the\n // closure and changes as the loop changes -- causing i\n // to always be set to its highest value\n var startParallelTask = function(pname, pi) {\n forge.task.start({\n type: pname,\n run: function(task) {\n subrun[pi](task);\n },\n success: function(task) {\n ptask.unblock();\n },\n failure: function(task) {\n ptask.unblock();\n }\n });\n };\n\n for(var i = 0; i < subrun.length; i++) {\n // Type must be unique so task starts in parallel:\n // name + private string + task id + sub-task index\n // start tasks in parallel and unblock when the finish\n var pname = name + '__parallel-' + task.id + '-' + i;\n var pi = i;\n startParallelTask(pname, pi);\n }\n });\n};\n\n/**\n * Stops a running task.\n */\nTask.prototype.stop = function() {\n this.state = sStateTable[this.state][STOP];\n};\n\n/**\n * Starts running a task.\n */\nTask.prototype.start = function() {\n this.error = false;\n this.state = sStateTable[this.state][START];\n\n // try to restart\n if(this.state === RUNNING) {\n this.start = new Date();\n this.run(this);\n runNext(this, 0);\n }\n};\n\n/**\n * Blocks a task until it one or more permits have been released. The\n * task will not resume until the requested number of permits have\n * been released with call(s) to unblock().\n *\n * @param n number of permits to wait for(default: 1).\n */\nTask.prototype.block = function(n) {\n n = typeof(n) === 'undefined' ? 1 : n;\n this.blocks += n;\n if(this.blocks > 0) {\n this.state = sStateTable[this.state][BLOCK];\n }\n};\n\n/**\n * Releases a permit to unblock a task. If a task was blocked by\n * requesting N permits via block(), then it will only continue\n * running once enough permits have been released via unblock() calls.\n *\n * If multiple processes need to synchronize with a single task then\n * use a condition variable (see forge.task.createCondition). It is\n * an error to unblock a task more times than it has been blocked.\n *\n * @param n number of permits to release (default: 1).\n *\n * @return the current block count (task is unblocked when count is 0)\n */\nTask.prototype.unblock = function(n) {\n n = typeof(n) === 'undefined' ? 1 : n;\n this.blocks -= n;\n if(this.blocks === 0 && this.state !== DONE) {\n this.state = RUNNING;\n runNext(this, 0);\n }\n return this.blocks;\n};\n\n/**\n * Sleep for a period of time before resuming tasks.\n *\n * @param n number of milliseconds to sleep (default: 0).\n */\nTask.prototype.sleep = function(n) {\n n = typeof(n) === 'undefined' ? 0 : n;\n this.state = sStateTable[this.state][SLEEP];\n var self = this;\n this.timeoutId = setTimeout(function() {\n self.timeoutId = null;\n self.state = RUNNING;\n runNext(self, 0);\n }, n);\n};\n\n/**\n * Waits on a condition variable until notified. The next task will\n * not be scheduled until notification. A condition variable can be\n * created with forge.task.createCondition().\n *\n * Once cond.notify() is called, the task will continue.\n *\n * @param cond the condition variable to wait on.\n */\nTask.prototype.wait = function(cond) {\n cond.wait(this);\n};\n\n/**\n * If sleeping, wakeup and continue running tasks.\n */\nTask.prototype.wakeup = function() {\n if(this.state === SLEEPING) {\n cancelTimeout(this.timeoutId);\n this.timeoutId = null;\n this.state = RUNNING;\n runNext(this, 0);\n }\n};\n\n/**\n * Cancel all remaining subtasks of this task.\n */\nTask.prototype.cancel = function() {\n this.state = sStateTable[this.state][CANCEL];\n // remove permits needed\n this.permitsNeeded = 0;\n // cancel timeouts\n if(this.timeoutId !== null) {\n cancelTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n // remove subtasks\n this.subtasks = [];\n};\n\n/**\n * Finishes this task with failure and sets error flag. The entire\n * task will be aborted unless the next task that should execute\n * is passed as a parameter. This allows levels of subtasks to be\n * skipped. For instance, to abort only this tasks's subtasks, then\n * call fail(task.parent). To abort this task's subtasks and its\n * parent's subtasks, call fail(task.parent.parent). To abort\n * all tasks and simply call the task callback, call fail() or\n * fail(null).\n *\n * The task callback (success or failure) will always, eventually, be\n * called.\n *\n * @param next the task to continue at, or null to abort entirely.\n */\nTask.prototype.fail = function(next) {\n // set error flag\n this.error = true;\n\n // finish task\n finish(this, true);\n\n if(next) {\n // propagate task info\n next.error = this.error;\n next.swapTime = this.swapTime;\n next.userData = this.userData;\n\n // do next task as specified\n runNext(next, 0);\n } else {\n if(this.parent !== null) {\n // finish root task (ensures it is removed from task queue)\n var parent = this.parent;\n while(parent.parent !== null) {\n // propagate task info\n parent.error = this.error;\n parent.swapTime = this.swapTime;\n parent.userData = this.userData;\n parent = parent.parent;\n }\n finish(parent, true);\n }\n\n // call failure callback if one exists\n if(this.failureCallback) {\n this.failureCallback(this);\n }\n }\n};\n\n/**\n * Asynchronously start a task.\n *\n * @param task the task to start.\n */\nvar start = function(task) {\n task.error = false;\n task.state = sStateTable[task.state][START];\n setTimeout(function() {\n if(task.state === RUNNING) {\n task.swapTime = +new Date();\n task.run(task);\n runNext(task, 0);\n }\n }, 0);\n};\n\n/**\n * Run the next subtask or finish this task.\n *\n * @param task the task to process.\n * @param recurse the recursion count.\n */\nvar runNext = function(task, recurse) {\n // get time since last context swap (ms), if enough time has passed set\n // swap to true to indicate that doNext was performed asynchronously\n // also, if recurse is too high do asynchronously\n var swap =\n (recurse > sMaxRecursions) ||\n (+new Date() - task.swapTime) > sTimeSlice;\n\n var doNext = function(recurse) {\n recurse++;\n if(task.state === RUNNING) {\n if(swap) {\n // update swap time\n task.swapTime = +new Date();\n }\n\n if(task.subtasks.length > 0) {\n // run next subtask\n var subtask = task.subtasks.shift();\n subtask.error = task.error;\n subtask.swapTime = task.swapTime;\n subtask.userData = task.userData;\n subtask.run(subtask);\n if(!subtask.error) {\n runNext(subtask, recurse);\n }\n } else {\n finish(task);\n\n if(!task.error) {\n // chain back up and run parent\n if(task.parent !== null) {\n // propagate task info\n task.parent.error = task.error;\n task.parent.swapTime = task.swapTime;\n task.parent.userData = task.userData;\n\n // no subtasks left, call run next subtask on parent\n runNext(task.parent, recurse);\n }\n }\n }\n }\n };\n\n if(swap) {\n // we're swapping, so run asynchronously\n setTimeout(doNext, 0);\n } else {\n // not swapping, so run synchronously\n doNext(recurse);\n }\n};\n\n/**\n * Finishes a task and looks for the next task in the queue to start.\n *\n * @param task the task to finish.\n * @param suppressCallbacks true to suppress callbacks.\n */\nvar finish = function(task, suppressCallbacks) {\n // subtask is now done\n task.state = DONE;\n\n delete sTasks[task.id];\n if(sVL >= 1) {\n forge.log.verbose(cat, '[%s][%s] finish',\n task.id, task.name, task);\n }\n\n // only do queue processing for root tasks\n if(task.parent === null) {\n // report error if queue is missing\n if(!(task.type in sTaskQueues)) {\n forge.log.error(cat,\n '[%s][%s] task queue missing [%s]',\n task.id, task.name, task.type);\n } else if(sTaskQueues[task.type].length === 0) {\n // report error if queue is empty\n forge.log.error(cat,\n '[%s][%s] task queue empty [%s]',\n task.id, task.name, task.type);\n } else if(sTaskQueues[task.type][0] !== task) {\n // report error if this task isn't the first in the queue\n forge.log.error(cat,\n '[%s][%s] task not first in queue [%s]',\n task.id, task.name, task.type);\n } else {\n // remove ourselves from the queue\n sTaskQueues[task.type].shift();\n // clean up queue if it is empty\n if(sTaskQueues[task.type].length === 0) {\n if(sVL >= 1) {\n forge.log.verbose(cat, '[%s][%s] delete queue [%s]',\n task.id, task.name, task.type);\n }\n /* Note: Only a task can delete a queue of its own type. This\n is used as a way to synchronize tasks. If a queue for a certain\n task type exists, then a task of that type is running.\n */\n delete sTaskQueues[task.type];\n } else {\n // dequeue the next task and start it\n if(sVL >= 1) {\n forge.log.verbose(cat,\n '[%s][%s] queue start next [%s] remain:%s',\n task.id, task.name, task.type,\n sTaskQueues[task.type].length);\n }\n sTaskQueues[task.type][0].start();\n }\n }\n\n if(!suppressCallbacks) {\n // call final callback if one exists\n if(task.error && task.failureCallback) {\n task.failureCallback(task);\n } else if(!task.error && task.successCallback) {\n task.successCallback(task);\n }\n }\n }\n};\n\n/* Tasks API */\nmodule.exports = forge.task = forge.task || {};\n\n/**\n * Starts a new task that will run the passed function asynchronously.\n *\n * In order to finish the task, either task.doNext() or task.fail()\n * *must* be called.\n *\n * The task must have a type (a string identifier) that can be used to\n * synchronize it with other tasks of the same type. That type can also\n * be used to cancel tasks that haven't started yet.\n *\n * To start a task, the following object must be provided as a parameter\n * (each function takes a task object as its first parameter):\n *\n * {\n * type: the type of task.\n * run: the function to run to execute the task.\n * success: a callback to call when the task succeeds (optional).\n * failure: a callback to call when the task fails (optional).\n * }\n *\n * @param options the object as described above.\n */\nforge.task.start = function(options) {\n // create a new task\n var task = new Task({\n run: options.run,\n name: options.name || sNoTaskName\n });\n task.type = options.type;\n task.successCallback = options.success || null;\n task.failureCallback = options.failure || null;\n\n // append the task onto the appropriate queue\n if(!(task.type in sTaskQueues)) {\n if(sVL >= 1) {\n forge.log.verbose(cat, '[%s][%s] create queue [%s]',\n task.id, task.name, task.type);\n }\n // create the queue with the new task\n sTaskQueues[task.type] = [task];\n start(task);\n } else {\n // push the task onto the queue, it will be run after a task\n // with the same type completes\n sTaskQueues[options.type].push(task);\n }\n};\n\n/**\n * Cancels all tasks of the given type that haven't started yet.\n *\n * @param type the type of task to cancel.\n */\nforge.task.cancel = function(type) {\n // find the task queue\n if(type in sTaskQueues) {\n // empty all but the current task from the queue\n sTaskQueues[type] = [sTaskQueues[type][0]];\n }\n};\n\n/**\n * Creates a condition variable to synchronize tasks. To make a task wait\n * on the condition variable, call task.wait(condition). To notify all\n * tasks that are waiting, call condition.notify().\n *\n * @return the condition variable.\n */\nforge.task.createCondition = function() {\n var cond = {\n // all tasks that are blocked\n tasks: {}\n };\n\n /**\n * Causes the given task to block until notify is called. If the task\n * is already waiting on this condition then this is a no-op.\n *\n * @param task the task to cause to wait.\n */\n cond.wait = function(task) {\n // only block once\n if(!(task.id in cond.tasks)) {\n task.block();\n cond.tasks[task.id] = task;\n }\n };\n\n /**\n * Notifies all waiting tasks to wake up.\n */\n cond.notify = function() {\n // since unblock() will run the next task from here, make sure to\n // clear the condition's blocked task list before unblocking\n var tmp = cond.tasks;\n cond.tasks = {};\n for(var id in tmp) {\n tmp[id].unblock();\n }\n };\n\n return cond;\n};\n","/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = require('./forge');\nrequire('./aes');\nrequire('./aesCipherSuites');\nrequire('./asn1');\nrequire('./cipher');\nrequire('./debug');\nrequire('./des');\nrequire('./ed25519');\nrequire('./hmac');\nrequire('./kem');\nrequire('./log');\nrequire('./md.all');\nrequire('./mgf1');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./pkcs1');\nrequire('./pkcs12');\nrequire('./pkcs7');\nrequire('./pki');\nrequire('./prime');\nrequire('./prng');\nrequire('./pss');\nrequire('./random');\nrequire('./rc2');\nrequire('./ssh');\nrequire('./task');\nrequire('./tls');\nrequire('./util');\n","var forge = require('node-forge');\n\n// a hexString is considered negative if it's most significant bit is 1\n// because serial numbers use ones' complement notation\n// this RFC in section 4.1.2.2 requires serial numbers to be positive\n// http://www.ietf.org/rfc/rfc5280.txt\nfunction toPositiveHex(hexString){\n var mostSiginficativeHexAsInt = parseInt(hexString[0], 16);\n if (mostSiginficativeHexAsInt < 8){\n return hexString;\n }\n\n mostSiginficativeHexAsInt -= 8;\n return mostSiginficativeHexAsInt.toString() + hexString.substring(1);\n}\n\nfunction getAlgorithm(key) {\n switch (key) {\n case 'sha256':\n return forge.md.sha256.create();\n default:\n return forge.md.sha1.create();\n }\n}\n\n/**\n *\n * @param {forge.pki.CertificateField[]} attrs Attributes used for subject and issuer.\n * @param {object} options\n * @param {number} [options.days=365] the number of days before expiration\n * @param {number} [options.keySize=1024] the size for the private key in bits\n * @param {object} [options.extensions] additional extensions for the certificate\n * @param {string} [options.algorithm=\"sha1\"] The signature algorithm sha256 or sha1\n * @param {boolean} [options.pkcs7=false] include PKCS#7 as part of the output\n * @param {boolean} [options.clientCertificate=false] generate client cert signed by the original key\n * @param {string} [options.clientCertificateCN=\"John Doe jdoe123\"] client certificate's common name\n * @param {function} [done] Optional callback, if not provided the generation is synchronous\n * @returns\n */\nexports.generate = function generate(attrs, options, done) {\n if (typeof attrs === 'function') {\n done = attrs;\n attrs = undefined;\n } else if (typeof options === 'function') {\n done = options;\n options = {};\n }\n\n options = options || {};\n\n var generatePem = function (keyPair) {\n var cert = forge.pki.createCertificate();\n\n cert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9))); // the serial number can be decimal or hex (if preceded by 0x)\n\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n cert.validity.notAfter.setDate(cert.validity.notBefore.getDate() + (options.days || 365));\n\n attrs = attrs || [{\n name: 'commonName',\n value: 'example.org'\n }, {\n name: 'countryName',\n value: 'US'\n }, {\n shortName: 'ST',\n value: 'Virginia'\n }, {\n name: 'localityName',\n value: 'Blacksburg'\n }, {\n name: 'organizationName',\n value: 'Test'\n }, {\n shortName: 'OU',\n value: 'Test'\n }];\n\n cert.setSubject(attrs);\n cert.setIssuer(attrs);\n\n cert.publicKey = keyPair.publicKey;\n\n cert.setExtensions(options.extensions || [{\n name: 'basicConstraints',\n cA: true\n }, {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n }, {\n name: 'subjectAltName',\n altNames: [{\n type: 6, // URI\n value: 'http://example.org/webid#me'\n }]\n }]);\n\n cert.sign(keyPair.privateKey, getAlgorithm(options && options.algorithm));\n\n const fingerprint = forge.md.sha1\n .create()\n .update(forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes())\n .digest()\n .toHex()\n .match(/.{2}/g)\n .join(':');\n\n var pem = {\n private: forge.pki.privateKeyToPem(keyPair.privateKey),\n public: forge.pki.publicKeyToPem(keyPair.publicKey),\n cert: forge.pki.certificateToPem(cert),\n fingerprint: fingerprint,\n };\n\n if (options && options.pkcs7) {\n var p7 = forge.pkcs7.createSignedData();\n p7.addCertificate(cert);\n pem.pkcs7 = forge.pkcs7.messageToPem(p7);\n }\n\n if (options && options.clientCertificate) {\n var clientkeys = forge.pki.rsa.generateKeyPair(1024);\n var clientcert = forge.pki.createCertificate();\n clientcert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9)));\n clientcert.validity.notBefore = new Date();\n clientcert.validity.notAfter = new Date();\n clientcert.validity.notAfter.setFullYear(clientcert.validity.notBefore.getFullYear() + 1);\n\n var clientAttrs = JSON.parse(JSON.stringify(attrs));\n\n for(var i = 0; i < clientAttrs.length; i++) {\n if(clientAttrs[i].name === 'commonName') {\n if( options.clientCertificateCN )\n clientAttrs[i] = { name: 'commonName', value: options.clientCertificateCN };\n else\n clientAttrs[i] = { name: 'commonName', value: 'John Doe jdoe123' };\n }\n }\n\n clientcert.setSubject(clientAttrs);\n\n // Set the issuer to the parent key\n clientcert.setIssuer(attrs);\n\n clientcert.publicKey = clientkeys.publicKey;\n\n // Sign client cert with root cert\n clientcert.sign(keyPair.privateKey);\n\n pem.clientprivate = forge.pki.privateKeyToPem(clientkeys.privateKey);\n pem.clientpublic = forge.pki.publicKeyToPem(clientkeys.publicKey);\n pem.clientcert = forge.pki.certificateToPem(clientcert);\n\n if (options.pkcs7) {\n var clientp7 = forge.pkcs7.createSignedData();\n clientp7.addCertificate(clientcert);\n pem.clientpkcs7 = forge.pkcs7.messageToPem(clientp7);\n }\n }\n\n var caStore = forge.pki.createCaStore();\n caStore.addCertificate(cert);\n\n try {\n forge.pki.verifyCertificateChain(caStore, [cert],\n function (vfd, depth, chain) {\n if (vfd !== true) {\n throw new Error('Certificate could not be verified.');\n }\n return true;\n });\n }\n catch(ex) {\n throw new Error(ex);\n }\n\n return pem;\n };\n\n var keySize = options.keySize || 1024;\n\n if (done) { // async scenario\n return forge.pki.rsa.generateKeyPair({ bits: keySize }, function (err, keyPair) {\n if (err) { return done(err); }\n\n try {\n return done(null, generatePem(keyPair));\n } catch (ex) {\n return done(ex);\n }\n });\n }\n\n var keyPair = options.keyPair ? {\n privateKey: forge.pki.privateKeyFromPem(options.keyPair.privateKey),\n publicKey: forge.pki.publicKeyFromPem(options.keyPair.publicKey)\n } : forge.pki.rsa.generateKeyPair(keySize);\n\n return generatePem(keyPair);\n};\n"],"names":["forge","baseN","require$$0","require$$1","util","global","_createCipher","_updateBlock","registerAlgorithm","oids","asn1","_initialized","_init","_update","_padding","_k","_crypto","BigInteger","pki","privateKeyValidator","publicKeyValidator","contentInfoValidator","tls","sha512"],"mappings":";;;;;;;;;;;;;;;;;;;IAOAA,OAAc,GAAG;AACjB;AACA,EAAE,OAAO,EAAE;AACX,IAAI,iBAAiB,EAAE,KAAK;AAC5B,GAAG;AACH,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACkBD,IAAI,GAAG,GAAG,EAAE,CAAC;IACbC,OAAc,GAAG,GAAG,CAAC;AACrB;AACA;AACA,IAAI,iBAAiB,GAAG,EAAE,CAAC;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,CAAC,MAAM,GAAG,SAAS,KAAK,EAAE,QAAQ,EAAE,OAAO,E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ACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,UAAU,GAAG;AACtB,EAAE,IAAI,GAAG,IAAI,CAAC;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC5E;AACA;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC;AAC7B,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,EAAE,CAAC,EAAE;AAC/B,IAAI,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACtB,IAAI,KAAK,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GA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AAC,MAAM,EAAE,EAAE,CAAC,EAAE;AAC1C,MAAM,IAAI,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAC1B,MAAM,OAAO,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;AACnC,KAAK;AACL,GAAG;AACH;AACA,EAAE,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AACF;AACA;AACA;AACA;AACAA,KAAG,CAAC,gBAAgB,GAAG;AACvB,EAAE,eAAe,EAAE,0BAA0B;AAC7C,EAAE,uBAAuB,EAAE,kCAAkC;AAC7D,EAAE,mBAAmB,EAAE,8BAA8B;AACrD,EAAE,mBAAmB,EAAE,8BAA8B;AACrD,EAAE,mBAAmB,EAAE,8BAA8B;AACrD,EAAE,UAAU,EAAE,uCAAuC;AACrD,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAA,KAAG,CAAC,sBAAsB,GAAG,SAAS,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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AAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACvE,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACvE,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAA,KAAG,CAAC,YAAY,GAAG,SAAS,CAAC,EAAE,EAAE,EAAE;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,GAAG,GAAG,QAAQ,CAAC;AACrB;AACA;AACA,EAAE,IAAI,MAAM,GAAG,EAAE,CAAC,aAAa,GAAG,EAAE,CAAC,aAAa,CAAC;AACnD;AACA;AACA,EAAE,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE;AAC1B;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AAC;AAC9B,CAAC;;;;;;;"} \ No newline at end of file diff --git a/node_modules/vite/dist/node/chunks/dep-1be34a63.js b/node_modules/vite/dist/node/chunks/dep-1be34a63.js new file mode 100644 index 0000000..c69df64 --- /dev/null +++ b/node_modules/vite/dist/node/chunks/dep-1be34a63.js @@ -0,0 +1,77266 @@ +'use strict'; + +var fs$v = require('fs'); +var path$w = require('path'); +var require$$0$5 = require('os'); +var require$$0$4 = require('tty'); +var require$$0$7 = require('util'); +var require$$4$1 = require('net'); +var require$$0$b = require('events'); +var require$$0$a = require('url'); +var require$$1$3 = require('http'); +var require$$0$6 = require('stream'); +var resolve$4 = require('resolve'); +var require$$0$9 = require('module'); +var require$$1$4 = require('https'); +var require$$4$2 = require('tls'); +var require$$1$1 = require('crypto'); +var require$$0$8 = require('zlib'); +var require$$6 = require('assert'); +var require$$0$c = require('buffer'); +var qs = require('querystring'); +var require$$3$1 = require('repl'); +var require$$4 = require('vm'); +var require$$7 = require('console'); +var esbuild = require('esbuild'); +var require$$1$2 = require('worker_threads'); +var require$$1$5 = require('child_process'); +var readline = require('readline'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + n[k] = e[k]; + }); + } + n['default'] = e; + return n; +} + +var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$v); +var fs__namespace = /*#__PURE__*/_interopNamespace(fs$v); +var path__default = /*#__PURE__*/_interopDefaultLegacy(path$w); +var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$5); +var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); +var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$7); +var require$$4__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$4$1); +var require$$0__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$0$b); +var require$$0__default$7 = /*#__PURE__*/_interopDefaultLegacy(require$$0$a); +var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3); +var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$6); +var resolve__default = /*#__PURE__*/_interopDefaultLegacy(resolve$4); +var require$$0__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$0$9); +var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$4); +var require$$4__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$4$2); +var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1); +var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$8); +var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6); +var require$$0__default$8 = /*#__PURE__*/_interopDefaultLegacy(require$$0$c); +var qs__namespace = /*#__PURE__*/_interopNamespace(qs); +var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3$1); +var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4); +var require$$7__default = /*#__PURE__*/_interopDefaultLegacy(require$$7); +var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1$2); +var require$$1__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$1$5); +var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline); + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +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 ansiStyles$2 = {exports: {}}; + +var colorName$1 = { + "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] +}; + +/* MIT license */ + +/* eslint-disable no-mixed-operators */ +const cssKeywords$1 = colorName$1; + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +const reverseKeywords$1 = {}; +for (const key of Object.keys(cssKeywords$1)) { + reverseKeywords$1[cssKeywords$1[key]] = key; +} + +const convert$3 = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +var conversions$5 = convert$3; + +// Hide .channels and .labels properties +for (const model of Object.keys(convert$3)) { + if (!('channels' in convert$3[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert$3[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert$3[model].labels.length !== convert$3[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + const {channels, labels} = convert$3[model]; + delete convert$3[model].channels; + delete convert$3[model].labels; + Object.defineProperty(convert$3[model], 'channels', {value: channels}); + Object.defineProperty(convert$3[model], 'labels', {value: labels}); +} + +convert$3.rgb.hsl = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + const l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert$3.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert$3.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert$3.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert$3.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +function comparativeDistance$1(x, y) { + /* + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + */ + return ( + ((x[0] - y[0]) ** 2) + + ((x[1] - y[1]) ** 2) + + ((x[2] - y[2]) ** 2) + ); +} + +convert$3.rgb.keyword = function (rgb) { + const reversed = reverseKeywords$1[rgb]; + if (reversed) { + return reversed; + } + + let currentClosestDistance = Infinity; + let currentClosestKeyword; + + for (const keyword of Object.keys(cssKeywords$1)) { + const value = cssKeywords$1[keyword]; + + // Compute comparative distance + const distance = comparativeDistance$1(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + + return currentClosestKeyword; +}; + +convert$3.keyword.rgb = function (keyword) { + return cssKeywords$1[keyword]; +}; + +convert$3.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + + // Assume sRGB + r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); + g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); + b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); + + const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert$3.rgb.lab = function (rgb) { + const xyz = convert$3.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; +}; + +convert$3.hsl.rgb = function (hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + const t1 = 2 * l - t2; + + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert$3.hsl.hsv = function (hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert$3.hsv.rgb = function (hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - (s * f)); + const t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert$3.hsv.hsl = function (hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert$3.hwb.rgb = function (hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; + + // Wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + const n = wh + f * (v - wh); // Linear interpolation + + let r; + let g; + let b; + /* eslint-disable max-statements-per-line,no-multi-spaces */ + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + /* eslint-enable max-statements-per-line,no-multi-spaces */ + + return [r * 255, g * 255, b * 255]; +}; + +convert$3.cmyk.rgb = function (cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert$3.xyz.rgb = function (xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // Assume sRGB + r = r > 0.0031308 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert$3.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; +}; + +convert$3.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert$3.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + const c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert$3.lch.lab = function (lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert$3.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert$3.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + let ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert$3.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert$3.rgb.ansi16(convert$3.hsv.rgb(args), args[2]); +}; + +convert$3.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; + + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + const ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert$3.ansi16.rgb = function (args) { + let color = args % 10; + + // Handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + const mult = (~~(args > 50) + 1) * 0.5; + const r = ((color & 1) * mult) * 255; + const g = (((color >> 1) & 1) * mult) * 255; + const b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert$3.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert$3.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert$3.hex.rgb = function (args) { + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + let colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } + + const integer = parseInt(colorString, 16); + const r = (integer >> 16) & 0xFF; + const g = (integer >> 8) & 0xFF; + const b = integer & 0xFF; + + return [r, g, b]; +}; + +convert$3.rgb.hcg = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = (max - min); + let grayscale; + let hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert$3.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); + + let f = 0; + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert$3.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + + const c = s * v; + let f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert$3.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + const pure = [0, 0, 0]; + const hi = (h % 1) * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + + /* eslint-disable max-statements-per-line */ + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + /* eslint-enable max-statements-per-line */ + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert$3.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const v = c + g * (1.0 - c); + let f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert$3.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert$3.hcg.hwb = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert$3.hwb.hcg = function (hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert$3.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert$3.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert$3.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert$3.gray.hsl = function (args) { + return [0, 0, args[0]]; +}; + +convert$3.gray.hsv = convert$3.gray.hsl; + +convert$3.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert$3.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert$3.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert$3.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert$3.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; + +const conversions$4 = conversions$5; + +/* + This function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph$1() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions$4); + + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS$1(fromModel) { + const graph = buildGraph$1(); + const queue = [fromModel]; // Unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions$4[current]); + + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link$1(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion$1(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions$4[graph[toModel].parent][toModel]; + + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link$1(conversions$4[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +var route$3 = function (fromModel) { + const graph = deriveBFS$1(fromModel); + const conversion = {}; + + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; + + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion$1(toModel, graph); + } + + return conversion; +}; + +const conversions$3 = conversions$5; +const route$2 = route$3; + +const convert$2 = {}; + +const models$1 = Object.keys(conversions$3); + +function wrapRaw$1(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + return fn(args); + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded$1(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + const result = fn(args); + + // We're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models$1.forEach(fromModel => { + convert$2[fromModel] = {}; + + Object.defineProperty(convert$2[fromModel], 'channels', {value: conversions$3[fromModel].channels}); + Object.defineProperty(convert$2[fromModel], 'labels', {value: conversions$3[fromModel].labels}); + + const routes = route$2(fromModel); + const routeModels = Object.keys(routes); + + routeModels.forEach(toModel => { + const fn = routes[toModel]; + + convert$2[fromModel][toModel] = wrapRounded$1(fn); + convert$2[fromModel][toModel].raw = wrapRaw$1(fn); + }); +}); + +var colorConvert$1 = convert$2; + +(function (module) { + +const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +const ansi2ansi = n => n; +const rgb2rgb = (r, g, b) => [r, g, b]; + +const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); + + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + + return value; + }, + enumerable: true, + configurable: true + }); +}; + +/** @type {typeof import('color-convert')} */ +let colorConvert; +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = colorConvert$1; + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } + + return styles; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); +}(ansiStyles$2)); + +var hasFlag$3 = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; + +const os$5 = require$$0__default$1; +const tty = require$$0__default; +const hasFlag$2 = hasFlag$3; + +const {env: env$2} = process; + +let forceColor$1; +if (hasFlag$2('no-color') || + hasFlag$2('no-colors') || + hasFlag$2('color=false') || + hasFlag$2('color=never')) { + forceColor$1 = 0; +} else if (hasFlag$2('color') || + hasFlag$2('colors') || + hasFlag$2('color=true') || + hasFlag$2('color=always')) { + forceColor$1 = 1; +} + +if ('FORCE_COLOR' in env$2) { + if (env$2.FORCE_COLOR === 'true') { + forceColor$1 = 1; + } else if (env$2.FORCE_COLOR === 'false') { + forceColor$1 = 0; + } else { + forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3); + } +} + +function translateLevel$1(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor$1(haveStream, streamIsTTY) { + if (forceColor$1 === 0) { + return 0; + } + + if (hasFlag$2('color=16m') || + hasFlag$2('color=full') || + hasFlag$2('color=truecolor')) { + return 3; + } + + if (hasFlag$2('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor$1 === undefined) { + return 0; + } + + const min = forceColor$1 || 0; + + if (env$2.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os$5.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$2) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$2) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$2.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$2) { + const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$2.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$2.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { + return 1; + } + + if ('COLORTERM' in env$2) { + return 1; + } + + return min; +} + +function getSupportLevel$1(stream) { + const level = supportsColor$1(stream, stream && stream.isTTY); + return translateLevel$1(level); +} + +var supportsColor_1$1 = { + supportsColor: getSupportLevel$1, + stdout: translateLevel$1(supportsColor$1(true, tty.isatty(1))), + stderr: translateLevel$1(supportsColor$1(true, tty.isatty(2))) +}; + +const stringReplaceAll$1 = (string, substring, replacer) => { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } + + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; +}; + +const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ''; + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; +}; + +var util$c = { + stringReplaceAll: stringReplaceAll$1, + stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1 +}; + +const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; + +const ESCAPES$1 = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); + +function unescape$2(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; + + if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } + + return ESCAPES$1.get(c) || c; +} + +function parseArguments$1(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); + } else if ((matches = chunk.match(STRING_REGEX$1))) { + results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$2(escape) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseStyle$1(style) { + STYLE_REGEX$1.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX$1.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments$1(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle$1(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } + + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } + + return current; +} + +var templates$1 = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape$2(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string)); + styles.push({inverse, styles: parseStyle$1(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle$1(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMessage); + } + + return chunks.join(''); +}; + +const ansiStyles$1 = ansiStyles$2.exports; +const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1$1; +const { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +} = util$c; + +const {isArray: isArray$4} = Array; + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = [ + 'ansi', + 'ansi', + 'ansi256', + 'ansi16m' +]; + +const styles = Object.create(null); + +const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } + + // Detect level if not set manually + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; + +class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } +} + +const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; + + chalk.template.Instance = ChalkClass; + + return chalk.template; +}; + +function Chalk(options) { + return chalkFactory(options); +} + +for (const [styleName, style] of Object.entries(ansiStyles$1)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, {value: builder}); + return builder; + } + }; +} + +styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + } +}; + +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; + +for (const model of usedModels) { + styles[model] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} + +for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} + +const proto$1 = Object.defineProperties(() => {}, { + ...styles, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } +}); + +const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + + return { + open, + close, + openAll, + closeAll, + parent + }; +}; + +const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray$4(arguments_[0]) && isArray$4(arguments_[0].raw)) { + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } + + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); + }; + + // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + Object.setPrototypeOf(builder, proto$1); + + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; + + return builder; +}; + +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } + + let styler = self._styler; + + if (styler === undefined) { + return string; + } + + const {openAll, closeAll} = styler; + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll(string, styler.close, styler.open); + + styler = styler.parent; + } + } + + // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + const lfIndex = string.indexOf('\n'); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } + + return openAll + string + closeAll; +}; + +let template; +const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; + + if (!isArray$4(firstString) || !isArray$4(firstString.raw)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } + + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; + + for (let i = 1; i < firstString.length; i++) { + parts.push( + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); + } + + if (template === undefined) { + template = templates$1; + } + + return template(chalk, parts.join('')); +}; + +Object.defineProperties(Chalk.prototype, styles); + +const chalk$2 = Chalk(); // eslint-disable-line new-cap +chalk$2.supportsColor = stdoutColor; +chalk$2.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap +chalk$2.stderr.supportsColor = stderrColor; + +var source = chalk$2; + +var dist$4 = {}; + +var Stream$1 = require$$0__default$2; +var writeMethods = ["write", "end", "destroy"]; +var readMethods = ["resume", "pause"]; +var readEvents = ["data", "close"]; +var slice$2 = Array.prototype.slice; + +var duplexer$1 = duplex; + +function forEach (arr, fn) { + if (arr.forEach) { + return arr.forEach(fn) + } + + for (var i = 0; i < arr.length; i++) { + fn(arr[i], i); + } +} + +function duplex(writer, reader) { + var stream = new Stream$1(); + var ended = false; + + forEach(writeMethods, proxyWriter); + + forEach(readMethods, proxyReader); + + forEach(readEvents, proxyStream); + + reader.on("end", handleEnd); + + writer.on("drain", function() { + stream.emit("drain"); + }); + + writer.on("error", reemit); + reader.on("error", reemit); + + stream.writable = writer.writable; + stream.readable = reader.readable; + + return stream + + function proxyWriter(methodName) { + stream[methodName] = method; + + function method() { + return writer[methodName].apply(writer, arguments) + } + } + + function proxyReader(methodName) { + stream[methodName] = method; + + function method() { + stream.emit(methodName); + var func = reader[methodName]; + if (func) { + return func.apply(reader, arguments) + } + reader.emit(methodName); + } + } + + function proxyStream(methodName) { + reader.on(methodName, reemit); + + function reemit() { + var args = slice$2.call(arguments); + args.unshift(methodName); + stream.emit.apply(stream, args); + } + } + + function handleEnd() { + if (ended) { + return + } + ended = true; + var args = slice$2.call(arguments); + args.unshift("end"); + stream.emit.apply(stream, args); + } + + function reemit(err) { + stream.emit("error", err); + } +} + +Object.defineProperty(dist$4, "__esModule", { value: true }); +const zlib_1 = require$$0__default$4; +const stream_1$6 = require$$0__default$2; +const fs_1 = fs__default; +const util_1$3 = require$$0__default$3; +const duplexer = duplexer$1; +const readFilePromise = util_1$3.promisify(fs_1.readFile); +const bufferFormatter = (incoming) => typeof incoming === 'string' ? Buffer.from(incoming, 'utf8') : incoming; +const optionFormatter = (passed, toEncode) => ({ + params: { + [zlib_1.constants.BROTLI_PARAM_MODE]: passed && 'mode' in passed && passed.mode || zlib_1.constants.BROTLI_DEFAULT_MODE, + [zlib_1.constants.BROTLI_PARAM_QUALITY]: passed && 'quality' in passed && passed.quality || zlib_1.constants.BROTLI_MAX_QUALITY, + [zlib_1.constants.BROTLI_PARAM_SIZE_HINT]: toEncode ? toEncode.byteLength : 0, + } +}); +/** + * @param incoming Either a Buffer or string of the value to encode. + * @param options Subset of Encoding Parameters. + * @return Promise that resolves with the encoded Buffer length. + */ +async function size(incoming, options) { + const buffer = bufferFormatter(incoming); + return new Promise(function (resolve, reject) { + zlib_1.brotliCompress(buffer, optionFormatter(options, buffer), (error, result) => { + if (error !== null) { + reject(error); + } + resolve(result.byteLength); + }); + }); +} +var _default = dist$4.default = size; +/** + * @param incoming Either a Buffer or string of the value to encode. + * @param options Subset of Encoding Parameters. + * @return Length of encoded Buffer. + */ +function sync$c(incoming, options) { + const buffer = bufferFormatter(incoming); + return zlib_1.brotliCompressSync(buffer, optionFormatter(options, buffer)).byteLength; +} +dist$4.sync = sync$c; +/** + * @param options + * @return PassThroughStream for the contents being compressed + */ +function stream$8(options) { + const input = new stream_1$6.PassThrough(); + const output = new stream_1$6.PassThrough(); + const wrapper = duplexer(input, output); + let size = 0; + const brotli = zlib_1.createBrotliCompress(optionFormatter(options)) + .on('data', buf => { + size += buf.length; + }) + .on('error', () => { + wrapper.brotliSize = 0; + }) + .on('end', () => { + wrapper.brotliSize = size; + wrapper.emit('brotli-size', size); + output.end(); + }); + input.pipe(brotli); + input.pipe(output, { end: false }); + return wrapper; +} +dist$4.stream = stream$8; +/** + * @param path File Path for the file to compress. + * @param options Subset of Encoding Parameters. + * @return Promise that resolves with size of encoded file. + */ +async function file(path, options) { + const file = await readFilePromise(path); + return (await size(file, options)); +} +dist$4.file = file; +/** + * @param path File Path for the file to compress. + * @param options Subset of Encoding Parameters. + * @return size of encoded file. + */ +function fileSync(path, options) { + const file = fs_1.readFileSync(path); + return sync$c(file, options); +} +dist$4.fileSync = fileSync; + +var src$3 = {exports: {}}; + +var browser$2 = {exports: {}}; + +/** + * 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 = 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$l(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$l(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; + 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(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) { + 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.substr(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$e = setup; + +/* eslint-env browser */ + +(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$e(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$2, browser$2.exports)); + +var node$2 = {exports: {}}; + +/** + * Module dependencies. + */ + +(function (module, exports) { +const tty = require$$0__default; +const util = require$$0__default$3; + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + '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 = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = supportsColor_1$1; + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = common$e(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; +}(node$2, node$2.exports)); + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + src$3.exports = browser$2.exports; +} else { + src$3.exports = node$2.exports; +} + +var debug$d = src$3.exports; + +const DEFAULT_MAIN_FIELDS = [ + 'module', + 'jsnext:main', + 'jsnext' +]; +const DEFAULT_EXTENSIONS = [ + '.mjs', + '.js', + '.ts', + '.jsx', + '.tsx', + '.json' +]; +const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/; +const OPTIMIZABLE_ENTRY_RE = /\.(?:m?js|ts)$/; +const SPECIAL_QUERY_RE = /[\?&](?:worker|sharedworker|raw|url)\b/; +/** + * Prefix for resolved fs paths, since windows paths may not be valid as URLs. + */ +const FS_PREFIX = `/@fs/`; +/** + * Prefix for resolved Ids that are not valid browser import specifiers + */ +const VALID_ID_PREFIX = `/@id/`; +/** + * Some Rollup plugins use ids that starts with the null byte \0 to avoid + * collisions, but it is not permitted in import URLs so we have to replace + * them. + */ +const NULL_BYTE_PLACEHOLDER = `__x00__`; +const CLIENT_PUBLIC_PATH = `/@vite/client`; +const ENV_PUBLIC_PATH = `/@vite/env`; +// eslint-disable-next-line node/no-missing-require +const CLIENT_ENTRY = require.resolve('vite/dist/client/client.mjs'); +// eslint-disable-next-line node/no-missing-require +const ENV_ENTRY = require.resolve('vite/dist/client/env.mjs'); +const CLIENT_DIR = path__default.dirname(CLIENT_ENTRY); +// ** READ THIS ** before editing `KNOWN_ASSET_TYPES`. +// If you add an asset to `KNOWN_ASSET_TYPES`, make sure to also add it +// to the TypeScript declaration file `packages/vite/client.d.ts`. +const KNOWN_ASSET_TYPES = [ + // images + 'png', + 'jpe?g', + 'gif', + 'svg', + 'ico', + 'webp', + 'avif', + // media + 'mp4', + 'webm', + 'ogg', + 'mp3', + 'wav', + 'flac', + 'aac', + // fonts + 'woff2?', + 'eot', + 'ttf', + 'otf', + // other + 'wasm', + 'webmanifest', + 'pdf' +]; +const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`); +const DEP_VERSION_RE = /[\?&](v=[\w\.-]+)\b/; + +const {builtinModules} = require$$0__default$5; + +const ignoreList = [ + 'sys' +]; + +// eslint-disable-next-line node/no-deprecated-api +var builtinModules_1 = (builtinModules || Object.keys(process.binding('natives'))) + .filter(x => !/^_|^(internal|v8|node-inspect)\/|\//.test(x) && !ignoreList.includes(x)) + .sort(); + +var charToInteger$1 = {}; +var chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +for (var i$2 = 0; i$2 < chars$2.length; i$2++) { + charToInteger$1[chars$2.charCodeAt(i$2)] = i$2; +} +function decode(mappings) { + var decoded = []; + var line = []; + var segment = [ + 0, + 0, + 0, + 0, + 0, + ]; + var j = 0; + for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) { + var c = mappings.charCodeAt(i); + if (c === 44) { // "," + segmentify(line, segment, j); + j = 0; + } + else if (c === 59) { // ";" + segmentify(line, segment, j); + j = 0; + decoded.push(line); + line = []; + segment[0] = 0; + } + else { + var integer = charToInteger$1[c]; + if (integer === undefined) { + throw new Error('Invalid character (' + String.fromCharCode(c) + ')'); + } + var hasContinuationBit = integer & 32; + integer &= 31; + value += integer << shift; + if (hasContinuationBit) { + shift += 5; + } + else { + var shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = value === 0 ? -0x80000000 : -value; + } + segment[j] += value; + j++; + value = shift = 0; // reset + } + } + } + segmentify(line, segment, j); + decoded.push(line); + return decoded; +} +function segmentify(line, segment, j) { + // This looks ugly, but we're creating specialized arrays with a specific + // length. This is much faster than creating a new array (which v8 expands to + // a capacity of 17 after pushing the first item), or slicing out a subarray + // (which is slow). Length 4 is assumed to be the most frequent, followed by + // length 5 (since not everything will have an associated name), followed by + // length 1 (it's probably rare for a source substring to not have an + // associated segment data). + if (j === 4) + line.push([segment[0], segment[1], segment[2], segment[3]]); + else if (j === 5) + line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]); + else if (j === 1) + line.push([segment[0]]); +} +function encode$1(decoded) { + var sourceFileIndex = 0; // second field + var sourceCodeLine = 0; // third field + var sourceCodeColumn = 0; // fourth field + var nameIndex = 0; // fifth field + var mappings = ''; + for (var i = 0; i < decoded.length; i++) { + var line = decoded[i]; + if (i > 0) + mappings += ';'; + if (line.length === 0) + continue; + var generatedCodeColumn = 0; // first field + var lineMappings = []; + for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { + var segment = line_1[_i]; + var segmentMappings = encodeInteger$1(segment[0] - generatedCodeColumn); + generatedCodeColumn = segment[0]; + if (segment.length > 1) { + segmentMappings += + encodeInteger$1(segment[1] - sourceFileIndex) + + encodeInteger$1(segment[2] - sourceCodeLine) + + encodeInteger$1(segment[3] - sourceCodeColumn); + sourceFileIndex = segment[1]; + sourceCodeLine = segment[2]; + sourceCodeColumn = segment[3]; + } + if (segment.length === 5) { + segmentMappings += encodeInteger$1(segment[4] - nameIndex); + nameIndex = segment[4]; + } + lineMappings.push(segmentMappings); + } + mappings += lineMappings.join(','); + } + return mappings; +} +function encodeInteger$1(num) { + var result = ''; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + var clamped = num & 31; + num >>>= 5; + if (num > 0) { + clamped |= 32; + } + result += chars$2[clamped]; + } while (num > 0); + return result; +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Creates a brand new (prototype-less) object with the enumerable-own + * properties of `target`. Any enumerable-own properties from `source` which + * are not present on `target` will be copied as well. + */ +function defaults(target, source) { + return Object.assign(Object.create(null), source, target); +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Decodes an input sourcemap into a `DecodedSourceMap` sourcemap object. + * + * Valid input maps include a `DecodedSourceMap`, a `RawSourceMap`, or JSON + * representations of either type. + */ +function decodeSourceMap(map) { + if (typeof map === 'string') { + map = JSON.parse(map); + } + let { mappings } = map; + if (typeof mappings === 'string') { + mappings = sortMappings(decode(mappings), true); + } + else { + // Clone the Line so that we can sort it. We don't want to mutate an array + // that we don't own directly. + mappings = sortMappings(mappings, false); + } + return defaults({ mappings }, map); +} +function firstUnsortedSegmentLine(mappings) { + for (let i = 0; i < mappings.length; i++) { + const segments = mappings[i]; + for (let j = 1; j < segments.length; j++) { + if (segments[j][0] < segments[j - 1][0]) { + return i; + } + } + } + return mappings.length; +} +function sortMappings(mappings, owned) { + const unosrtedIndex = firstUnsortedSegmentLine(mappings); + if (unosrtedIndex === mappings.length) + return mappings; + if (!owned) + mappings = mappings.slice(); + for (let i = unosrtedIndex; i < mappings.length; i++) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function sortSegments(segments, owned) { + if (!owned) + segments = segments.slice(); + return segments.sort(segmentComparator); +} +function segmentComparator(a, b) { + return a[0] - b[0]; +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified + * source file. Recursive segment tracing ends at the `OriginalSource`. + */ +class OriginalSource { + constructor(filename, content) { + this.filename = filename; + this.content = content; + } + /** + * Tracing a `SourceMapSegment` ends when we get to an `OriginalSource`, + * meaning this line/column location originated from this source file. + */ + traceSegment(line, column, name) { + return { column, line, name, source: this }; + } +} + +/* istanbul ignore next */ +const Url$1 = (typeof URL !== 'undefined' ? URL : require('url').URL); +// Matches "..", which must be preceeded by "/" or the start of the string, and +// must be followed by a "/". We do not eat the following "/", so that the next +// iteration can match on it. +const parentRegex = /(^|\/)\.\.(?=\/|$)/g; +function isAbsoluteUrl(url) { + try { + return !!new Url$1(url); + } + catch (e) { + return false; + } +} +/** + * Creates a directory name that is guaranteed to not be in `str`. + */ +function uniqInStr(str) { + let uniq = String(Math.random()).slice(2); + while (str.indexOf(uniq) > -1) { + /* istanbul ignore next */ + uniq += uniq; + } + return uniq; +} +/** + * Removes the filename from the path (everything trailing the last "/"). This + * is only safe to call on a path, never call with an absolute or protocol + * relative URL. + */ +function stripPathFilename(path) { + path = normalizePath$5(path); + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +/** + * Normalizes a protocol-relative URL, but keeps it protocol relative by + * stripping out the protocl before returning it. + */ +function normalizeProtocolRelative(input, absoluteBase) { + const { href, protocol } = new Url$1(input, absoluteBase); + return href.slice(protocol.length); +} +/** + * Normalizes a simple path (one that has no ".."s, or is absolute so ".."s can + * be normalized absolutely). + */ +function normalizeSimplePath(input) { + const { href } = new Url$1(input, 'https://foo.com/'); + return href.slice('https://foo.com/'.length); +} +/** + * Normalizes a path, ensuring that excess ".."s are preserved for relative + * paths in the output. + * + * If the input is absolute, this will return an absolutey normalized path, but + * it will not have a leading "/". + * + * If the input has a leading "..", the output will have a leading "..". + * + * If the input has a leading ".", the output will not have a leading "." + * unless there are too many ".."s, in which case there will be a leading "..". + */ +function normalizePath$5(input) { + // If there are no ".."s, we can treat this as if it were an absolute path. + // The return won't be an absolute path, so it's easy. + if (!parentRegex.test(input)) + return normalizeSimplePath(input); + // We already found one "..". Let's see how many there are. + let total = 1; + while (parentRegex.test(input)) + total++; + // If there are ".."s, we need to prefix the the path with the same number of + // unique directories. This is to ensure that we "remember" how many parent + // directories we are accessing. Eg, "../../.." must keep 3, and "foo/../.." + // must keep 1. + const uniqDirectory = `z${uniqInStr(input)}/`; + // uniqDirectory is just a "z", followed by numbers, followed by a "/". So + // generating a runtime regex from it is safe. We'll use this search regex to + // strip out our uniq directory names and insert any needed ".."s. + const search = new RegExp(`^(?:${uniqDirectory})*`); + // Now we can resolve the total path. If there are excess ".."s, they will + // eliminate one or more of the unique directories we prefix with. + const relative = normalizeSimplePath(uniqDirectory.repeat(total) + input); + // We can now count the number of unique directories that were eliminated. If + // there were 3, and 1 was eliminated, we know we only need to add 1 "..". If + // 2 were eliminated, we need to insert 2 ".."s. If all 3 were eliminated, + // then we need 3, etc. This replace is guranteed to match (it may match 0 or + // more times), and we can count the total match to see how many were eliminated. + return relative.replace(search, (all) => { + const leftover = all.length / uniqDirectory.length; + return '../'.repeat(total - leftover); + }); +} +/** + * Attempts to resolve `input` URL relative to `base`. + */ +function resolve$3(input, base) { + if (!base) + base = ''; + // Absolute URLs are very easy to resolve right. + if (isAbsoluteUrl(input)) + return new Url$1(input).href; + if (base) { + // Absolute URLs are easy... + if (isAbsoluteUrl(base)) + return new Url$1(input, base).href; + // If base is protocol relative, we'll resolve with it but keep the result + // protocol relative. + if (base.startsWith('//')) + return normalizeProtocolRelative(input, `https:${base}`); + } + // Normalize input, but keep it protocol relative. We know base doesn't supply + // a protocol, because that would have been handled above. + if (input.startsWith('//')) + return normalizeProtocolRelative(input, 'https://foo.com/'); + // We now know that base (if there is one) and input are paths. We've handled + // both absolute and protocol-relative variations above. + // Absolute paths don't need any special handling, because they cannot have + // extra "." or ".."s. That'll all be stripped away. Input takes priority here, + // because if input is an absolute path, base path won't affect it in any way. + if (input.startsWith('/')) + return '/' + normalizeSimplePath(input); + // Since input and base are paths, we need to join them to do any further + // processing. Paths are joined at the directory level, so we need to remove + // the base's filename before joining. We also know that input does not have a + // leading slash, and that the stripped base will have a trailing slash if + // there are any directories (or it'll be empty). + const joined = stripPathFilename(base) + input; + // If base is an absolute path, then input will be relative to it. + if (base.startsWith('/')) + return '/' + normalizeSimplePath(joined); + // We now know both base (if there is one) and input are relative paths. + const relative = normalizePath$5(joined); + // If base started with a leading ".", or there is no base and input started + // with a ".", then we need to ensure that the relative path starts with a + // ".". We don't know if relative starts with a "..", though, so check before + // prepending. + if ((base || input).startsWith('.') && !relative.startsWith('.')) { + return './' + relative; + } + return relative; +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function resolve$1$1(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolve$3(input, base); +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A binary search implementation that returns the index if a match is found, + * or the negated index of where the `needle` should be inserted. + * + * The `comparator` callback receives both the `item` under comparison and the + * needle we are searching for. It must return `0` if the `item` is a match, + * any negative number if `item` is too small (and we must search after it), or + * any positive number if the `item` is too large (and we must search before + * it). + * + * If no match is found, a negated index of where to insert the `needle` is + * returned. This negated index is guaranteed to be less than 0. To insert an + * item, negate it (again) and splice: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, -2); + * assert.equal(~index, 1); + * array.splice(~index, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +function binarySearch$4(haystack, needle, comparator, low, high) { + low = Math.max(low, 0); + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = comparator(haystack[mid], needle); + if (cmp === 0) { + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + return ~low; +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * FastStringArray acts like a `Set` (allowing only one occurrence of a string + * `key`), but provides the index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of + * the backing array, like how `sourcesContent[i]` is the source content + * associated with `source[i]`, and there are never duplicates. + */ +class FastStringArray { + constructor() { + this.indexes = Object.create(null); + this.array = []; + } + /** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ + put(key) { + const { array, indexes } = this; + // The key may or may not be present. If it is present, it's a number. + let index = indexes[key]; + // If it's not yet present, we need to insert it and track the index in the + // indexes. + if (index === undefined) { + index = indexes[key] = array.length; + array.push(key); + } + return index; + } +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SourceMapTree represents a single sourcemap, with the ability to trace + * mappings into its child nodes (which may themselves be SourceMapTrees). + */ +class SourceMapTree { + constructor(map, sources) { + this.map = map; + this.sources = sources; + this.lastLine = 0; + this.lastColumn = 0; + this.lastIndex = 0; + } + /** + * traceMappings is only called on the root level SourceMapTree, and begins + * the process of resolving each mapping in terms of the original source + * files. + */ + traceMappings() { + const mappings = []; + const names = new FastStringArray(); + const sources = new FastStringArray(); + const sourcesContent = []; + const { mappings: rootMappings, names: rootNames } = this.map; + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + const tracedSegments = []; + let lastTraced = undefined; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + // 1-length segments only move the current generated column, there's no + // source information to gather from it. + if (segment.length === 1) + continue; + const source = this.sources[segment[1]]; + const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + if (!traced) + continue; + // So we traced a segment down into its original source file. Now push a + // new segment pointing to this location. + const { column, line, name } = traced; + const { content, filename } = traced.source; + // Store the source location, and ensure we keep sourcesContent up to + // date with the sources array. + const sourceIndex = sources.put(filename); + sourcesContent[sourceIndex] = content; + if (lastTraced && + lastTraced[1] === sourceIndex && + lastTraced[2] === line && + lastTraced[3] === column) { + // This is a duplicate mapping pointing at the exact same starting point in the source file. + // It doesn't provide any new information, and only bloats the sourcemap. + continue; + } + // This looks like unnecessary duplication, but it noticeably increases + // performance. If we were to push the nameIndex onto length-4 array, v8 + // would internally allocate 22 slots! That's 68 wasted bytes! Array + // literals have the same capacity as their length, saving memory. + if (name) { + lastTraced = [segment[0], sourceIndex, line, column, names.put(name)]; + } + else { + lastTraced = [segment[0], sourceIndex, line, column]; + } + tracedSegments.push(lastTraced); + } + mappings.push(tracedSegments); + } + // TODO: Make all sources relative to the sourceRoot. + return defaults({ + mappings, + names: names.array, + sources: sources.array, + sourcesContent, + }, this.map); + } + /** + * traceSegment is only called on children SourceMapTrees. It recurses down + * into its own child SourceMapTrees, until we find the original source map. + */ + traceSegment(line, column, name) { + const { mappings, names } = this.map; + // It's common for parent sourcemaps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= mappings.length) + return null; + const segments = mappings[line]; + if (segments.length === 0) + return null; + let low = 0; + let high = segments.length - 1; + if (line === this.lastLine) { + if (column >= this.lastColumn) { + low = this.lastIndex; + } + else { + high = this.lastIndex; + } + } + let index = binarySearch$4(segments, column, segmentComparator$1, low, high); + this.lastLine = line; + this.lastColumn = column; + if (index === -1) { + this.lastIndex = index; + return null; // we come before any mapped segment + } + // If we can't find a segment that lines up to this column, we use the + // segment before. + if (index < 0) { + index = ~index - 1; + } + this.lastIndex = index; + const segment = segments[index]; + // 1-length segments only move the current generated column, there's no + // source information to gather from it. + if (segment.length === 1) + return null; + const source = this.sources[segment[1]]; + // So now we can recurse down, until we hit the original source file. + return source.traceSegment(segment[2], segment[3], + // A child map's recorded name for this segment takes precedence over the + // parent's mapped name. Imagine a mangler changing the name over, etc. + segment.length === 5 ? names[segment[4]] : name); + } +} +function segmentComparator$1(segment, column) { + return segment[0] - column; +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Removes the filename from a path. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; +} +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +function buildSourceMapTree(input, loader, relativeRoot) { + const maps = asArray(input).map(decodeSourceMap); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length !== 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + const { sourceRoot, sources, sourcesContent } = map; + const children = sources.map((sourceFile, i) => { + // Each source file is loaded relative to the sourcemap's own sourceRoot, + // which is itself relative to the sourcemap's parent. + const uri = resolve$1$1(sourceFile || '', resolve$1$1(sourceRoot || '', stripFilename(relativeRoot))); + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(uri); + // If there is no sourcemap, then it is an unmodified source file. + if (!sourceMap) { + // The source file's actual contents must be included in the sourcemap + // (done when generating the sourcemap) for it to be included as a + // sourceContent in the output sourcemap. + const sourceContent = sourcesContent ? sourcesContent[i] : null; + return new OriginalSource(uri, sourceContent); + } + // Else, it's a real sourcemap, and we need to recurse into it to load its + // source files. + return buildSourceMapTree(decodeSourceMap(sourceMap), loader, uri); + }); + let tree = new SourceMapTree(map, children); + for (let i = maps.length - 1; i >= 0; i--) { + tree = new SourceMapTree(maps[i], [tree]); + } + return tree; +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +class SourceMap$1 { + constructor(map, options) { + this.version = 3; // SourceMap spec says this should be first. + if ('file' in map) + this.file = map.file; + this.mappings = options.decodedMappings ? map.mappings : encode$1(map.mappings); + this.names = map.names; + // TODO: We first need to make all source URIs relative to the sourceRoot + // before we can support a sourceRoot. + // if ('sourceRoot' in map) this.sourceRoot = map.sourceRoot; + this.sources = map.sources; + if (!options.excludeContent && 'sourcesContent' in map) { + this.sourcesContent = map.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +} + +/** + * Copyright 2019 The AMP HTML Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const graph = buildSourceMapTree(input, loader); + return new SourceMap$1(graph.traceMappings(), opts); +} + +function slash$3(p) { + return p.replace(/\\/g, '/'); +} +// Strip valid id prefix. This is prepended to resolved Ids that are +// not valid browser import specifiers by the importAnalysis plugin. +function unwrapId$1(id) { + return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length) : id; +} +const flattenId = (id) => id.replace(/(\s*>\s*)/g, '__').replace(/[\/\.]/g, '_'); +const normalizeId$1 = (id) => id.replace(/(\s*>\s*)/g, ' > '); +function isBuiltin(id) { + return builtinModules_1.includes(id); +} +const bareImportRE = /^[\w@](?!.*:\/\/)/; +const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//; +let isRunningWithYarnPnp; +try { + isRunningWithYarnPnp = Boolean(require('pnpapi')); +} +catch { } +const ssrExtensions = ['.js', '.cjs', '.json', '.node']; +function resolveFrom$3(id, basedir, ssr = false) { + return resolve__default.sync(id, { + basedir, + extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS, + // necessary to work with pnpm + preserveSymlinks: isRunningWithYarnPnp || false + }); +} +/** + * like `resolveFrom` but supports resolving `>` path in `id`, + * for example: `foo > bar > baz` + */ +function nestedResolveFrom(id, basedir) { + const pkgs = id.split('>').map((pkg) => pkg.trim()); + try { + for (const pkg of pkgs) { + basedir = resolveFrom$3(pkg, basedir); + } + } + catch { } + return basedir; +} +// set in bin/vite.js +const filter$1 = process.env.VITE_DEBUG_FILTER; +const DEBUG$1 = process.env.DEBUG; +function createDebugger(namespace, options = {}) { + const log = debug$d(namespace); + const { onlyWhenFocused } = options; + const focus = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace; + return (msg, ...args) => { + if (filter$1 && !msg.includes(filter$1)) { + return; + } + if (onlyWhenFocused && !(DEBUG$1 === null || DEBUG$1 === void 0 ? void 0 : DEBUG$1.includes(focus))) { + return; + } + log(msg, ...args); + }; +} +const isWindows$4 = require$$0__default$1.platform() === 'win32'; +const VOLUME_RE = /^[A-Z]:/i; +function normalizePath$4(id) { + return path__default.posix.normalize(isWindows$4 ? slash$3(id) : id); +} +function fsPathFromId(id) { + const fsPath = normalizePath$4(id.slice(FS_PREFIX.length)); + return fsPath.startsWith('/') || fsPath.match(VOLUME_RE) + ? fsPath + : `/${fsPath}`; +} +function ensureVolumeInPath(file) { + return isWindows$4 ? path__default.resolve(file) : file; +} +const queryRE = /\?.*$/s; +const hashRE = /#.*$/s; +const cleanUrl = (url) => url.replace(hashRE, '').replace(queryRE, ''); +const externalRE = /^(https?:)?\/\//; +const isExternalUrl = (url) => externalRE.test(url); +const dataUrlRE = /^\s*data:/i; +const isDataUrl = (url) => dataUrlRE.test(url); +const knownJsSrcRE = /\.((j|t)sx?|mjs|vue|marko|svelte)($|\?)/; +const isJSRequest = (url) => { + url = cleanUrl(url); + if (knownJsSrcRE.test(url)) { + return true; + } + if (!path__default.extname(url) && !url.endsWith('/')) { + return true; + } + return false; +}; +const importQueryRE = /(\?|&)import=?(?:&|$)/; +const internalPrefixes = [ + FS_PREFIX, + VALID_ID_PREFIX, + CLIENT_PUBLIC_PATH, + ENV_PUBLIC_PATH +]; +const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`); +const trailingSeparatorRE = /[\?&]$/; +const isImportRequest = (url) => importQueryRE.test(url); +const isInternalRequest = (url) => InternalPrefixRE.test(url); +function removeImportQuery(url) { + return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, ''); +} +function injectQuery(url, queryToInject) { + // encode percents for consistent behavior with pathToFileURL + // see #2614 for details + let resolvedUrl = new require$$0$a.URL(url.replace(/%/g, '%25'), 'relative:///'); + if (resolvedUrl.protocol !== 'relative:') { + resolvedUrl = require$$0$a.pathToFileURL(url); + } + let { protocol, pathname, search, hash } = resolvedUrl; + if (protocol === 'file:') { + pathname = pathname.slice(1); + } + pathname = decodeURIComponent(pathname); + return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`; +} +const timestampRE = /\bt=\d{13}&?\b/; +function removeTimestampQuery(url) { + return url.replace(timestampRE, '').replace(trailingSeparatorRE, ''); +} +async function asyncReplace(input, re, replacer) { + let match; + let remaining = input; + let rewritten = ''; + while ((match = re.exec(remaining))) { + rewritten += remaining.slice(0, match.index); + rewritten += await replacer(match); + remaining = remaining.slice(match.index + match[0].length); + } + rewritten += remaining; + return rewritten; +} +function timeFrom(start, subtract = 0) { + const time = Date.now() - start - subtract; + const timeString = (time + `ms`).padEnd(5, ' '); + if (time < 10) { + return source.green(timeString); + } + else if (time < 50) { + return source.yellow(timeString); + } + else { + return source.red(timeString); + } +} +/** + * pretty url for logging. + */ +function prettifyUrl(url, root) { + url = removeTimestampQuery(url); + const isAbsoluteFile = url.startsWith(root); + if (isAbsoluteFile || url.startsWith(FS_PREFIX)) { + let file = path__default.relative(root, isAbsoluteFile ? url : fsPathFromId(url)); + const seg = file.split('/'); + const npmIndex = seg.indexOf(`node_modules`); + const isSourceMap = file.endsWith('.map'); + if (npmIndex > 0) { + file = seg[npmIndex + 1]; + if (file.startsWith('@')) { + file = `${file}/${seg[npmIndex + 2]}`; + } + file = `npm: ${source.dim(file)}${isSourceMap ? ` (source map)` : ``}`; + } + return source.dim(file); + } + else { + return source.dim(url); + } +} +function isObject$3(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} +function isDefined(value) { + return value != null; +} +function lookupFile(dir, formats, pathOnly = false) { + for (const format of formats) { + const fullPath = path__default.join(dir, format); + if (fs__default.existsSync(fullPath) && fs__default.statSync(fullPath).isFile()) { + return pathOnly ? fullPath : fs__default.readFileSync(fullPath, 'utf-8'); + } + } + const parentDir = path__default.dirname(dir); + if (parentDir !== dir) { + return lookupFile(parentDir, formats, pathOnly); + } +} +const splitRE = /\r?\n/; +const range$1 = 2; +function pad$1(source, n = 2) { + const lines = source.split(splitRE); + return lines.map((l) => ` `.repeat(n) + l).join(`\n`); +} +function posToNumber(source, pos) { + if (typeof pos === 'number') + return pos; + const lines = source.split(splitRE); + const { line, column } = pos; + let start = 0; + for (let i = 0; i < line - 1; i++) { + start += lines[i].length + 1; + } + return start + column; +} +function numberToPos(source, offset) { + if (typeof offset !== 'number') + return offset; + if (offset > source.length) { + throw new Error('offset is longer than source length!'); + } + const lines = source.split(splitRE); + let counted = 0; + let line = 0; + let column = 0; + for (; line < lines.length; line++) { + const lineLength = lines[line].length + 1; + if (counted + lineLength >= offset) { + column = offset - counted + 1; + break; + } + counted += lineLength; + } + return { line: line + 1, column }; +} +function generateCodeFrame(source, start = 0, end) { + start = posToNumber(source, start); + end = end || start; + const lines = source.split(splitRE); + let count = 0; + const res = []; + for (let i = 0; i < lines.length; i++) { + count += lines[i].length + 1; + if (count >= start) { + for (let j = i - range$1; j <= i + range$1 || end > count; j++) { + if (j < 0 || j >= lines.length) + continue; + const line = j + 1; + res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`); + const lineLength = lines[j].length; + if (j === i) { + // push underline + const pad = start - (count - lineLength) + 1; + const length = Math.max(1, end > count ? lineLength - pad : end - start); + res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)); + } + else if (j > i) { + if (end > count) { + const length = Math.max(Math.min(end - count, lineLength), 1); + res.push(` | ` + '^'.repeat(length)); + } + count += lineLength + 1; + } + } + break; + } + } + return res.join('\n'); +} +function writeFile(filename, content) { + const dir = path__default.dirname(filename); + if (!fs__default.existsSync(dir)) { + fs__default.mkdirSync(dir, { recursive: true }); + } + fs__default.writeFileSync(filename, content); +} +/** + * Delete every file and subdirectory. **The given directory must exist.** + * Pass an optional `skip` array to preserve files in the root directory. + */ +function emptyDir(dir, skip) { + for (const file of fs__default.readdirSync(dir)) { + if (skip === null || skip === void 0 ? void 0 : skip.includes(file)) { + continue; + } + const abs = path__default.resolve(dir, file); + // baseline is Node 12 so can't use rmSync :( + if (fs__default.lstatSync(abs).isDirectory()) { + emptyDir(abs); + fs__default.rmdirSync(abs); + } + else { + fs__default.unlinkSync(abs); + } + } +} +function copyDir(srcDir, destDir) { + fs__default.mkdirSync(destDir, { recursive: true }); + for (const file of fs__default.readdirSync(srcDir)) { + const srcFile = path__default.resolve(srcDir, file); + if (srcFile === destDir) { + continue; + } + const destFile = path__default.resolve(destDir, file); + const stat = fs__default.statSync(srcFile); + if (stat.isDirectory()) { + copyDir(srcFile, destFile); + } + else { + fs__default.copyFileSync(srcFile, destFile); + } + } +} +function ensureLeadingSlash(path) { + return !path.startsWith('/') ? '/' + path : path; +} +function ensureWatchedFile(watcher, file, root) { + if (file && + // only need to watch if out of root + !file.startsWith(root + '/') && + // some rollup plugins use null bytes for private resolved Ids + !file.includes('\0') && + fs__default.existsSync(file)) { + // resolve file to normalized system path + watcher.add(path__default.resolve(file)); + } +} +const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g; +async function processSrcSet(srcs, replacer) { + const imageCandidates = srcs + .split(',') + .map((s) => { + const [url, descriptor] = s + .replace(escapedSpaceCharacters, ' ') + .trim() + .split(' ', 2); + return { url, descriptor }; + }) + .filter(({ url }) => !!url); + const ret = await Promise.all(imageCandidates.map(async ({ url, descriptor }) => { + return { + url: await replacer({ url, descriptor }), + descriptor + }; + })); + const url = ret.reduce((prev, { url, descriptor }, index) => { + descriptor = descriptor || ''; + return (prev += + url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`); + }, ''); + return url; +} +// based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221 +const nullSourceMap = { + names: [], + sources: [], + mappings: '', + version: 3 +}; +function combineSourcemaps(filename, sourcemapList) { + if (sourcemapList.length === 0 || + sourcemapList.every((m) => m.sources.length === 0)) { + return { ...nullSourceMap }; + } + // We don't declare type here so we can convert/fake/map as RawSourceMap + let map; //: SourceMap + let mapIndex = 1; + const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined; + if (useArrayInterface) { + map = remapping(sourcemapList, () => null, true); + } + else { + map = remapping(sourcemapList[0], function loader(sourcefile) { + if (sourcefile === filename && sourcemapList[mapIndex]) { + return sourcemapList[mapIndex++]; + } + else { + return { ...nullSourceMap }; + } + }, true); + } + if (!map.file) { + delete map.file; + } + return map; +} +function unique(arr) { + return Array.from(new Set(arr)); +} +function resolveHostname(optionsHost) { + let host; + if (optionsHost === undefined || + optionsHost === false || + optionsHost === 'localhost') { + // Use a secure default + host = '127.0.0.1'; + } + else if (optionsHost === true) { + // If passed --host in the CLI without arguments + host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs) + } + else { + host = optionsHost; + } + // Set host name to localhost when possible, unless the user explicitly asked for '127.0.0.1' + const name = (optionsHost !== '127.0.0.1' && host === '127.0.0.1') || + host === '0.0.0.0' || + host === '::' || + host === undefined + ? 'localhost' + : host; + return { host, name }; +} +function arraify(target) { + return Array.isArray(target) ? target : [target]; +} +const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm; +const singlelineCommentsRE = /\/\/.*/g; + +/* eslint no-console: 0 */ +const LogLevels = { + silent: 0, + error: 1, + warn: 2, + info: 3 +}; +let lastType; +let lastMsg; +let sameCount = 0; +function clearScreen() { + const repeatCount = process.stdout.rows - 2; + const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''; + console.log(blank); + readline__default.cursorTo(process.stdout, 0, 0); + readline__default.clearScreenDown(process.stdout); +} +function createLogger(level = 'info', options = {}) { + if (options.customLogger) { + return options.customLogger; + } + const loggedErrors = new WeakSet(); + const { prefix = '[vite]', allowClearScreen = true } = options; + const thresh = LogLevels[level]; + const clear = allowClearScreen && process.stdout.isTTY && !process.env.CI + ? clearScreen + : () => { }; + function output(type, msg, options = {}) { + if (thresh >= LogLevels[type]) { + const method = type === 'info' ? 'log' : type; + const format = () => { + if (options.timestamp) { + const tag = type === 'info' + ? source.cyan.bold(prefix) + : type === 'warn' + ? source.yellow.bold(prefix) + : source.red.bold(prefix); + return `${source.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`; + } + else { + return msg; + } + }; + if (options.error) { + loggedErrors.add(options.error); + } + if (type === lastType && msg === lastMsg) { + sameCount++; + clear(); + console[method](format(), source.yellow(`(x${sameCount + 1})`)); + } + else { + sameCount = 0; + lastMsg = msg; + lastType = type; + if (options.clear) { + clear(); + } + console[method](format()); + } + } + } + const warnedMessages = new Set(); + const logger = { + hasWarned: false, + info(msg, opts) { + output('info', msg, opts); + }, + warn(msg, opts) { + logger.hasWarned = true; + output('warn', msg, opts); + }, + warnOnce(msg, opts) { + if (warnedMessages.has(msg)) + return; + logger.hasWarned = true; + output('warn', msg, opts); + warnedMessages.add(msg); + }, + error(msg, opts) { + logger.hasWarned = true; + output('error', msg, opts); + }, + clearScreen(type) { + if (thresh >= LogLevels[type]) { + clear(); + } + }, + hasErrorLogged(error) { + return loggedErrors.has(error); + } + }; + return logger; +} +function printServerUrls(hostname, protocol, port, base, info) { + if (hostname.host === '127.0.0.1') { + const url = `${protocol}://${hostname.name}:${source.bold(port)}${base}`; + info(` > Local: ${source.cyan(url)}`); + if (hostname.name !== '127.0.0.1') { + info(` > Network: ${source.dim('use `--host` to expose')}`); + } + } + else { + Object.values(require$$0__default$1.networkInterfaces()) + .flatMap((nInterface) => nInterface !== null && nInterface !== void 0 ? nInterface : []) + .filter((detail) => detail.family === 'IPv4') + .map((detail) => { + const type = detail.address.includes('127.0.0.1') + ? 'Local: ' + : 'Network: '; + const host = detail.address.replace('127.0.0.1', hostname.name); + const url = `${protocol}://${host}:${source.bold(port)}${base}`; + return ` > ${type} ${source.cyan(url)}`; + }) + .forEach((msg) => info(msg)); + } +} + +const writeColors = { + [0 /* JS */]: source.cyan, + [1 /* CSS */]: source.magenta, + [2 /* ASSET */]: source.green, + [3 /* HTML */]: source.blue, + [4 /* SOURCE_MAP */]: source.gray +}; +function buildReporterPlugin(config) { + const chunkLimit = config.build.chunkSizeWarningLimit; + function isLarge(code) { + // bail out on particularly large chunks + return code.length / 1024 > chunkLimit; + } + async function getCompressedSize(code) { + if (config.build.ssr || !config.build.brotliSize) { + return ''; + } + if (isLarge(code)) { + return ' / brotli: skipped (large chunk)'; + } + return ` / brotli: ${((await _default(typeof code === 'string' ? code : Buffer.from(code))) / 1024).toFixed(2)} KiB`; + } + function printFileInfo(filePath, content, type, maxLength, compressedSize = '') { + const outDir = normalizePath$4(path__default.relative(config.root, path__default.resolve(config.root, config.build.outDir))) + '/'; + const kibs = content.length / 1024; + const sizeColor = kibs > chunkLimit ? source.yellow : source.dim; + config.logger.info(`${source.gray(source.white.dim(outDir))}${writeColors[type](filePath.padEnd(maxLength + 2))} ${sizeColor(`${kibs.toFixed(2)} KiB${compressedSize}`)}`); + } + const tty = process.stdout.isTTY && !process.env.CI; + const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info; + let hasTransformed = false; + let hasRenderedChunk = false; + let transformedCount = 0; + let chunkCount = 0; + const logTransform = throttle((id) => { + writeLine(`transforming (${transformedCount}) ${source.dim(path__default.relative(config.root, id))}`); + }); + return { + name: 'vite:reporter', + transform(_, id) { + transformedCount++; + if (shouldLogInfo) { + if (!tty) { + if (!hasTransformed) { + config.logger.info(`transforming...`); + } + } + else { + if (id.includes(`?`)) + return; + logTransform(id); + } + hasTransformed = true; + } + return null; + }, + buildEnd() { + if (shouldLogInfo) { + if (tty) { + process.stdout.clearLine(0); + process.stdout.cursorTo(0); + } + config.logger.info(`${source.green(`✓`)} ${transformedCount} modules transformed.`); + } + }, + renderStart() { + chunkCount = 0; + }, + renderChunk() { + chunkCount++; + if (shouldLogInfo) { + if (!tty) { + if (!hasRenderedChunk) { + config.logger.info('rendering chunks...'); + } + } + else { + writeLine(`rendering chunks (${chunkCount})...`); + } + hasRenderedChunk = true; + } + return null; + }, + generateBundle() { + if (shouldLogInfo && tty) { + process.stdout.clearLine(0); + process.stdout.cursorTo(0); + } + }, + async writeBundle(_, output) { + let hasLargeChunks = false; + if (shouldLogInfo) { + let longest = 0; + for (const file in output) { + const l = output[file].fileName.length; + if (l > longest) + longest = l; + } + // large chunks are deferred to be logged at the end so they are more + // visible. + const deferredLogs = []; + await Promise.all(Object.keys(output).map(async (file) => { + const chunk = output[file]; + if (chunk.type === 'chunk') { + const log = async () => { + printFileInfo(chunk.fileName, chunk.code, 0 /* JS */, longest, await getCompressedSize(chunk.code)); + if (chunk.map) { + printFileInfo(chunk.fileName + '.map', chunk.map.toString(), 4 /* SOURCE_MAP */, longest); + } + }; + if (isLarge(chunk.code)) { + hasLargeChunks = true; + deferredLogs.push(log); + } + else { + await log(); + } + } + else if (chunk.source) { + const isCSS = chunk.fileName.endsWith('.css'); + printFileInfo(chunk.fileName, chunk.source, isCSS ? 1 /* CSS */ : 2 /* ASSET */, longest, isCSS ? await getCompressedSize(chunk.source) : undefined); + } + })); + await Promise.all(deferredLogs.map((l) => l())); + } + else { + hasLargeChunks = Object.keys(output).some((file) => { + const chunk = output[file]; + return chunk.type === 'chunk' && chunk.code.length / 1024 > chunkLimit; + }); + } + if (hasLargeChunks && + config.build.minify && + !config.build.lib && + !config.build.ssr) { + config.logger.warn(source.yellow(`\n(!) Some chunks are larger than ${chunkLimit} KiB after minification. Consider:\n` + + `- Using dynamic import() to code-split the application\n` + + `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks\n` + + `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`)); + } + } + }; +} +function writeLine(output) { + process.stdout.clearLine(0); + process.stdout.cursorTo(0); + if (output.length < process.stdout.columns) { + process.stdout.write(output); + } + else { + process.stdout.write(output.substring(0, process.stdout.columns - 1)); + } +} +function throttle(fn) { + let timerHandle = null; + return (...args) => { + if (timerHandle) + return; + fn(...args); + timerHandle = setTimeout(() => { + timerHandle = null; + }, 100); + }; +} + +var charToInteger = {}; +var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +for (var i$1 = 0; i$1 < chars$1.length; i$1++) { + charToInteger[chars$1.charCodeAt(i$1)] = i$1; +} +function encode(decoded) { + var sourceFileIndex = 0; // second field + var sourceCodeLine = 0; // third field + var sourceCodeColumn = 0; // fourth field + var nameIndex = 0; // fifth field + var mappings = ''; + for (var i = 0; i < decoded.length; i++) { + var line = decoded[i]; + if (i > 0) + mappings += ';'; + if (line.length === 0) + continue; + var generatedCodeColumn = 0; // first field + var lineMappings = []; + for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { + var segment = line_1[_i]; + var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn); + generatedCodeColumn = segment[0]; + if (segment.length > 1) { + segmentMappings += + encodeInteger(segment[1] - sourceFileIndex) + + encodeInteger(segment[2] - sourceCodeLine) + + encodeInteger(segment[3] - sourceCodeColumn); + sourceFileIndex = segment[1]; + sourceCodeLine = segment[2]; + sourceCodeColumn = segment[3]; + } + if (segment.length === 5) { + segmentMappings += encodeInteger(segment[4] - nameIndex); + nameIndex = segment[4]; + } + lineMappings.push(segmentMappings); + } + mappings += lineMappings.join(','); + } + return mappings; +} +function encodeInteger(num) { + var result = ''; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + var clamped = num & 31; + num >>>= 5; + if (num > 0) { + clamped |= 32; + } + result += chars$1[clamped]; + } while (num > 0); + return result; +} + +var BitSet = function BitSet(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; +}; + +BitSet.prototype.add = function add (n) { + this.bits[n >> 5] |= 1 << (n & 31); +}; + +BitSet.prototype.has = function has (n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); +}; + +var Chunk = function Chunk(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + // we make these non-enumerable, for sanity while debugging + Object.defineProperties(this, { + previous: { writable: true, value: null }, + next: { writable: true, value: null } + }); +}; + +Chunk.prototype.appendLeft = function appendLeft (content) { + this.outro += content; +}; + +Chunk.prototype.appendRight = function appendRight (content) { + this.intro = this.intro + content; +}; + +Chunk.prototype.clone = function clone () { + var chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; +}; + +Chunk.prototype.contains = function contains (index) { + return this.start < index && index < this.end; +}; + +Chunk.prototype.eachNext = function eachNext (fn) { + var chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } +}; + +Chunk.prototype.eachPrevious = function eachPrevious (fn) { + var chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } +}; + +Chunk.prototype.edit = function edit (content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; +}; + +Chunk.prototype.prependLeft = function prependLeft (content) { + this.outro = content + this.outro; +}; + +Chunk.prototype.prependRight = function prependRight (content) { + this.intro = content + this.intro; +}; + +Chunk.prototype.split = function split (index) { + var sliceIndex = index - this.start; + + var originalBefore = this.original.slice(0, sliceIndex); + var originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + var newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) { newChunk.next.previous = newChunk; } + newChunk.previous = this; + this.next = newChunk; + + return newChunk; +}; + +Chunk.prototype.toString = function toString () { + return this.intro + this.content + this.outro; +}; + +Chunk.prototype.trimEnd = function trimEnd (rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + + var trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + } + return true; + + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + } +}; + +Chunk.prototype.trimStart = function trimStart (rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + + var trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.end - trimmed.length); + this.edit('', undefined, true); + } + return true; + + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + } +}; + +var btoa$1 = function () { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); +}; +if (typeof window !== 'undefined' && typeof window.btoa === 'function') { + btoa$1 = function (str) { return window.btoa(unescape(encodeURIComponent(str))); }; +} else if (typeof Buffer === 'function') { + btoa$1 = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); }; +} + +var SourceMap = function SourceMap(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode(properties.mappings); +}; + +SourceMap.prototype.toString = function toString () { + return JSON.stringify(this); +}; + +SourceMap.prototype.toUrl = function toUrl () { + return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString()); +}; + +function guessIndent(code) { + var lines = code.split('\n'); + + var tabbed = lines.filter(function (line) { return /^\t+/.test(line); }); + var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); }); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + var min = spaced.reduce(function (previous, current) { + var numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + var fromParts = from.split(/[/\\]/); + var toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + var i = fromParts.length; + while (i--) { fromParts[i] = '..'; } + } + + return fromParts.concat(toParts).join('/'); +} + +var toString$2 = Object.prototype.toString; + +function isObject$2(thing) { + return toString$2.call(thing) === '[object Object]'; +} + +function getLocator(source) { + var originalLines = source.split('\n'); + var lineOffsets = []; + + for (var i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + var i = 0; + var j = lineOffsets.length; + while (i < j) { + var m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + var line = i - 1; + var column = index - lineOffsets[line]; + return { line: line, column: column }; + }; +} + +var Mappings = function Mappings(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; +}; + +Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) { + if (content.length) { + var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + } else if (this.pending) { + this.rawSegments.push(this.pending); + } + + this.advance(content); + this.pending = null; +}; + +Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) { + var originalCharIndex = chunk.start; + var first = true; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; +}; + +Mappings.prototype.advance = function advance (str) { + if (!str) { return; } + + var lines = str.split('\n'); + + if (lines.length > 1) { + for (var i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; +}; + +var n = '\n'; + +var warned$1 = { + insertLeft: false, + insertRight: false, + storeName: false +}; + +var MagicString = function MagicString(string, options) { + if ( options === void 0 ) options = {}; + + var chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: guessIndent(string) } + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; +}; + +MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) { + this.sourcemapLocations.add(char); +}; + +MagicString.prototype.append = function append (content) { + if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } + + this.outro += content; + return this; +}; + +MagicString.prototype.appendLeft = function appendLeft (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; +}; + +MagicString.prototype.appendRight = function appendRight (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; +}; + +MagicString.prototype.clone = function clone () { + var cloned = new MagicString(this.original, { filename: this.filename }); + + var originalChunk = this.firstChunk; + var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + var nextOriginalChunk = originalChunk.next; + var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; +}; + +MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) { + var this$1$1 = this; + + options = options || {}; + + var sourceIndex = 0; + var names = Object.keys(this.storedNames); + var mappings = new Mappings(options.hires); + + var locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext(function (chunk) { + var loc = locate(chunk.start); + + if (chunk.intro.length) { mappings.advance(chunk.intro); } + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1 + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations); + } + + if (chunk.outro.length) { mappings.advance(chunk.outro); } + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : null, + sources: [options.source ? getRelativePath(options.file || '', options.source) : null], + sourcesContent: options.includeContent ? [this.original] : [null], + names: names, + mappings: mappings.raw + }; +}; + +MagicString.prototype.generateMap = function generateMap (options) { + return new SourceMap(this.generateDecodedMap(options)); +}; + +MagicString.prototype.getIndentString = function getIndentString () { + return this.indentStr === null ? '\t' : this.indentStr; +}; + +MagicString.prototype.indent = function indent (indentStr, options) { + var pattern = /^[^\r\n]/gm; + + if (isObject$2(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t'; + + if (indentStr === '') { return this; } // noop + + options = options || {}; + + // Process exclusion ranges + var isExcluded = {}; + + if (options.exclude) { + var exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach(function (exclusion) { + for (var i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + var shouldIndentNextCharacter = options.indentStart !== false; + var replacer = function (match) { + if (shouldIndentNextCharacter) { return ("" + indentStr + match); } + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + var charIndex = 0; + var chunk = this.firstChunk; + + while (chunk) { + var end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + var char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; +}; + +MagicString.prototype.insert = function insert () { + throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'); +}; + +MagicString.prototype.insertLeft = function insertLeft (index, content) { + if (!warned$1.insertLeft) { + console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console + warned$1.insertLeft = true; + } + + return this.appendLeft(index, content); +}; + +MagicString.prototype.insertRight = function insertRight (index, content) { + if (!warned$1.insertRight) { + console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console + warned$1.insertRight = true; + } + + return this.prependRight(index, content); +}; + +MagicString.prototype.move = function move (start, end, index) { + if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); } + + this._split(start); + this._split(end); + this._split(index); + + var first = this.byStart[start]; + var last = this.byEnd[end]; + + var oldLeft = first.previous; + var oldRight = last.next; + + var newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) { return this; } + var newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) { oldLeft.next = oldRight; } + if (oldRight) { oldRight.previous = oldLeft; } + + if (newLeft) { newLeft.next = first; } + if (newRight) { newRight.previous = last; } + + if (!first.previous) { this.firstChunk = last.next; } + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) { this.firstChunk = first; } + if (!newRight) { this.lastChunk = last; } + return this; +}; + +MagicString.prototype.overwrite = function overwrite (start, end, content, options) { + if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); } + + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + if (end > this.original.length) { throw new Error('end is out of bounds'); } + if (start === end) + { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); } + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned$1.storeName) { + console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console + warned$1.storeName = true; + } + + options = { storeName: true }; + } + var storeName = options !== undefined ? options.storeName : false; + var contentOnly = options !== undefined ? options.contentOnly : false; + + if (storeName) { + var original = this.original.slice(start, end); + this.storedNames[original] = true; + } + + var first = this.byStart[start]; + var last = this.byEnd[end]; + + if (first) { + if (end > first.end && first.next !== this.byStart[first.end]) { + throw new Error('Cannot overwrite across a split point'); + } + + first.edit(content, storeName, contentOnly); + + if (first !== last) { + var chunk = first.next; + while (chunk !== last) { + chunk.edit('', false); + chunk = chunk.next; + } + + chunk.edit('', false); + } + } else { + // must be inserting at the end + var newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; +}; + +MagicString.prototype.prepend = function prepend (content) { + if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } + + this.intro = content + this.intro; + return this; +}; + +MagicString.prototype.prependLeft = function prependLeft (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; +}; + +MagicString.prototype.prependRight = function prependRight (index, content) { + if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } + + this._split(index); + + var chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; +}; + +MagicString.prototype.remove = function remove (start, end) { + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + if (start === end) { return this; } + + if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); } + if (start > end) { throw new Error('end must be greater than start'); } + + this._split(start); + this._split(end); + + var chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; +}; + +MagicString.prototype.lastChar = function lastChar () { + if (this.outro.length) + { return this.outro[this.outro.length - 1]; } + var chunk = this.lastChunk; + do { + if (chunk.outro.length) + { return chunk.outro[chunk.outro.length - 1]; } + if (chunk.content.length) + { return chunk.content[chunk.content.length - 1]; } + if (chunk.intro.length) + { return chunk.intro[chunk.intro.length - 1]; } + } while (chunk = chunk.previous); + if (this.intro.length) + { return this.intro[this.intro.length - 1]; } + return ''; +}; + +MagicString.prototype.lastLine = function lastLine () { + var lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) + { return this.outro.substr(lineIndex + 1); } + var lineStr = this.outro; + var chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) + { return chunk.outro.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) + { return chunk.content.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) + { return chunk.intro.substr(lineIndex + 1) + lineStr; } + lineStr = chunk.intro + lineStr; + } + } while (chunk = chunk.previous); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) + { return this.intro.substr(lineIndex + 1) + lineStr; } + return this.intro + lineStr; +}; + +MagicString.prototype.slice = function slice (start, end) { + if ( start === void 0 ) start = 0; + if ( end === void 0 ) end = this.original.length; + + while (start < 0) { start += this.original.length; } + while (end < 0) { end += this.original.length; } + + var result = ''; + + // find start chunk + var chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); } + + var startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + var containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); } + + var sliceStart = startChunk === chunk ? start - chunk.start : 0; + var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; +}; + +// TODO deprecate this? not really very useful +MagicString.prototype.snip = function snip (start, end) { + var clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; +}; + +MagicString.prototype._split = function _split (index) { + if (this.byStart[index] || this.byEnd[index]) { return; } + + var chunk = this.lastSearchedChunk; + var searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) { return this._splitChunk(chunk, index); } + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } +}; + +MagicString.prototype._splitChunk = function _splitChunk (chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + var loc = getLocator(this.original)(index); + throw new Error( + ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") + ); + } + + var newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) { this.lastChunk = newChunk; } + + this.lastSearchedChunk = chunk; + return true; +}; + +MagicString.prototype.toString = function toString () { + var str = this.intro; + + var chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; +}; + +MagicString.prototype.isEmpty = function isEmpty () { + var chunk = this.firstChunk; + do { + if (chunk.intro.length && chunk.intro.trim() || + chunk.content.length && chunk.content.trim() || + chunk.outro.length && chunk.outro.trim()) + { return false; } + } while (chunk = chunk.next); + return true; +}; + +MagicString.prototype.length = function length () { + var chunk = this.firstChunk; + var length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while (chunk = chunk.next); + return length; +}; + +MagicString.prototype.trimLines = function trimLines () { + return this.trim('[\\r\\n]'); +}; + +MagicString.prototype.trim = function trim (charType) { + return this.trimStart(charType).trimEnd(charType); +}; + +MagicString.prototype.trimEndAborted = function trimEndAborted (charType) { + var rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) { return true; } + + var chunk = this.lastChunk; + + do { + var end = chunk.end; + var aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) { return true; } + chunk = chunk.previous; + } while (chunk); + + return false; +}; + +MagicString.prototype.trimEnd = function trimEnd (charType) { + this.trimEndAborted(charType); + return this; +}; +MagicString.prototype.trimStartAborted = function trimStartAborted (charType) { + var rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) { return true; } + + var chunk = this.firstChunk; + + do { + var end = chunk.end; + var aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) { this.lastChunk = chunk.next; } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) { return true; } + chunk = chunk.next; + } while (chunk); + + return false; +}; + +MagicString.prototype.trimStart = function trimStart (charType) { + this.trimStartAborted(charType); + return this; +}; + +/** + * @param typeMap [Object] Map of MIME type -> Array[extensions] + * @param ... + */ +function Mime$1() { + this._types = Object.create(null); + this._extensions = Object.create(null); + + for (let i = 0; i < arguments.length; i++) { + this.define(arguments[i]); + } + + this.define = this.define.bind(this); + this.getType = this.getType.bind(this); + this.getExtension = this.getExtension.bind(this); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * If a type declares an extension that has already been defined, an error will + * be thrown. To suppress this error and force the extension to be associated + * with the new type, pass `force`=true. Alternatively, you may prefix the + * extension with "*" to map the type to extension, without mapping the + * extension to the type. + * + * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']}); + * + * + * @param map (Object) type definitions + * @param force (Boolean) if true, force overriding of existing definitions + */ +Mime$1.prototype.define = function(typeMap, force) { + for (let type in typeMap) { + let extensions = typeMap[type].map(function(t) { + return t.toLowerCase(); + }); + type = type.toLowerCase(); + + for (let i = 0; i < extensions.length; i++) { + const ext = extensions[i]; + + // '*' prefix = not the preferred type for this extension. So fixup the + // extension, and skip it. + if (ext[0] === '*') { + continue; + } + + if (!force && (ext in this._types)) { + throw new Error( + 'Attempt to change mapping for "' + ext + + '" extension from "' + this._types[ext] + '" to "' + type + + '". Pass `force=true` to allow this, otherwise remove "' + ext + + '" from the list of extensions for "' + type + '".' + ); + } + + this._types[ext] = type; + } + + // Use first extension as default + if (force || !this._extensions[type]) { + const ext = extensions[0]; + this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1); + } + } +}; + +/** + * Lookup a mime type based on extension + */ +Mime$1.prototype.getType = function(path) { + path = String(path); + let last = path.replace(/^.*[/\\]/, '').toLowerCase(); + let ext = last.replace(/^.*\./, '').toLowerCase(); + + let hasPath = last.length < path.length; + let hasDot = ext.length < last.length - 1; + + return (hasDot || !hasPath) && this._types[ext] || null; +}; + +/** + * Return file extension associated with a mime type + */ +Mime$1.prototype.getExtension = function(type) { + type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; + return type && this._extensions[type.toLowerCase()] || null; +}; + +var Mime_1 = Mime$1; + +var standard = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma","es"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/mrb-consumer+xml":["*xdf"],"application/mrb-publish+xml":["*xdf"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["*xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-error+xml":["xer"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}; + +let Mime = Mime_1; +var lite = new Mime(standard); + +const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g; +// urls in JS must be quoted as strings, so when replacing them we need +// a different regex +const assetUrlQuotedRE = /"__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?"/g; +const rawRE = /(\?|&)raw(?:&|$)/; +const urlRE = /(\?|&)url(?:&|$)/; +const chunkToEmittedAssetsMap = new WeakMap(); +const assetCache = new WeakMap(); +const assetHashToFilenameMap = new WeakMap(); +// save hashes of the files that has been emitted in build watch +const emittedHashMap = new WeakMap(); +/** + * Also supports loading plain strings with import text from './foo.txt?raw' + */ +function assetPlugin(config) { + // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined + assetHashToFilenameMap.set(config, new Map()); + return { + name: 'vite:asset', + buildStart() { + assetCache.set(config, new Map()); + emittedHashMap.set(config, new Set()); + }, + resolveId(id) { + if (!config.assetsInclude(cleanUrl(id))) { + return; + } + // imports to absolute urls pointing to files in /public + // will fail to resolve in the main resolver. handle them here. + const publicFile = checkPublicFile(id, config); + if (publicFile) { + return id; + } + }, + async load(id) { + if (id.startsWith('\0')) { + // Rollup convention, this id should be handled by the + // plugin that marked it with \0 + return; + } + // raw requests, read from disk + if (rawRE.test(id)) { + const file = checkPublicFile(id, config) || cleanUrl(id); + // raw query, read file and return as string + return `export default ${JSON.stringify(await fs$v.promises.readFile(file, 'utf-8'))}`; + } + if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) { + return; + } + id = id.replace(urlRE, '$1').replace(/[\?&]$/, ''); + const url = await fileToUrl(id, config, this); + return `export default ${JSON.stringify(url)}`; + }, + renderChunk(code, chunk) { + let match; + let s; + while ((match = assetUrlQuotedRE.exec(code))) { + s = s || (s = new MagicString(code)); + const [full, hash, postfix = ''] = match; + // some internal plugins may still need to emit chunks (e.g. worker) so + // fallback to this.getFileName for that. + const file = getAssetFilename(hash, config) || this.getFileName(hash); + registerAssetToChunk(chunk, file); + const outputFilepath = config.base + file + postfix; + s.overwrite(match.index, match.index + full.length, JSON.stringify(outputFilepath)); + } + if (s) { + return { + code: s.toString(), + map: config.build.sourcemap ? s.generateMap({ hires: true }) : null + }; + } + else { + return null; + } + }, + generateBundle(_, bundle) { + // do not emit assets for SSR build + if (config.command === 'build' && config.build.ssr) { + for (const file in bundle) { + if (bundle[file].type === 'asset' && + !file.includes('ssr-manifest.json')) { + delete bundle[file]; + } + } + } + } + }; +} +function registerAssetToChunk(chunk, file) { + let emitted = chunkToEmittedAssetsMap.get(chunk); + if (!emitted) { + emitted = new Set(); + chunkToEmittedAssetsMap.set(chunk, emitted); + } + emitted.add(cleanUrl(file)); +} +function checkPublicFile(url, { publicDir }) { + // note if the file is in /public, the resolver would have returned it + // as-is so it's not going to be a fully resolved path. + if (!publicDir || !url.startsWith('/')) { + return; + } + const publicFile = path__default.join(publicDir, cleanUrl(url)); + if (fs__default.existsSync(publicFile)) { + return publicFile; + } + else { + return; + } +} +function fileToUrl(id, config, ctx) { + if (config.command === 'serve') { + return fileToDevUrl(id, config); + } + else { + return fileToBuiltUrl(id, config, ctx); + } +} +function fileToDevUrl(id, config) { + let rtn; + if (checkPublicFile(id, config)) { + // in public dir, keep the url as-is + rtn = id; + } + else if (id.startsWith(config.root)) { + // in project root, infer short public path + rtn = '/' + path__default.posix.relative(config.root, id); + } + else { + // outside of project root, use absolute fs path + // (this is special handled by the serve static middleware + rtn = path__default.posix.join(FS_PREFIX + id); + } + return config.base + rtn.replace(/^\//, ''); +} +function getAssetFilename(hash, config) { + var _a; + return (_a = assetHashToFilenameMap.get(config)) === null || _a === void 0 ? void 0 : _a.get(hash); +} +/** + * converts the source filepath of the asset to the output filename based on the assetFileNames option. \ + * this function imitates the behavior of rollup.js. \ + * https://rollupjs.org/guide/en/#outputassetfilenames + * + * @example + * ```ts + * const content = Buffer.from('text'); + * const fileName = assetFileNamesToFileName( + * 'assets/[name].[hash][extname]', + * '/path/to/file.txt', + * getAssetHash(content), + * content + * ) + * // fileName: 'assets/file.982d9e3e.txt' + * ``` + * + * @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'` + * @param file filepath of the asset + * @param contentHash hash of the asset. used for `'[hash]'` placeholder + * @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function + * @returns output filename + */ +function assetFileNamesToFileName(assetFileNames, file, contentHash, content) { + const basename = path__default.basename(file); + // placeholders for `assetFileNames` + // `hash` is slightly different from the rollup's one + const extname = path__default.extname(basename); + const ext = extname.substr(1); + const name = basename.slice(0, -extname.length); + const hash = contentHash; + if (typeof assetFileNames === 'function') { + assetFileNames = assetFileNames({ + name: file, + source: content, + type: 'asset' + }); + if (typeof assetFileNames !== 'string') { + throw new TypeError('assetFileNames must return a string'); + } + } + else if (typeof assetFileNames !== 'string') { + throw new TypeError('assetFileNames must be a string or a function'); + } + const fileName = assetFileNames.replace(/\[\w+\]/g, (placeholder) => { + switch (placeholder) { + case '[ext]': + return ext; + case '[extname]': + return extname; + case '[hash]': + return hash; + case '[name]': + return name; + } + throw new Error(`invalid placeholder ${placeholder} in assetFileNames "${assetFileNames}"`); + }); + return fileName; +} +/** + * Register an asset to be emitted as part of the bundle (if necessary) + * and returns the resolved public URL + */ +async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) { + var _a, _b, _c; + if (!skipPublicCheck && checkPublicFile(id, config)) { + return config.base + id.slice(1); + } + const cache = assetCache.get(config); + const cached = cache.get(id); + if (cached) { + return cached; + } + const file = cleanUrl(id); + const content = await fs$v.promises.readFile(file); + let url; + if (config.build.lib || + (!file.endsWith('.svg') && + content.length < Number(config.build.assetsInlineLimit))) { + // base64 inlined as a string + url = `data:${lite.getType(file)};base64,${content.toString('base64')}`; + } + else { + // emit as asset + // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code + // that uses runtime url sniffing and it can be verbose when targeting + // non-module format. It also fails to cascade the asset content change + // into the chunk's hash, so we have to do our own content hashing here. + // https://bundlers.tooling.report/hashing/asset-cascade/ + // https://github.com/rollup/rollup/issues/3415 + const map = assetHashToFilenameMap.get(config); + const contentHash = getAssetHash(content); + const { search, hash } = require$$0$a.parse(id); + const postfix = (search || '') + (hash || ''); + const output = (_b = (_a = config.build) === null || _a === void 0 ? void 0 : _a.rollupOptions) === null || _b === void 0 ? void 0 : _b.output; + const assetFileNames = (_c = (output && !Array.isArray(output) ? output.assetFileNames : undefined)) !== null && _c !== void 0 ? _c : + // defaults to '/[name].[hash][extname]' + // slightly different from rollup's one ('assets/[name]-[hash][extname]') + path__default.posix.join(config.build.assetsDir, '[name].[hash][extname]'); + const fileName = assetFileNamesToFileName(assetFileNames, file, contentHash, content); + if (!map.has(contentHash)) { + map.set(contentHash, fileName); + } + const emittedSet = emittedHashMap.get(config); + if (!emittedSet.has(contentHash)) { + const name = normalizePath$4(path__default.relative(config.root, file)); + pluginContext.emitFile({ + name, + fileName, + type: 'asset', + source: content + }); + emittedSet.add(contentHash); + } + url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`; + } + cache.set(id, url); + return url; +} +function getAssetHash(content) { + return require$$1$1.createHash('sha256').update(content).digest('hex').slice(0, 8); +} +async function urlToBuiltUrl(url, importer, config, pluginContext) { + if (checkPublicFile(url, config)) { + return config.base + url.slice(1); + } + const file = url.startsWith('/') + ? path__default.join(config.root, url) + : path__default.join(path__default.dirname(importer), url); + return fileToBuiltUrl(file, config, pluginContext, + // skip public check since we just did it above + true); +} + +var tasks = {}; + +var utils$k = {}; + +var array$1 = {}; + +Object.defineProperty(array$1, "__esModule", { value: true }); +array$1.splitWhen = array$1.flatten = void 0; +function flatten$1(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); +} +array$1.flatten = flatten$1; +function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } + else { + result[groupIndex].push(item); + } + } + return result; +} +array$1.splitWhen = splitWhen; + +var errno$1 = {}; + +Object.defineProperty(errno$1, "__esModule", { value: true }); +errno$1.isEnoentCodeError = void 0; +function isEnoentCodeError(error) { + return error.code === 'ENOENT'; +} +errno$1.isEnoentCodeError = isEnoentCodeError; + +var fs$u = {}; + +Object.defineProperty(fs$u, "__esModule", { value: true }); +fs$u.createDirentFromStats = void 0; +class DirentFromStats$1 { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats$1(name, stats) { + return new DirentFromStats$1(name, stats); +} +fs$u.createDirentFromStats = createDirentFromStats$1; + +var path$v = {}; + +Object.defineProperty(path$v, "__esModule", { value: true }); +path$v.removeLeadingDotSegment = path$v.escape = path$v.makeAbsolute = path$v.unixify = void 0; +const path$u = path__default; +const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ +const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; +/** + * Designed to work only with simple paths: `dir\\file`. + */ +function unixify(filepath) { + return filepath.replace(/\\/g, '/'); +} +path$v.unixify = unixify; +function makeAbsolute(cwd, filepath) { + return path$u.resolve(cwd, filepath); +} +path$v.makeAbsolute = makeAbsolute; +function escape$1(pattern) { + return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +path$v.escape = escape$1; +function removeLeadingDotSegment(entry) { + // We do not use `startsWith` because this is 10x slower than current implementation for some cases. + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (entry.charAt(0) === '.') { + const secondCharactery = entry.charAt(1); + if (secondCharactery === '/' || secondCharactery === '\\') { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + } + return entry; +} +path$v.removeLeadingDotSegment = removeLeadingDotSegment; + +var pattern$1 = {}; + +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +var isExtglob$1 = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; + +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var isExtglob = isExtglob$1; +var chars = { '{': '}', '(': ')', '[': ']'}; +var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; +var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; + +var isGlob$2 = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var regex = strictRegex; + var match; + + // optionally relax regex + if (options && options.strict === false) { + regex = relaxedRegex; + } + + while ((match = regex.exec(str))) { + if (match[2]) return true; + var idx = match.index + match[0].length; + + // if an open bracket/brace/paren is escaped, + // set the index to the next closing character + var open = match[1]; + var close = open ? chars[open] : null; + if (open && close) { + var n = str.indexOf(close, idx); + if (n !== -1) { + idx = n + 1; + } + } + + str = str.slice(idx); + } + return false; +}; + +var isGlob$1 = isGlob$2; +var pathPosixDirname = path__default.posix.dirname; +var isWin32 = require$$0__default$1.platform() === 'win32'; + +var slash$2 = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\}\]]$/; +var globby$2 = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + * @returns {string} + */ +var globParent$2 = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash$2) < 0) { + str = str.replace(backslash, slash$2); + } + + // special case for strings ending in enclosure containing path separator + if (enclosure.test(str)) { + str += slash$2; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlob$1(str) || globby$2.test(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; + +var utils$j = {}; + +(function (exports) { + +exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; +}; + +/** + * Find a node of the given type + */ + +exports.find = (node, type) => node.nodes.find(node => node.type === type); + +/** + * Find a node of the given type + */ + +exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; +}; + +/** + * Escape the given node with '\\' before node.value + */ + +exports.escapeNode = (block, n = 0, type) => { + let node = block.nodes[n]; + if (!node) return; + + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } +}; + +/** + * Returns true if the given brace node should be enclosed in literal braces + */ + +exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a brace node is invalid. + */ + +exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a node is an open or close node + */ + +exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; +}; + +/** + * Reduce an array of text nodes. + */ + +exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; +}, []); + +/** + * Flatten an array + */ + +exports.flatten = (...args) => { + const result = []; + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); + } + return result; + }; + flat(args); + return result; +}; +}(utils$j)); + +const utils$i = utils$j; + +var stringify$7 = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils$i.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils$i.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +var isNumber$2 = function(num) { + if (typeof num === 'number') { + return num - num === 0; + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + return false; +}; + +/*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + +const isNumber$1 = isNumber$2; + +const toRegexRange$1 = (min, max, options) => { + if (isNumber$1(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber$1(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) { + return toRegexRange$1.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange$1.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false) || []; + let onlyPositive = filterPatterns(pos, neg, '', false) || []; + let intersected = filterPatterns(neg, pos, '-?', true) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); + + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { pattern, count: [count], digits }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { string } = ele; + + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } + + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} + +/** + * Zip strings + */ + +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} + +/** + * Cache + */ + +toRegexRange$1.cache = {}; +toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {}); + +/** + * Expose `toRegexRange` + */ + +var toRegexRange_1 = toRegexRange$1; + +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ + +const util$b = require$$0__default$3; +const toRegexRange = toRegexRange_1; + +const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val); + +const transform = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; + +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; + +const isNumber = num => Number.isInteger(+num); + +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; + +const stringify$6 = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; + +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; + +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; + +const toSequence = (parts, options) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; + + if (parts.positives.length) { + positives = parts.positives.join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.join('|')})`; + } + + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + + if (options.wrap) { + return `(${prefix}${result})`; + } + + return result; +}; + +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, { wrap: false, ...options }); + } + + let start = String.fromCharCode(a); + if (a === b) return start; + + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; + +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange(start, end, options); +}; + +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util$b.inspect(...args)); +}; + +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; + +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; + +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } + + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; + + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify$6(start, end, options) === false; + let format = options.transform || transform(toNumber); + + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options) + : toRegex(range, null, { wrap: false, ...options }); + } + + return range; +}; + +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { + return invalidRange(start, end, options); + } + + + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } + + return range; +}; + +const fill$2 = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + + if (typeof step === 'function') { + return fill$2(start, end, 1, { transform: step }); + } + + if (isObject$1(step)) { + return fill$2(start, end, 0, step); + } + + let opts = { ...options }; + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + + if (!isNumber(step)) { + if (step != null && !isObject$1(step)) return invalidStep(step, opts); + return fill$2(start, end, 1, step); + } + + if (isNumber(start) && isNumber(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +var fillRange = fill$2; + +const fill$1 = fillRange; +const utils$h = utils$j; + +const compile$1 = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils$h.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + if (node.isClose === true) { + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? (prefix + node.value) : '('; + } + + if (node.type === 'close') { + return invalid ? (prefix + node.value) : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$h.reduce(node.nodes); + let range = fill$1(...args, { ...options, wrap: false, toRegex: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + return output; + }; + + return walk(ast); +}; + +var compile_1 = compile$1; + +const fill = fillRange; +const stringify$5 = stringify$7; +const utils$g = utils$j; + +const append$1 = (queue = '', stash = '', enclose = false) => { + let result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils$g.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append$1(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele)); + } + } + } + return utils$g.flatten(result); +}; + +const expand$3 = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + + let walk = (node, parent = {}) => { + node.queue = []; + + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append$1(q.pop(), stringify$5(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append$1(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$g.reduce(node.nodes); + + if (utils$g.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fill(...args, options); + if (range.length === 0) { + range = stringify$5(node, options); + } + + q.push(append$1(q.pop(), range)); + node.nodes = []; + return; + } + + let enclose = utils$g.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append$1(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append$1(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils$g.flatten(walk(ast)); +}; + +var expand_1 = expand$3; + +var constants$6 = { + MAX_LENGTH: 1024 * 64, + + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ + + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + + CHAR_ASTERISK: '*', /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; + +const stringify$4 = stringify$7; + +/** + * Constants + */ + +const { + MAX_LENGTH: MAX_LENGTH$1, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA: CHAR_COMMA$1, /* , */ + CHAR_DOT: CHAR_DOT$1, /* . */ + CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ + CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ + CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ + CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ + CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */ + CHAR_DOUBLE_QUOTE, /* " */ + CHAR_SINGLE_QUOTE, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = constants$6; + +/** + * parse + */ + +const parse$k = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + let opts = options || {}; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + let ast = { type: 'root', input, nodes: [] }; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let length = input.length; + let index = 0; + let depth = 0; + let value; + + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ type: 'bos' }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + + /** + * Escaped chars + */ + + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } + + /** + * Right square bracket (literal): ']' + */ + + if (value === CHAR_RIGHT_SQUARE_BRACKET$1) { + push({ type: 'text', value: '\\' + value }); + continue; + } + + /** + * Left square bracket: '[' + */ + + if (value === CHAR_LEFT_SQUARE_BRACKET$1) { + brackets++; + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET$1) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES$1) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES$1) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; + } + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } + + /** + * Quotes: '|"|` + */ + + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + let open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Left curly brace: '{' + */ + + if (value === CHAR_LEFT_CURLY_BRACE$1) { + depth++; + + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } + + /** + * Right curly brace: '}' + */ + + if (value === CHAR_RIGHT_CURLY_BRACE$1) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + + let type = 'close'; + block = stack.pop(); + block.close = true; + + push({ type, value }); + depth--; + + block = stack[stack.length - 1]; + continue; + } + + /** + * Comma: ',' + */ + + if (value === CHAR_COMMA$1 && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + let open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify$4(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) { + let siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + + let before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); + } + + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); + + // get the location of the block on parent.nodes (block's siblings) + let parent = stack[stack.length - 1]; + let index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +var parse_1$2 = parse$k; + +const stringify$3 = stringify$7; +const compile = compile_1; +const expand$2 = expand_1; +const parse$j = parse_1$2; + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces$2 = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces$2.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces$2.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + +braces$2.parse = (input, options = {}) => parse$j(input, options); + +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$2.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify$3(braces$2.parse(input, options), options); + } + return stringify$3(input, options); +}; + +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$2.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces$2.parse(input, options); + } + return compile(input, options); +}; + +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$2.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces$2.parse(input, options); + } + + let result = expand$2(input, options); + + // filter out empty strings if specified + if (options.noempty === true) { + result = result.filter(Boolean); + } + + // filter out duplicates if specified + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; + +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$2.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true + ? braces$2.compile(input, options) + : braces$2.expand(input, options); +}; + +/** + * Expose "braces" + */ + +var braces_1 = braces$2; + +var utils$f = {}; + +const path$t = path__default; +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR$1 = `${QMARK}*?`; + +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR: STAR$1, + START_ANCHOR +}; + +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = { + ...POSIX_CHARS, + + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; + +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE$1 = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + +var constants$5 = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, + + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ + + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ + + CHAR_ASTERISK: 42, /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + + SEP: path$t.sep, + + /** + * Create EXTGLOB_CHARS + */ + + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, + + /** + * Create GLOB_CHARS + */ + + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; + +(function (exports) { + +const path = path__default; +const win32 = process.platform === 'win32'; +const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL +} = constants$5; + +exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); +exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); +exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); +exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); +exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + +exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); +}; + +exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; +}; + +exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path.sep === '\\'; +}; + +exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; +}; + +exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; +}; + +exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; +}; +}(utils$f)); + +const utils$e = utils$f; +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET /* ] */ +} = constants$5; + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; + +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + +const scan$1 = (input, options) => { + const opts = options || {}; + + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; + + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; + + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; + } + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; + } + break; + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils$e.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils$e.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +var scan_1 = scan$1; + +const constants$4 = constants$5; +const utils$d = utils$f; + +/** + * Constants + */ + +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants$4; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + return value; +}; + +/** + * Create the message for a syntax error + */ + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; + +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse$i = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; + + const capture = opts.capture ? '' : '?:'; + const win32 = utils$d.isWindows(options); + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants$4.globChars(win32); + const EXTGLOB_CHARS = constants$4.extglobChars(PLATFORM_CHARS); + + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + + input = utils$d.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + let rest; + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + output = token.close = `)${rest})${extglobStar})`; + } + + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils$d.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils$d.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Square brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + decrement('brackets'); + + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils$d.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils$d.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } + + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } + + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ type: 'comma', value, output }); + continue; + } + + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } + + /** + * Dots + */ + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } + + /** + * Question marks + */ + + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if (next === '<' && !utils$d.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } + + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } + + push({ type: 'text', value, output }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } + + push({ type: 'qmark', value, output: QMARK }); + continue; + } + + /** + * Exclamation + */ + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Plain text + */ + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Stars + */ + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + + state.output += prior.output + prev.output; + state.globstar = true; + + consume(value + advance()); + + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils$d.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils$d.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils$d.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse$i.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + const win32 = utils$d.isWindows(options); + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants$4.globChars(win32); + + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils$d.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +var parse_1$1 = parse$i; + +const path$s = path__default; +const scan = scan_1; +const parse$h = parse_1$1; +const utils$c = utils$f; +const constants$3 = constants$5; +const isObject = val => val && typeof val === 'object' && !Array.isArray(val); + +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + +const picomatch$4 = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch$4(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + + const isState = isObject(glob) && glob.tokens && glob.input; + + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = utils$c.isWindows(options); + const regex = isState + ? picomatch$4.compileRe(glob, options) + : picomatch$4.makeRe(glob, options, false, true); + + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch$4(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch$4.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; + +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + +picomatch$4.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils$c.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch$4.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { isMatch: Boolean(match), match, output }; +}; + +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch$4.matchBase = (input, glob, options, posix = utils$c.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch$4.makeRe(glob, options); + return regex.test(path$s.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +picomatch$4.isMatch = (str, patterns, options) => picomatch$4(patterns, options)(str); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + +picomatch$4.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch$4.parse(p, options)); + return parse$h(pattern, { ...options, fastpaths: false }); +}; + +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +picomatch$4.scan = (input, options) => scan(input, options); + +/** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ + +picomatch$4.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch$4.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } + + return regex; +}; + +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +picomatch$4.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + let parsed = { negated: false, fastpaths: true }; + + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse$h.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse$h(input, options); + } + + return picomatch$4.compileRe(parsed, options, returnOutput, returnState); +}; + +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +picomatch$4.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; + +/** + * Picomatch constants. + * @return {Object} + */ + +picomatch$4.constants = constants$3; + +/** + * Expose "picomatch" + */ + +var picomatch_1 = picomatch$4; + +var picomatch$3 = picomatch_1; + +const util$a = require$$0__default$3; +const braces$1 = braces_1; +const picomatch$2 = picomatch$3; +const utils$b = utils$f; +const isEmptyString = val => val === '' || val === './'; + +/** + * Returns an array of strings that match one or more glob patterns. + * + * ```js + * const mm = require('micromatch'); + * // mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {String|Array} `list` List of strings to match. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + +const micromatch$1 = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); + + let omit = new Set(); + let keep = new Set(); + let items = new Set(); + let negatives = 0; + + let onResult = state => { + items.add(state.output); + if (options && options.onResult) { + options.onResult(state); + } + }; + + for (let i = 0; i < patterns.length; i++) { + let isMatch = picomatch$2(String(patterns[i]), { ...options, onResult }, true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) negatives++; + + for (let item of list) { + let matched = isMatch(item, true); + + let match = negated ? !matched.isMatch : matched.isMatch; + if (!match) continue; + + if (negated) { + omit.add(matched.output); + } else { + omit.delete(matched.output); + keep.add(matched.output); + } + } + } + + let result = negatives === patterns.length ? [...items] : [...keep]; + let matches = result.filter(item => !omit.has(item)); + + if (options && matches.length === 0) { + if (options.failglob === true) { + throw new Error(`No matches found for "${patterns.join(', ')}"`); + } + + if (options.nonull === true || options.nullglob === true) { + return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; + } + } + + return matches; +}; + +/** + * Backwards compatibility + */ + +micromatch$1.match = micromatch$1; + +/** + * Returns a matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * const mm = require('micromatch'); + * // mm.matcher(pattern[, options]); + * + * const isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` + * @return {Function} Returns a matcher function. + * @api public + */ + +micromatch$1.matcher = (pattern, options) => picomatch$2(pattern, options); + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const mm = require('micromatch'); + * // mm.isMatch(string, patterns[, options]); + * + * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(mm.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `[options]` See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch$1.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str); + +/** + * Backwards compatibility + */ + +micromatch$1.any = micromatch$1.isMatch; + +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +micromatch$1.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = new Set(); + let items = []; + + let onResult = state => { + if (options.onResult) options.onResult(state); + items.push(state.output); + }; + + let matches = micromatch$1(list, patterns, { ...options, onResult }); + + for (let item of items) { + if (!matches.includes(item)) { + result.add(item); + } + } + return [...result]; +}; + +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * // mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any of the patterns matches any part of `str`. + * @api public + */ + +micromatch$1.contains = (str, pattern, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util$a.inspect(str)}"`); + } + + if (Array.isArray(pattern)) { + return pattern.some(p => micromatch$1.contains(str, p, options)); + } + + if (typeof pattern === 'string') { + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } + + if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { + return true; + } + } + + return micromatch$1.isMatch(str, pattern, { ...options, contains: true }); +}; + +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * const mm = require('micromatch'); + * // mm.matchKeys(object, patterns[, options]); + * + * const obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + +micromatch$1.matchKeys = (obj, patterns, options) => { + if (!utils$b.isObject(obj)) { + throw new TypeError('Expected the first argument to be an object'); + } + let keys = micromatch$1(Object.keys(obj), patterns, options); + let res = {}; + for (let key of keys) res[key] = obj[key]; + return res; +}; + +/** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` + * @api public + */ + +micromatch$1.some = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch$2(String(pattern), options); + if (items.some(item => isMatch(item))) { + return true; + } + } + return false; +}; + +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` + * @api public + */ + +micromatch$1.every = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch$2(String(pattern), options); + if (!items.every(item => isMatch(item))) { + return false; + } + } + return true; +}; + +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * const mm = require('micromatch'); + * // mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch$1.all = (str, patterns, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util$a.inspect(str)}"`); + } + + return [].concat(patterns).every(p => picomatch$2(p, options)(str)); +}; + +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * const mm = require('micromatch'); + * // mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `glob` Glob pattern to use for matching. + * @param {String} `input` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. + * @api public + */ + +micromatch$1.capture = (glob, input, options) => { + let posix = utils$b.isWindows(options); + let regex = picomatch$2.makeRe(String(glob), { ...options, capture: true }); + let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input); + + if (match) { + return match.slice(1).map(v => v === void 0 ? '' : v); + } +}; + +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * const mm = require('micromatch'); + * // mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +micromatch$1.makeRe = (...args) => picomatch$2.makeRe(...args); + +/** + * Scan a glob pattern to separate the pattern into segments. Used + * by the [split](#split) method. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.scan(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +micromatch$1.scan = (...args) => picomatch$2.scan(...args); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const mm = require('micromatch'); + * const state = mm(pattern[, options]); + * ``` + * @param {String} `glob` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as regex source string. + * @api public + */ + +micromatch$1.parse = (patterns, options) => { + let res = []; + for (let pattern of [].concat(patterns || [])) { + for (let str of braces$1(String(pattern), options)) { + res.push(picomatch$2.parse(str, options)); + } + } + return res; +}; + +/** + * Process the given brace `pattern`. + * + * ```js + * const { braces } = require('micromatch'); + * console.log(braces('foo/{a,b,c}/bar')); + * //=> [ 'foo/(a|b|c)/bar' ] + * + * console.log(braces('foo/{a,b,c}/bar', { expand: true })); + * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] + * ``` + * @param {String} `pattern` String with brace pattern to process. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ + +micromatch$1.braces = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { + return [pattern]; + } + return braces$1(pattern, options); +}; + +/** + * Expand braces + */ + +micromatch$1.braceExpand = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + return micromatch$1.braces(pattern, { ...options, expand: true }); +}; + +/** + * Expose micromatch + */ + +var micromatch_1 = micromatch$1; + +Object.defineProperty(pattern$1, "__esModule", { value: true }); +pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0; +const path$r = path__default; +const globParent$1 = globParent$2; +const micromatch = micromatch_1; +const GLOBSTAR$2 = '**'; +const ESCAPE_SYMBOL = '\\'; +const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; +const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/; +const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/; +const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/; +const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/; +function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); +} +pattern$1.isStaticPattern = isStaticPattern; +function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === '') { + return false; + } + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) { + return true; + } + return false; +} +pattern$1.isDynamicPattern = isDynamicPattern; +function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; +} +pattern$1.convertToPositivePattern = convertToPositivePattern; +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +pattern$1.convertToNegativePattern = convertToNegativePattern; +function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; +} +pattern$1.isNegativePattern = isNegativePattern; +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +pattern$1.isPositivePattern = isPositivePattern; +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +pattern$1.getNegativePatterns = getNegativePatterns; +function getPositivePatterns$1(patterns) { + return patterns.filter(isPositivePattern); +} +pattern$1.getPositivePatterns = getPositivePatterns$1; +/** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsInsideCurrentDirectory(patterns) { + return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); +} +pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; +/** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsOutsideCurrentDirectory(patterns) { + return patterns.filter(isPatternRelatedToParentDirectory); +} +pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; +function isPatternRelatedToParentDirectory(pattern) { + return pattern.startsWith('..') || pattern.startsWith('./..'); +} +pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; +function getBaseDirectory(pattern) { + return globParent$1(pattern, { flipBackslashes: false }); +} +pattern$1.getBaseDirectory = getBaseDirectory; +function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR$2); +} +pattern$1.hasGlobStar = hasGlobStar; +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR$2); +} +pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar; +function isAffectDepthOfReadingPattern(pattern) { + const basename = path$r.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); +} +pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; +function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); +} +pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; +function expandBraceExpansion(pattern) { + return micromatch.braces(pattern, { + expand: true, + nodupes: true + }); +} +pattern$1.expandBraceExpansion = expandBraceExpansion; +function getPatternParts(pattern, options) { + let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + if (parts.length === 0) { + parts = [pattern]; + } + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + if (parts[0].startsWith('/')) { + parts[0] = parts[0].slice(1); + parts.unshift(''); + } + return parts; +} +pattern$1.getPatternParts = getPatternParts; +function makeRe$1(pattern, options) { + return micromatch.makeRe(pattern, options); +} +pattern$1.makeRe = makeRe$1; +function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe$1(pattern, options)); +} +pattern$1.convertPatternsToRe = convertPatternsToRe; +function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); +} +pattern$1.matchAny = matchAny; + +var stream$7 = {}; + +/* + * merge2 + * https://github.com/teambition/merge2 + * + * Copyright (c) 2014-2020 Teambition + * Licensed under the MIT license. + */ +const Stream = require$$0__default$2; +const PassThrough$1 = Stream.PassThrough; +const slice$1 = Array.prototype.slice; + +var merge2_1 = merge2$2; + +function merge2$2 () { + const streamsQueue = []; + const args = slice$1.call(arguments); + let merging = false; + let options = args[args.length - 1]; + + if (options && !Array.isArray(options) && options.pipe == null) { + args.pop(); + } else { + options = {}; + } + + const doEnd = options.end !== false; + const doPipeError = options.pipeError === true; + if (options.objectMode == null) { + options.objectMode = true; + } + if (options.highWaterMark == null) { + options.highWaterMark = 64 * 1024; + } + const mergedStream = PassThrough$1(options); + + function addStream () { + for (let i = 0, len = arguments.length; i < len; i++) { + streamsQueue.push(pauseStreams(arguments[i], options)); + } + mergeStream(); + return this + } + + function mergeStream () { + if (merging) { + return + } + merging = true; + + let streams = streamsQueue.shift(); + if (!streams) { + process.nextTick(endStream); + return + } + if (!Array.isArray(streams)) { + streams = [streams]; + } + + let pipesCount = streams.length + 1; + + function next () { + if (--pipesCount > 0) { + return + } + merging = false; + mergeStream(); + } + + function pipe (stream) { + function onend () { + stream.removeListener('merge2UnpipeEnd', onend); + stream.removeListener('end', onend); + if (doPipeError) { + stream.removeListener('error', onerror); + } + next(); + } + function onerror (err) { + mergedStream.emit('error', err); + } + // skip ended stream + if (stream._readableState.endEmitted) { + return next() + } + + stream.on('merge2UnpipeEnd', onend); + stream.on('end', onend); + + if (doPipeError) { + stream.on('error', onerror); + } + + stream.pipe(mergedStream, { end: false }); + // compatible for old stream + stream.resume(); + } + + for (let i = 0; i < streams.length; i++) { + pipe(streams[i]); + } + + next(); + } + + function endStream () { + merging = false; + // emit 'queueDrain' when all streams merged. + mergedStream.emit('queueDrain'); + if (doEnd) { + mergedStream.end(); + } + } + + mergedStream.setMaxListeners(0); + mergedStream.add = addStream; + mergedStream.on('unpipe', function (stream) { + stream.emit('merge2UnpipeEnd'); + }); + + if (args.length) { + addStream.apply(null, args); + } + return mergedStream +} + +// check and pause streams for pipe. +function pauseStreams (streams, options) { + if (!Array.isArray(streams)) { + // Backwards-compat with old-style streams + if (!streams._readableState && streams.pipe) { + streams = streams.pipe(PassThrough$1(options)); + } + if (!streams._readableState || !streams.pause || !streams.pipe) { + throw new Error('Only readable stream can be merged.') + } + streams.pause(); + } else { + for (let i = 0, len = streams.length; i < len; i++) { + streams[i] = pauseStreams(streams[i], options); + } + } + return streams +} + +Object.defineProperty(stream$7, "__esModule", { value: true }); +stream$7.merge = void 0; +const merge2$1 = merge2_1; +function merge$2(streams) { + const mergedStream = merge2$1(streams); + streams.forEach((stream) => { + stream.once('error', (error) => mergedStream.emit('error', error)); + }); + mergedStream.once('close', () => propagateCloseEventToSources(streams)); + mergedStream.once('end', () => propagateCloseEventToSources(streams)); + return mergedStream; +} +stream$7.merge = merge$2; +function propagateCloseEventToSources(streams) { + streams.forEach((stream) => stream.emit('close')); +} + +var string$2 = {}; + +Object.defineProperty(string$2, "__esModule", { value: true }); +string$2.isEmpty = string$2.isString = void 0; +function isString$1(input) { + return typeof input === 'string'; +} +string$2.isString = isString$1; +function isEmpty(input) { + return input === ''; +} +string$2.isEmpty = isEmpty; + +Object.defineProperty(utils$k, "__esModule", { value: true }); +utils$k.string = utils$k.stream = utils$k.pattern = utils$k.path = utils$k.fs = utils$k.errno = utils$k.array = void 0; +const array = array$1; +utils$k.array = array; +const errno = errno$1; +utils$k.errno = errno; +const fs$t = fs$u; +utils$k.fs = fs$t; +const path$q = path$v; +utils$k.path = path$q; +const pattern = pattern$1; +utils$k.pattern = pattern; +const stream$6 = stream$7; +utils$k.stream = stream$6; +const string$1 = string$2; +utils$k.string = string$1; + +Object.defineProperty(tasks, "__esModule", { value: true }); +tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0; +const utils$a = utils$k; +function generate(patterns, settings) { + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); + const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); + return staticTasks.concat(dynamicTasks); +} +tasks.generate = generate; +/** + * Returns tasks grouped by basic pattern directories. + * + * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. + * This is necessary because directory traversal starts at the base directory and goes deeper. + */ +function convertPatternsToTasks(positive, negative, dynamic) { + const tasks = []; + const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive); + const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive); + const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); + const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); + tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); + /* + * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory + * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. + */ + if ('.' in insideCurrentDirectoryGroup) { + tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); + } + else { + tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + } + return tasks; +} +tasks.convertPatternsToTasks = convertPatternsToTasks; +function getPositivePatterns(patterns) { + return utils$a.pattern.getPositivePatterns(patterns); +} +tasks.getPositivePatterns = getPositivePatterns; +function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils$a.pattern.convertToPositivePattern); + return positive; +} +tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive; +function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils$a.pattern.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } + else { + collection[base] = [pattern]; + } + return collection; + }, group); +} +tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; +function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); +} +tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks; +function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern)) + }; +} +tasks.convertPatternGroupToTask = convertPatternGroupToTask; + +var async$6 = {}; + +var stream$5 = {}; + +var out$3 = {}; + +var async$5 = {}; + +Object.defineProperty(async$5, "__esModule", { value: true }); +async$5.read = void 0; +function read$4(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + callFailureCallback$2(callback, lstatError); + return; + } + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + callSuccessCallback$2(callback, lstat); + return; + } + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + callFailureCallback$2(callback, statError); + return; + } + callSuccessCallback$2(callback, lstat); + return; + } + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + callSuccessCallback$2(callback, stat); + }); + }); +} +async$5.read = read$4; +function callFailureCallback$2(callback, error) { + callback(error); +} +function callSuccessCallback$2(callback, result) { + callback(null, result); +} + +var sync$b = {}; + +Object.defineProperty(sync$b, "__esModule", { value: true }); +sync$b.read = void 0; +function read$3(path, settings) { + const lstat = settings.fs.lstatSync(path); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + try { + const stat = settings.fs.statSync(path); + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + return stat; + } + catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + throw error; + } +} +sync$b.read = read$3; + +var settings$3 = {}; + +var fs$s = {}; + +(function (exports) { +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; +const fs = fs__default; +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; +}(fs$s)); + +Object.defineProperty(settings$3, "__esModule", { value: true }); +const fs$r = fs$s; +class Settings$2 { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs$r.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +settings$3.default = Settings$2; + +Object.defineProperty(out$3, "__esModule", { value: true }); +out$3.statSync = out$3.stat = out$3.Settings = void 0; +const async$4 = async$5; +const sync$a = sync$b; +const settings_1$3 = settings$3; +out$3.Settings = settings_1$3.default; +function stat$5(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async$4.read(path, getSettings$2(), optionsOrSettingsOrCallback); + return; + } + async$4.read(path, getSettings$2(optionsOrSettingsOrCallback), callback); +} +out$3.stat = stat$5; +function statSync(path, optionsOrSettings) { + const settings = getSettings$2(optionsOrSettings); + return sync$a.read(path, settings); +} +out$3.statSync = statSync; +function getSettings$2(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$3.default) { + return settingsOrOptions; + } + return new settings_1$3.default(settingsOrOptions); +} + +var out$2 = {}; + +var async$3 = {}; + +var async$2 = {}; + +var out$1 = {}; + +var async$1 = {}; + +/*! queue-microtask. MIT License. Feross Aboukhadijeh */ + +let promise$1; + +var queueMicrotask_1 = typeof queueMicrotask === 'function' + ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal) + // reuse resolved promise, and allocate it lazily + : cb => (promise$1 || (promise$1 = Promise.resolve())) + .then(cb) + .catch(err => setTimeout(() => { throw err }, 0)); + +/*! run-parallel. MIT License. Feross Aboukhadijeh */ + +var runParallel_1 = runParallel; + +const queueMicrotask$1 = queueMicrotask_1; + +function runParallel (tasks, cb) { + let results, pending, keys; + let isSync = true; + + if (Array.isArray(tasks)) { + results = []; + pending = tasks.length; + } else { + keys = Object.keys(tasks); + results = {}; + pending = keys.length; + } + + function done (err) { + function end () { + if (cb) cb(err, results); + cb = null; + } + if (isSync) queueMicrotask$1(end); + else end(); + } + + function each (i, err, result) { + results[i] = result; + if (--pending === 0 || err) { + done(err); + } + } + + if (!pending) { + // empty + done(null); + } else if (keys) { + // object + keys.forEach(function (key) { + tasks[key](function (err, result) { each(key, err, result); }); + }); + } else { + // array + tasks.forEach(function (task, i) { + task(function (err, result) { each(i, err, result); }); + }); + } + + isSync = false; +} + +var constants$2 = {}; + +Object.defineProperty(constants$2, "__esModule", { value: true }); +constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; +const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); +if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { + throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); +} +const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); +const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); +const SUPPORTED_MAJOR_VERSION = 10; +const SUPPORTED_MINOR_VERSION = 10; +const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; +const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; +/** + * IS `true` for Node.js 10.10 and greater. + */ +constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; + +var utils$9 = {}; + +var fs$q = {}; + +Object.defineProperty(fs$q, "__esModule", { value: true }); +fs$q.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +fs$q.createDirentFromStats = createDirentFromStats; + +Object.defineProperty(utils$9, "__esModule", { value: true }); +utils$9.fs = void 0; +const fs$p = fs$q; +utils$9.fs = fs$p; + +var common$d = {}; + +Object.defineProperty(common$d, "__esModule", { value: true }); +common$d.joinPathSegments = void 0; +function joinPathSegments$1(a, b, separator) { + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +common$d.joinPathSegments = joinPathSegments$1; + +Object.defineProperty(async$1, "__esModule", { value: true }); +async$1.readdir = async$1.readdirWithFileTypes = async$1.read = void 0; +const fsStat$5 = out$3; +const rpl = runParallel_1; +const constants_1$1 = constants$2; +const utils$8 = utils$9; +const common$c = common$d; +function read$2(directory, settings, callback) { + if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + readdirWithFileTypes$1(directory, settings, callback); + return; + } + readdir$3(directory, settings, callback); +} +async$1.read = read$2; +function readdirWithFileTypes$1(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + callFailureCallback$1(callback, readdirError); + return; + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: common$c.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + })); + if (!settings.followSymbolicLinks) { + callSuccessCallback$1(callback, entries); + return; + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + rpl(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + callFailureCallback$1(callback, rplError); + return; + } + callSuccessCallback$1(callback, rplEntries); + }); + }); +} +async$1.readdirWithFileTypes = readdirWithFileTypes$1; +function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + done(null, entry); + return; + } + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + done(statError); + return; + } + done(null, entry); + return; + } + entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats); + done(null, entry); + }); + }; +} +function readdir$3(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + callFailureCallback$1(callback, readdirError); + return; + } + const tasks = names.map((name) => { + const path = common$c.joinPathSegments(directory, name, settings.pathSegmentSeparator); + return (done) => { + fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => { + if (error !== null) { + done(error); + return; + } + const entry = { + name, + path, + dirent: utils$8.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + done(null, entry); + }); + }; + }); + rpl(tasks, (rplError, entries) => { + if (rplError !== null) { + callFailureCallback$1(callback, rplError); + return; + } + callSuccessCallback$1(callback, entries); + }); + }); +} +async$1.readdir = readdir$3; +function callFailureCallback$1(callback, error) { + callback(error); +} +function callSuccessCallback$1(callback, result) { + callback(null, result); +} + +var sync$9 = {}; + +Object.defineProperty(sync$9, "__esModule", { value: true }); +sync$9.readdir = sync$9.readdirWithFileTypes = sync$9.read = void 0; +const fsStat$4 = out$3; +const constants_1 = constants$2; +const utils$7 = utils$9; +const common$b = common$d; +function read$1(directory, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + return readdir$2(directory, settings); +} +sync$9.read = read$1; +function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); + return dirents.map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: common$b.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats); + } + catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + return entry; + }); +} +sync$9.readdirWithFileTypes = readdirWithFileTypes; +function readdir$2(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map((name) => { + const entryPath = common$b.joinPathSegments(directory, name, settings.pathSegmentSeparator); + const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils$7.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + return entry; + }); +} +sync$9.readdir = readdir$2; + +var settings$2 = {}; + +var fs$o = {}; + +(function (exports) { +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; +const fs = fs__default; +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; +}(fs$o)); + +Object.defineProperty(settings$2, "__esModule", { value: true }); +const path$p = path__default; +const fsStat$3 = out$3; +const fs$n = fs$o; +class Settings$1 { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs$n.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$p.sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new fsStat$3.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +settings$2.default = Settings$1; + +Object.defineProperty(out$1, "__esModule", { value: true }); +out$1.Settings = out$1.scandirSync = out$1.scandir = void 0; +const async = async$1; +const sync$8 = sync$9; +const settings_1$2 = settings$2; +out$1.Settings = settings_1$2.default; +function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings$1(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback); +} +out$1.scandir = scandir; +function scandirSync(path, optionsOrSettings) { + const settings = getSettings$1(optionsOrSettings); + return sync$8.read(path, settings); +} +out$1.scandirSync = scandirSync; +function getSettings$1(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$2.default) { + return settingsOrOptions; + } + return new settings_1$2.default(settingsOrOptions); +} + +var queue = {exports: {}}; + +function reusify$1 (Constructor) { + var head = new Constructor(); + var tail = head; + + function get () { + var current = head; + + if (current.next) { + head = current.next; + } else { + head = new Constructor(); + tail = head; + } + + current.next = null; + + return current + } + + function release (obj) { + tail.next = obj; + tail = obj; + } + + return { + get: get, + release: release + } +} + +var reusify_1 = reusify$1; + +/* eslint-disable no-var */ + +var reusify = reusify_1; + +function fastqueue (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker; + worker = context; + context = null; + } + + if (concurrency < 1) { + throw new Error('fastqueue concurrency must be greater than 1') + } + + var cache = reusify(Task); + var queueHead = null; + var queueTail = null; + var _running = 0; + var errorHandler = null; + + var self = { + push: push, + drain: noop$4, + saturated: noop$4, + pause: pause, + paused: false, + concurrency: concurrency, + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop$4, + kill: kill, + killAndDrain: killAndDrain, + error: error + }; + + return self + + function running () { + return _running + } + + function pause () { + self.paused = true; + } + + function length () { + var current = queueHead; + var counter = 0; + + while (current) { + current = current.next; + counter++; + } + + return counter + } + + function getQueue () { + var current = queueHead; + var tasks = []; + + while (current) { + tasks.push(current.value); + current = current.next; + } + + return tasks + } + + function resume () { + if (!self.paused) return + self.paused = false; + for (var i = 0; i < self.concurrency; i++) { + _running++; + release(); + } + } + + function idle () { + return _running === 0 && self.length() === 0 + } + + function push (value, done) { + var current = cache.get(); + + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop$4; + current.errorHandler = errorHandler; + + if (_running === self.concurrency || self.paused) { + if (queueTail) { + queueTail.next = current; + queueTail = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + } else { + _running++; + worker.call(context, current.value, current.worked); + } + } + + function unshift (value, done) { + var current = cache.get(); + + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop$4; + + if (_running === self.concurrency || self.paused) { + if (queueHead) { + current.next = queueHead; + queueHead = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + } else { + _running++; + worker.call(context, current.value, current.worked); + } + } + + function release (holder) { + if (holder) { + cache.release(holder); + } + var next = queueHead; + if (next) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null; + } + queueHead = next.next; + next.next = null; + worker.call(context, next.value, next.worked); + if (queueTail === null) { + self.empty(); + } + } else { + _running--; + } + } else if (--_running === 0) { + self.drain(); + } + } + + function kill () { + queueHead = null; + queueTail = null; + self.drain = noop$4; + } + + function killAndDrain () { + queueHead = null; + queueTail = null; + self.drain(); + self.drain = noop$4; + } + + function error (handler) { + errorHandler = handler; + } +} + +function noop$4 () {} + +function Task () { + this.value = null; + this.callback = noop$4; + this.next = null; + this.release = noop$4; + this.context = null; + this.errorHandler = null; + + var self = this; + + this.worked = function worked (err, result) { + var callback = self.callback; + var errorHandler = self.errorHandler; + var val = self.value; + self.value = null; + self.callback = noop$4; + if (self.errorHandler) { + errorHandler(err, val); + } + callback.call(self.context, err, result); + self.release(self); + }; +} + +function queueAsPromised (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker; + worker = context; + context = null; + } + + function asyncWrapper (arg, cb) { + worker.call(this, arg) + .then(function (res) { + cb(null, res); + }, cb); + } + + var queue = fastqueue(context, asyncWrapper, concurrency); + + var pushCb = queue.push; + var unshiftCb = queue.unshift; + + queue.push = push; + queue.unshift = unshift; + + return queue + + function push (value) { + var p = new Promise(function (resolve, reject) { + pushCb(value, function (err, result) { + if (err) { + reject(err); + return + } + resolve(result); + }); + }); + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop$4); + + return p + } + + function unshift (value) { + var p = new Promise(function (resolve, reject) { + unshiftCb(value, function (err, result) { + if (err) { + reject(err); + return + } + resolve(result); + }); + }); + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop$4); + + return p + } +} + +queue.exports = fastqueue; +queue.exports.promise = queueAsPromised; + +var common$a = {}; + +Object.defineProperty(common$a, "__esModule", { value: true }); +common$a.joinPathSegments = common$a.replacePathSegmentSeparator = common$a.isAppliedFilter = common$a.isFatalError = void 0; +function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + return !settings.errorFilter(error); +} +common$a.isFatalError = isFatalError; +function isAppliedFilter(filter, value) { + return filter === null || filter(value); +} +common$a.isAppliedFilter = isAppliedFilter; +function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[/\\]/).join(separator); +} +common$a.replacePathSegmentSeparator = replacePathSegmentSeparator; +function joinPathSegments(a, b, separator) { + if (a === '') { + return b; + } + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +common$a.joinPathSegments = joinPathSegments; + +var reader$1 = {}; + +Object.defineProperty(reader$1, "__esModule", { value: true }); +const common$9 = common$a; +class Reader$1 { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common$9.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } +} +reader$1.default = Reader$1; + +Object.defineProperty(async$2, "__esModule", { value: true }); +const events_1 = require$$0__default$6; +const fsScandir$2 = out$1; +const fastq = queue.exports; +const common$8 = common$a; +const reader_1$3 = reader$1; +class AsyncReader extends reader_1$3.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir$2.scandir; + this._emitter = new events_1.EventEmitter(); + this._queue = fastq(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + get isDestroyed() { + return this._isDestroyed; + } + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on('entry', callback); + } + onError(callback) { + this._emitter.once('error', callback); + } + onEnd(callback) { + this._emitter.once('end', callback); + } + _pushToQueue(directory, base) { + const queueItem = { directory, base }; + this._queue.push(queueItem, (error) => { + if (error !== null) { + this._handleError(error); + } + }); + } + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + done(error, undefined); + return; + } + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + done(null, undefined); + }); + } + _handleError(error) { + if (this._isDestroyed || !common$8.isFatalError(this._settings, error)) { + return; + } + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit('error', error); + } + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common$8.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common$8.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common$8.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } +} +async$2.default = AsyncReader; + +Object.defineProperty(async$3, "__esModule", { value: true }); +const async_1$3 = async$2; +class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1$3.default(this._root, this._settings); + this._storage = []; + } + read(callback) { + this._reader.onError((error) => { + callFailureCallback(callback, error); + }); + this._reader.onEntry((entry) => { + this._storage.push(entry); + }); + this._reader.onEnd(() => { + callSuccessCallback(callback, this._storage); + }); + this._reader.read(); + } +} +async$3.default = AsyncProvider; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, entries) { + callback(null, entries); +} + +var stream$4 = {}; + +Object.defineProperty(stream$4, "__esModule", { value: true }); +const stream_1$5 = require$$0__default$2; +const async_1$2 = async$2; +class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1$2.default(this._root, this._settings); + this._stream = new stream_1$5.Readable({ + objectMode: true, + read: () => { }, + destroy: () => { + if (!this._reader.isDestroyed) { + this._reader.destroy(); + } + } + }); + } + read() { + this._reader.onError((error) => { + this._stream.emit('error', error); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } +} +stream$4.default = StreamProvider; + +var sync$7 = {}; + +var sync$6 = {}; + +Object.defineProperty(sync$6, "__esModule", { value: true }); +const fsScandir$1 = out$1; +const common$7 = common$a; +const reader_1$2 = reader$1; +class SyncReader extends reader_1$2.default { + constructor() { + super(...arguments); + this._scandir = fsScandir$1.scandirSync; + this._storage = []; + this._queue = new Set(); + } + read() { + this._pushToQueue(this._root, this._settings.basePath); + this._handleQueue(); + return this._storage; + } + _pushToQueue(directory, base) { + this._queue.add({ directory, base }); + } + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.directory, item.base); + } + } + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + for (const entry of entries) { + this._handleEntry(entry, base); + } + } + catch (error) { + this._handleError(error); + } + } + _handleError(error) { + if (!common$7.isFatalError(this._settings, error)) { + return; + } + throw error; + } + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common$7.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common$7.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + if (entry.dirent.isDirectory() && common$7.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _pushToStorage(entry) { + this._storage.push(entry); + } +} +sync$6.default = SyncReader; + +Object.defineProperty(sync$7, "__esModule", { value: true }); +const sync_1$3 = sync$6; +class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync_1$3.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } +} +sync$7.default = SyncProvider; + +var settings$1 = {}; + +Object.defineProperty(settings$1, "__esModule", { value: true }); +const path$o = path__default; +const fsScandir = out$1; +class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$o.sep); + this.fsScandirSettings = new fsScandir.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +settings$1.default = Settings; + +Object.defineProperty(out$2, "__esModule", { value: true }); +out$2.Settings = out$2.walkStream = out$2.walkSync = out$2.walk = void 0; +const async_1$1 = async$3; +const stream_1$4 = stream$4; +const sync_1$2 = sync$7; +const settings_1$1 = settings$1; +out$2.Settings = settings_1$1.default; +function walk$5(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + new async_1$1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + return; + } + new async_1$1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); +} +out$2.walk = walk$5; +function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync_1$2.default(directory, settings); + return provider.read(); +} +out$2.walkSync = walkSync; +function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream_1$4.default(directory, settings); + return provider.read(); +} +out$2.walkStream = walkStream; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$1.default) { + return settingsOrOptions; + } + return new settings_1$1.default(settingsOrOptions); +} + +var reader = {}; + +Object.defineProperty(reader, "__esModule", { value: true }); +const path$n = path__default; +const fsStat$2 = out$3; +const utils$6 = utils$k; +class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat$2.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path$n.resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils$6.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) { + entry.stats = stats; + } + return entry; + } + _isFatalError(error) { + return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } +} +reader.default = Reader; + +Object.defineProperty(stream$5, "__esModule", { value: true }); +const stream_1$3 = require$$0__default$2; +const fsStat$1 = out$3; +const fsWalk$1 = out$2; +const reader_1$1 = reader; +class ReaderStream extends reader_1$1.default { + constructor() { + super(...arguments); + this._walkStream = fsWalk$1.walkStream; + this._stat = fsStat$1.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream_1$3.PassThrough({ objectMode: true }); + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options) + .then((entry) => { + if (entry !== null && options.entryFilter(entry)) { + stream.push(entry); + } + if (index === filepaths.length - 1) { + stream.end(); + } + done(); + }) + .catch(done); + }; + for (let i = 0; i < filepaths.length; i++) { + stream.write(i); + } + return stream; + } + _getEntry(filepath, pattern, options) { + return this._getStat(filepath) + .then((stats) => this._makeEntry(stats, pattern)) + .catch((error) => { + if (options.errorFilter(error)) { + return null; + } + throw error; + }); + } + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); + } +} +stream$5.default = ReaderStream; + +var provider = {}; + +var deep = {}; + +var partial = {}; + +var matcher = {}; + +Object.defineProperty(matcher, "__esModule", { value: true }); +const utils$5 = utils$k; +class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + this._fillStorage(); + } + _fillStorage() { + /** + * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). + * So, before expand patterns with brace expansion into separated patterns. + */ + const patterns = utils$5.pattern.expandPatternsWithBraceExpansion(this._patterns); + for (const pattern of patterns) { + const segments = this._getPatternSegments(pattern); + const sections = this._splitSegmentsIntoSections(segments); + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + _getPatternSegments(pattern) { + const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map((part) => { + const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings); + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + return { + dynamic: true, + pattern: part, + patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern)); + } +} +matcher.default = Matcher; + +Object.defineProperty(partial, "__esModule", { value: true }); +const matcher_1 = matcher; +class PartialMatcher extends matcher_1.default { + match(filepath) { + const parts = filepath.split('/'); + const levels = parts.length; + const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + if (!pattern.complete && levels > section.length) { + return true; + } + const match = parts.every((part, index) => { + const segment = pattern.segments[index]; + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + if (!segment.dynamic && segment.pattern === part) { + return true; + } + return false; + }); + if (match) { + return true; + } + } + return false; + } +} +partial.default = PartialMatcher; + +Object.defineProperty(deep, "__esModule", { value: true }); +const utils$4 = utils$k; +const partial_1 = partial; +class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, matcher, negativeRe); + } + _getMatcher(patterns) { + return new partial_1.default(patterns, this._settings, this._micromatchOptions); + } + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern); + return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; + } + if (this._isSkippedSymbolicLink(entry)) { + return false; + } + const filepath = utils$4.path.removeLeadingDotSegment(entry.path); + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; + } + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) { + return false; + } + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split('/').length; + if (basePath === '') { + return entryPathDepth; + } + const basePathDepth = basePath.split('/').length; + return entryPathDepth - basePathDepth; + } + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils$4.pattern.matchAny(entryPath, patternsRe); + } +} +deep.default = DeepFilter; + +var entry$1 = {}; + +Object.defineProperty(entry$1, "__esModule", { value: true }); +const utils$3 = utils$k; +class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + getFilter(positive, negative) { + const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions); + const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions); + return (entry) => this._filter(entry, positiveRe, negativeRe); + } + _filter(entry, positiveRe, negativeRe) { + if (this._settings.unique && this._isDuplicateEntry(entry)) { + return false; + } + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; + } + if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { + return false; + } + const filepath = this._settings.baseNameMatch ? entry.name : entry.path; + const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); + if (this._settings.unique && isMatched) { + this._createIndexRecord(entry); + } + return isMatched; + } + _isDuplicateEntry(entry) { + return this.index.has(entry.path); + } + _createIndexRecord(entry) { + this.index.set(entry.path, undefined); + } + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { + if (!this._settings.absolute) { + return false; + } + const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath); + return utils$3.pattern.matchAny(fullpath, patternsRe); + } + _isMatchToPatterns(entryPath, patternsRe) { + const filepath = utils$3.path.removeLeadingDotSegment(entryPath); + return utils$3.pattern.matchAny(filepath, patternsRe); + } +} +entry$1.default = EntryFilter; + +var error$4 = {}; + +Object.defineProperty(error$4, "__esModule", { value: true }); +const utils$2 = utils$k; +class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + getFilter() { + return (error) => this._isNonFatalError(error); + } + _isNonFatalError(error) { + return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + } +} +error$4.default = ErrorFilter; + +var entry = {}; + +Object.defineProperty(entry, "__esModule", { value: true }); +const utils$1 = utils$k; +class EntryTransformer { + constructor(_settings) { + this._settings = _settings; + } + getTransformer() { + return (entry) => this._transform(entry); + } + _transform(entry) { + let filepath = entry.path; + if (this._settings.absolute) { + filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils$1.path.unixify(filepath); + } + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += '/'; + } + if (!this._settings.objectMode) { + return filepath; + } + return Object.assign(Object.assign({}, entry), { path: filepath }); + } +} +entry.default = EntryTransformer; + +Object.defineProperty(provider, "__esModule", { value: true }); +const path$m = path__default; +const deep_1 = deep; +const entry_1 = entry$1; +const error_1 = error$4; +const entry_2 = entry; +class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error_1.default(this._settings); + this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry_2.default(this._settings); + } + _getRootDirectory(task) { + return path$m.resolve(this._settings.cwd, task.base); + } + _getReaderOptions(task) { + const basePath = task.base === '.' ? '' : task.base; + return { + basePath, + pathSegmentSeparator: '/', + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } +} +provider.default = Provider; + +Object.defineProperty(async$6, "__esModule", { value: true }); +const stream_1$2 = stream$5; +const provider_1$2 = provider; +class ProviderAsync extends provider_1$2.default { + constructor() { + super(...arguments); + this._reader = new stream_1$2.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = []; + return new Promise((resolve, reject) => { + const stream = this.api(root, task, options); + stream.once('error', reject); + stream.on('data', (entry) => entries.push(options.transform(entry))); + stream.once('end', () => resolve(entries)); + }); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +async$6.default = ProviderAsync; + +var stream$3 = {}; + +Object.defineProperty(stream$3, "__esModule", { value: true }); +const stream_1$1 = require$$0__default$2; +const stream_2 = stream$5; +const provider_1$1 = provider; +class ProviderStream extends provider_1$1.default { + constructor() { + super(...arguments); + this._reader = new stream_2.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const source = this.api(root, task, options); + const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } }); + source + .once('error', (error) => destination.emit('error', error)) + .on('data', (entry) => destination.emit('data', options.transform(entry))) + .once('end', () => destination.emit('end')); + destination + .once('close', () => source.destroy()); + return destination; + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +stream$3.default = ProviderStream; + +var sync$5 = {}; + +var sync$4 = {}; + +Object.defineProperty(sync$4, "__esModule", { value: true }); +const fsStat = out$3; +const fsWalk = out$2; +const reader_1 = reader; +class ReaderSync extends reader_1.default { + constructor() { + super(...arguments); + this._walkSync = fsWalk.walkSync; + this._statSync = fsStat.statSync; + } + dynamic(root, options) { + return this._walkSync(root, options); + } + static(patterns, options) { + const entries = []; + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + const entry = this._getEntry(filepath, pattern, options); + if (entry === null || !options.entryFilter(entry)) { + continue; + } + entries.push(entry); + } + return entries; + } + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); + } + catch (error) { + if (options.errorFilter(error)) { + return null; + } + throw error; + } + } + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); + } +} +sync$4.default = ReaderSync; + +Object.defineProperty(sync$5, "__esModule", { value: true }); +const sync_1$1 = sync$4; +const provider_1 = provider; +class ProviderSync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1$1.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = this.api(root, task, options); + return entries.map(options.transform); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +sync$5.default = ProviderSync; + +var settings = {}; + +(function (exports) { +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; +const fs = fs__default; +const os = require$$0__default$1; +/** + * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. + * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 + */ +const CPU_COUNT = Math.max(os.cpus().length, 1); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + lstatSync: fs.lstatSync, + stat: fs.stat, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync +}; +class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + if (this.onlyDirectories) { + this.onlyFiles = false; + } + if (this.stats) { + this.objectMode = true; + } + } + _getValue(option, value) { + return option === undefined ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } +} +exports.default = Settings; +}(settings)); + +const taskManager = tasks; +const async_1 = async$6; +const stream_1 = stream$3; +const sync_1 = sync$5; +const settings_1 = settings; +const utils = utils$k; +async function FastGlob(source, options) { + assertPatternsInput$1(source); + const works = getWorks(source, async_1.default, options); + const result = await Promise.all(works); + return utils.array.flatten(result); +} +// https://github.com/typescript-eslint/typescript-eslint/issues/60 +// eslint-disable-next-line no-redeclare +(function (FastGlob) { + function sync(source, options) { + assertPatternsInput$1(source); + const works = getWorks(source, sync_1.default, options); + return utils.array.flatten(works); + } + FastGlob.sync = sync; + function stream(source, options) { + assertPatternsInput$1(source); + const works = getWorks(source, stream_1.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + return utils.stream.merge(works); + } + FastGlob.stream = stream; + function generateTasks(source, options) { + assertPatternsInput$1(source); + const patterns = [].concat(source); + const settings = new settings_1.default(options); + return taskManager.generate(patterns, settings); + } + FastGlob.generateTasks = generateTasks; + function isDynamicPattern(source, options) { + assertPatternsInput$1(source); + const settings = new settings_1.default(options); + return utils.pattern.isDynamicPattern(source, settings); + } + FastGlob.isDynamicPattern = isDynamicPattern; + function escapePath(source) { + assertPatternsInput$1(source); + return utils.path.escape(source); + } + FastGlob.escapePath = escapePath; +})(FastGlob || (FastGlob = {})); +function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings_1.default(options); + const tasks = taskManager.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks.map(provider.read, provider); +} +function assertPatternsInput$1(input) { + const source = [].concat(input); + const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); + if (!isValidSource) { + throw new TypeError('Patterns must be a string (non empty) or an array of strings'); + } +} +var out = FastGlob; + +var dist$3 = {}; + +(function (exports) { +Object.defineProperty(exports, "__esModule", { value: true }); +exports.lilconfigSync = exports.lilconfig = exports.defaultLoaders = void 0; +const path = path__default; +const fs = fs__default; +const os = require$$0__default$1; +const fsReadFileAsync = fs.promises.readFile; +function getDefaultSearchPlaces(name) { + return [ + 'package.json', + `.${name}rc.json`, + `.${name}rc.js`, + `${name}.config.js`, + `.${name}rc.cjs`, + `${name}.config.cjs`, + ]; +} +function getSearchPaths(startDir, stopDir) { + return startDir + .split(path.sep) + .reduceRight((acc, _, ind, arr) => { + const currentPath = arr.slice(0, ind + 1).join(path.sep); + if (!acc.passedStopDir) + acc.searchPlaces.push(currentPath || path.sep); + if (currentPath === stopDir) + acc.passedStopDir = true; + return acc; + }, { searchPlaces: [], passedStopDir: false }).searchPlaces; +} +exports.defaultLoaders = Object.freeze({ + '.js': eval('require'), + '.json': eval('require'), + '.cjs': eval('require'), + noExt(_, content) { + return JSON.parse(content); + }, +}); +function getExtDesc(ext) { + return ext === 'noExt' ? 'files without extensions' : `extension "${ext}"`; +} +function getOptions(name, options = {}) { + const conf = { + stopDir: os.homedir(), + searchPlaces: getDefaultSearchPlaces(name), + ignoreEmptySearchPlaces: true, + transform: (x) => x, + packageProp: [name], + ...options, + loaders: { ...exports.defaultLoaders, ...options.loaders }, + }; + conf.searchPlaces.forEach(place => { + const key = path.extname(place) || 'noExt'; + const loader = conf.loaders[key]; + if (!loader) { + throw new Error(`No loader specified for ${getExtDesc(key)}, so searchPlaces item "${place}" is invalid`); + } + if (typeof loader !== 'function') { + throw new Error(`loader for ${getExtDesc(key)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`); + } + }); + return conf; +} +function getPackageProp(props, obj) { + if (typeof props === 'string' && props in obj) + return obj[props]; + return ((Array.isArray(props) ? props : props.split('.')).reduce((acc, prop) => (acc === undefined ? acc : acc[prop]), obj) || null); +} +function getSearchItems(searchPlaces, searchPaths) { + return searchPaths.reduce((acc, searchPath) => { + searchPlaces.forEach(fileName => acc.push({ + fileName, + filepath: path.join(searchPath, fileName), + loaderKey: path.extname(fileName) || 'noExt', + })); + return acc; + }, []); +} +function validateFilePath(filepath) { + if (!filepath) + throw new Error('load must pass a non-empty string'); +} +function validateLoader(loader, ext) { + if (!loader) + throw new Error(`No loader specified for extension "${ext}"`); + if (typeof loader !== 'function') + throw new Error('loader is not a function'); +} +function lilconfig(name, options) { + const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options); + return { + async search(searchFrom = process.cwd()) { + const searchPaths = getSearchPaths(searchFrom, stopDir); + const result = { + config: null, + filepath: '', + }; + const searchItems = getSearchItems(searchPlaces, searchPaths); + for (const { fileName, filepath, loaderKey } of searchItems) { + try { + await fs.promises.access(filepath); + } + catch (_a) { + continue; + } + const content = String(await fsReadFileAsync(filepath)); + const loader = loaders[loaderKey]; + if (fileName === 'package.json') { + const pkg = loader(filepath, content); + const maybeConfig = getPackageProp(packageProp, pkg); + if (maybeConfig != null) { + result.config = maybeConfig; + result.filepath = filepath; + break; + } + continue; + } + const isEmpty = content.trim() === ''; + if (isEmpty && ignoreEmptySearchPlaces) + continue; + if (isEmpty) { + result.isEmpty = true; + result.config = undefined; + } + else { + validateLoader(loader, loaderKey); + result.config = loader(filepath, content); + } + result.filepath = filepath; + break; + } + if (result.filepath === '' && result.config === null) + return transform(null); + return transform(result); + }, + async load(filepath) { + validateFilePath(filepath); + const { base, ext } = path.parse(filepath); + const loaderKey = ext || 'noExt'; + const loader = loaders[loaderKey]; + validateLoader(loader, loaderKey); + const content = String(await fsReadFileAsync(filepath)); + if (base === 'package.json') { + const pkg = await loader(filepath, content); + return transform({ + config: getPackageProp(packageProp, pkg), + filepath, + }); + } + const result = { + config: null, + filepath, + }; + const isEmpty = content.trim() === ''; + if (isEmpty && ignoreEmptySearchPlaces) + return transform({ + config: undefined, + filepath, + isEmpty: true, + }); + result.config = isEmpty + ? undefined + : await loader(filepath, content); + return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result); + }, + }; +} +exports.lilconfig = lilconfig; +function lilconfigSync(name, options) { + const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options); + return { + search(searchFrom = process.cwd()) { + const searchPaths = getSearchPaths(searchFrom, stopDir); + const result = { + config: null, + filepath: '', + }; + const searchItems = getSearchItems(searchPlaces, searchPaths); + for (const { fileName, filepath, loaderKey } of searchItems) { + try { + fs.accessSync(filepath); + } + catch (_a) { + continue; + } + const loader = loaders[loaderKey]; + const content = String(fs.readFileSync(filepath)); + if (fileName === 'package.json') { + const pkg = loader(filepath, content); + const maybeConfig = getPackageProp(packageProp, pkg); + if (maybeConfig != null) { + result.config = maybeConfig; + result.filepath = filepath; + break; + } + continue; + } + const isEmpty = content.trim() === ''; + if (isEmpty && ignoreEmptySearchPlaces) + continue; + if (isEmpty) { + result.isEmpty = true; + result.config = undefined; + } + else { + validateLoader(loader, loaderKey); + result.config = loader(filepath, content); + } + result.filepath = filepath; + break; + } + if (result.filepath === '' && result.config === null) + return transform(null); + return transform(result); + }, + load(filepath) { + validateFilePath(filepath); + const { base, ext } = path.parse(filepath); + const loaderKey = ext || 'noExt'; + const loader = loaders[loaderKey]; + validateLoader(loader, loaderKey); + const content = String(fs.readFileSync(filepath)); + if (base === 'package.json') { + const pkg = loader(filepath, content); + return transform({ + config: getPackageProp(packageProp, pkg), + filepath, + }); + } + const result = { + config: null, + filepath, + }; + const isEmpty = content.trim() === ''; + if (isEmpty && ignoreEmptySearchPlaces) + return transform({ + filepath, + config: undefined, + isEmpty: true, + }); + result.config = isEmpty ? undefined : loader(filepath, content); + return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result); + }, + }; +} +exports.lilconfigSync = lilconfigSync; +}(dist$3)); + +var dist$2 = {}; + +var parseCst$1 = {}; + +var PlainValueEc8e588e = {}; + +const Char = { + ANCHOR: '&', + COMMENT: '#', + TAG: '!', + DIRECTIVES_END: '-', + DOCUMENT_END: '.' +}; +const Type = { + ALIAS: 'ALIAS', + BLANK_LINE: 'BLANK_LINE', + BLOCK_FOLDED: 'BLOCK_FOLDED', + BLOCK_LITERAL: 'BLOCK_LITERAL', + COMMENT: 'COMMENT', + DIRECTIVE: 'DIRECTIVE', + DOCUMENT: 'DOCUMENT', + FLOW_MAP: 'FLOW_MAP', + FLOW_SEQ: 'FLOW_SEQ', + MAP: 'MAP', + MAP_KEY: 'MAP_KEY', + MAP_VALUE: 'MAP_VALUE', + PLAIN: 'PLAIN', + QUOTE_DOUBLE: 'QUOTE_DOUBLE', + QUOTE_SINGLE: 'QUOTE_SINGLE', + SEQ: 'SEQ', + SEQ_ITEM: 'SEQ_ITEM' +}; +const defaultTagPrefix = 'tag:yaml.org,2002:'; +const defaultTags = { + MAP: 'tag:yaml.org,2002:map', + SEQ: 'tag:yaml.org,2002:seq', + STR: 'tag:yaml.org,2002:str' +}; + +function findLineStarts(src) { + const ls = [0]; + let offset = src.indexOf('\n'); + + while (offset !== -1) { + offset += 1; + ls.push(offset); + offset = src.indexOf('\n', offset); + } + + return ls; +} + +function getSrcInfo(cst) { + let lineStarts, src; + + if (typeof cst === 'string') { + lineStarts = findLineStarts(cst); + src = cst; + } else { + if (Array.isArray(cst)) cst = cst[0]; + + if (cst && cst.context) { + if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src); + lineStarts = cst.lineStarts; + src = cst.context.src; + } + } + + return { + lineStarts, + src + }; +} +/** + * @typedef {Object} LinePos - One-indexed position in the source + * @property {number} line + * @property {number} col + */ + +/** + * Determine the line/col position matching a character offset. + * + * Accepts a source string or a CST document as the second parameter. With + * the latter, starting indices for lines are cached in the document as + * `lineStarts: number[]`. + * + * Returns a one-indexed `{ line, col }` location if found, or + * `undefined` otherwise. + * + * @param {number} offset + * @param {string|Document|Document[]} cst + * @returns {?LinePos} + */ + + +function getLinePos(offset, cst) { + if (typeof offset !== 'number' || offset < 0) return null; + const { + lineStarts, + src + } = getSrcInfo(cst); + if (!lineStarts || !src || offset > src.length) return null; + + for (let i = 0; i < lineStarts.length; ++i) { + const start = lineStarts[i]; + + if (offset < start) { + return { + line: i, + col: offset - lineStarts[i - 1] + 1 + }; + } + + if (offset === start) return { + line: i + 1, + col: 1 + }; + } + + const line = lineStarts.length; + return { + line, + col: offset - lineStarts[line - 1] + 1 + }; +} +/** + * Get a specified line from the source. + * + * Accepts a source string or a CST document as the second parameter. With + * the latter, starting indices for lines are cached in the document as + * `lineStarts: number[]`. + * + * Returns the line as a string if found, or `null` otherwise. + * + * @param {number} line One-indexed line number + * @param {string|Document|Document[]} cst + * @returns {?string} + */ + +function getLine(line, cst) { + const { + lineStarts, + src + } = getSrcInfo(cst); + if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null; + const start = lineStarts[line - 1]; + let end = lineStarts[line]; // undefined for last line; that's ok for slice() + + while (end && end > start && src[end - 1] === '\n') --end; + + return src.slice(start, end); +} +/** + * Pretty-print the starting line from the source indicated by the range `pos` + * + * Trims output to `maxWidth` chars while keeping the starting column visible, + * using `…` at either end to indicate dropped characters. + * + * Returns a two-line string (or `null`) with `\n` as separator; the second line + * will hold appropriately indented `^` marks indicating the column range. + * + * @param {Object} pos + * @param {LinePos} pos.start + * @param {LinePos} [pos.end] + * @param {string|Document|Document[]*} cst + * @param {number} [maxWidth=80] + * @returns {?string} + */ + +function getPrettyContext({ + start, + end +}, cst, maxWidth = 80) { + let src = getLine(start.line, cst); + if (!src) return null; + let { + col + } = start; + + if (src.length > maxWidth) { + if (col <= maxWidth - 10) { + src = src.substr(0, maxWidth - 1) + '…'; + } else { + const halfWidth = Math.round(maxWidth / 2); + if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…'; + col -= src.length - maxWidth; + src = '…' + src.substr(1 - maxWidth); + } + } + + let errLen = 1; + let errEnd = ''; + + if (end) { + if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) { + errLen = end.col - start.col; + } else { + errLen = Math.min(src.length + 1, maxWidth) - col; + errEnd = '…'; + } + } + + const offset = col > 1 ? ' '.repeat(col - 1) : ''; + const err = '^'.repeat(errLen); + return `${src}\n${offset}${err}${errEnd}`; +} + +class Range { + static copy(orig) { + return new Range(orig.start, orig.end); + } + + constructor(start, end) { + this.start = start; + this.end = end || start; + } + + isEmpty() { + return typeof this.start !== 'number' || !this.end || this.end <= this.start; + } + /** + * Set `origStart` and `origEnd` to point to the original source range for + * this node, which may differ due to dropped CR characters. + * + * @param {number[]} cr - Positions of dropped CR characters + * @param {number} offset - Starting index of `cr` from the last call + * @returns {number} - The next offset, matching the one found for `origStart` + */ + + + setOrigRange(cr, offset) { + const { + start, + end + } = this; + + if (cr.length === 0 || end <= cr[0]) { + this.origStart = start; + this.origEnd = end; + return offset; + } + + let i = offset; + + while (i < cr.length) { + if (cr[i] > start) break;else ++i; + } + + this.origStart = start + i; + const nextOffset = i; + + while (i < cr.length) { + // if end was at \n, it should now be at \r + if (cr[i] >= end) break;else ++i; + } + + this.origEnd = end + i; + return nextOffset; + } + +} + +/** Root class of all nodes */ + +class Node$2 { + static addStringTerminator(src, offset, str) { + if (str[str.length - 1] === '\n') return str; + const next = Node$2.endOfWhiteSpace(src, offset); + return next >= src.length || src[next] === '\n' ? str + '\n' : str; + } // ^(---|...) + + + static atDocumentBoundary(src, offset, sep) { + const ch0 = src[offset]; + if (!ch0) return true; + const prev = src[offset - 1]; + if (prev && prev !== '\n') return false; + + if (sep) { + if (ch0 !== sep) return false; + } else { + if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false; + } + + const ch1 = src[offset + 1]; + const ch2 = src[offset + 2]; + if (ch1 !== ch0 || ch2 !== ch0) return false; + const ch3 = src[offset + 3]; + return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' '; + } + + static endOfIdentifier(src, offset) { + let ch = src[offset]; + const isVerbatim = ch === '<'; + const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ',']; + + while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1]; + + if (isVerbatim && ch === '>') offset += 1; + return offset; + } + + static endOfIndent(src, offset) { + let ch = src[offset]; + + while (ch === ' ') ch = src[offset += 1]; + + return offset; + } + + static endOfLine(src, offset) { + let ch = src[offset]; + + while (ch && ch !== '\n') ch = src[offset += 1]; + + return offset; + } + + static endOfWhiteSpace(src, offset) { + let ch = src[offset]; + + while (ch === '\t' || ch === ' ') ch = src[offset += 1]; + + return offset; + } + + static startOfLine(src, offset) { + let ch = src[offset - 1]; + if (ch === '\n') return offset; + + while (ch && ch !== '\n') ch = src[offset -= 1]; + + return offset + 1; + } + /** + * End of indentation, or null if the line's indent level is not more + * than `indent` + * + * @param {string} src + * @param {number} indent + * @param {number} lineStart + * @returns {?number} + */ + + + static endOfBlockIndent(src, indent, lineStart) { + const inEnd = Node$2.endOfIndent(src, lineStart); + + if (inEnd > lineStart + indent) { + return inEnd; + } else { + const wsEnd = Node$2.endOfWhiteSpace(src, inEnd); + const ch = src[wsEnd]; + if (!ch || ch === '\n') return wsEnd; + } + + return null; + } + + static atBlank(src, offset, endAsBlank) { + const ch = src[offset]; + return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch; + } + + static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) { + if (!ch || indentDiff < 0) return false; + if (indentDiff > 0) return true; + return indicatorAsIndent && ch === '-'; + } // should be at line or string end, or at next non-whitespace char + + + static normalizeOffset(src, offset) { + const ch = src[offset]; + return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node$2.endOfWhiteSpace(src, offset); + } // fold single newline into space, multiple newlines to N - 1 newlines + // presumes src[offset] === '\n' + + + static foldNewline(src, offset, indent) { + let inCount = 0; + let error = false; + let fold = ''; + let ch = src[offset + 1]; + + while (ch === ' ' || ch === '\t' || ch === '\n') { + switch (ch) { + case '\n': + inCount = 0; + offset += 1; + fold += '\n'; + break; + + case '\t': + if (inCount <= indent) error = true; + offset = Node$2.endOfWhiteSpace(src, offset + 2) - 1; + break; + + case ' ': + inCount += 1; + offset += 1; + break; + } + + ch = src[offset + 1]; + } + + if (!fold) fold = ' '; + if (ch && inCount <= indent) error = true; + return { + fold, + offset, + error + }; + } + + constructor(type, props, context) { + Object.defineProperty(this, 'context', { + value: context || null, + writable: true + }); + this.error = null; + this.range = null; + this.valueRange = null; + this.props = props || []; + this.type = type; + this.value = null; + } + + getPropValue(idx, key, skipKey) { + if (!this.context) return null; + const { + src + } = this.context; + const prop = this.props[idx]; + return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null; + } + + get anchor() { + for (let i = 0; i < this.props.length; ++i) { + const anchor = this.getPropValue(i, Char.ANCHOR, true); + if (anchor != null) return anchor; + } + + return null; + } + + get comment() { + const comments = []; + + for (let i = 0; i < this.props.length; ++i) { + const comment = this.getPropValue(i, Char.COMMENT, true); + if (comment != null) comments.push(comment); + } + + return comments.length > 0 ? comments.join('\n') : null; + } + + commentHasRequiredWhitespace(start) { + const { + src + } = this.context; + if (this.header && start === this.header.end) return false; + if (!this.valueRange) return false; + const { + end + } = this.valueRange; + return start !== end || Node$2.atBlank(src, end - 1); + } + + get hasComment() { + if (this.context) { + const { + src + } = this.context; + + for (let i = 0; i < this.props.length; ++i) { + if (src[this.props[i].start] === Char.COMMENT) return true; + } + } + + return false; + } + + get hasProps() { + if (this.context) { + const { + src + } = this.context; + + for (let i = 0; i < this.props.length; ++i) { + if (src[this.props[i].start] !== Char.COMMENT) return true; + } + } + + return false; + } + + get includesTrailingLines() { + return false; + } + + get jsonLike() { + const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE]; + return jsonLikeTypes.indexOf(this.type) !== -1; + } + + get rangeAsLinePos() { + if (!this.range || !this.context) return undefined; + const start = getLinePos(this.range.start, this.context.root); + if (!start) return undefined; + const end = getLinePos(this.range.end, this.context.root); + return { + start, + end + }; + } + + get rawValue() { + if (!this.valueRange || !this.context) return null; + const { + start, + end + } = this.valueRange; + return this.context.src.slice(start, end); + } + + get tag() { + for (let i = 0; i < this.props.length; ++i) { + const tag = this.getPropValue(i, Char.TAG, false); + + if (tag != null) { + if (tag[1] === '<') { + return { + verbatim: tag.slice(2, -1) + }; + } else { + // eslint-disable-next-line no-unused-vars + const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/); + return { + handle, + suffix + }; + } + } + } + + return null; + } + + get valueRangeContainsNewline() { + if (!this.valueRange || !this.context) return false; + const { + start, + end + } = this.valueRange; + const { + src + } = this.context; + + for (let i = start; i < end; ++i) { + if (src[i] === '\n') return true; + } + + return false; + } + + parseComment(start) { + const { + src + } = this.context; + + if (src[start] === Char.COMMENT) { + const end = Node$2.endOfLine(src, start + 1); + const commentRange = new Range(start, end); + this.props.push(commentRange); + return end; + } + + return start; + } + /** + * Populates the `origStart` and `origEnd` values of all ranges for this + * node. Extended by child classes to handle descendant nodes. + * + * @param {number[]} cr - Positions of dropped CR characters + * @param {number} offset - Starting index of `cr` from the last call + * @returns {number} - The next offset, matching the one found for `origStart` + */ + + + setOrigRanges(cr, offset) { + if (this.range) offset = this.range.setOrigRange(cr, offset); + if (this.valueRange) this.valueRange.setOrigRange(cr, offset); + this.props.forEach(prop => prop.setOrigRange(cr, offset)); + return offset; + } + + toString() { + const { + context: { + src + }, + range, + value + } = this; + if (value != null) return value; + const str = src.slice(range.start, range.end); + return Node$2.addStringTerminator(src, range.end, str); + } + +} + +class YAMLError extends Error { + constructor(name, source, message) { + if (!message || !(source instanceof Node$2)) throw new Error(`Invalid arguments for new ${name}`); + super(); + this.name = name; + this.message = message; + this.source = source; + } + + makePretty() { + if (!this.source) return; + this.nodeType = this.source.type; + const cst = this.source.context && this.source.context.root; + + if (typeof this.offset === 'number') { + this.range = new Range(this.offset, this.offset + 1); + const start = cst && getLinePos(this.offset, cst); + + if (start) { + const end = { + line: start.line, + col: start.col + 1 + }; + this.linePos = { + start, + end + }; + } + + delete this.offset; + } else { + this.range = this.source.range; + this.linePos = this.source.rangeAsLinePos; + } + + if (this.linePos) { + const { + line, + col + } = this.linePos.start; + this.message += ` at line ${line}, column ${col}`; + const ctx = cst && getPrettyContext(this.linePos, cst); + if (ctx) this.message += `:\n\n${ctx}\n`; + } + + delete this.source; + } + +} +class YAMLReferenceError extends YAMLError { + constructor(source, message) { + super('YAMLReferenceError', source, message); + } + +} +class YAMLSemanticError extends YAMLError { + constructor(source, message) { + super('YAMLSemanticError', source, message); + } + +} +class YAMLSyntaxError extends YAMLError { + constructor(source, message) { + super('YAMLSyntaxError', source, message); + } + +} +class YAMLWarning extends YAMLError { + constructor(source, message) { + super('YAMLWarning', source, message); + } + +} + +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; +} + +class PlainValue$6 extends Node$2 { + static endOfLine(src, start, inFlow) { + let ch = src[start]; + let offset = start; + + while (ch && ch !== '\n') { + if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break; + const next = src[offset + 1]; + if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break; + if ((ch === ' ' || ch === '\t') && next === '#') break; + offset += 1; + ch = next; + } + + return offset; + } + + get strValue() { + if (!this.valueRange || !this.context) return null; + let { + start, + end + } = this.valueRange; + const { + src + } = this.context; + let ch = src[end - 1]; + + while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1]; + + let str = ''; + + for (let i = start; i < end; ++i) { + const ch = src[i]; + + if (ch === '\n') { + const { + fold, + offset + } = Node$2.foldNewline(src, i, -1); + str += fold; + i = offset; + } else if (ch === ' ' || ch === '\t') { + // trim trailing whitespace + const wsStart = i; + let next = src[i + 1]; + + while (i < end && (next === ' ' || next === '\t')) { + i += 1; + next = src[i + 1]; + } + + if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; + } else { + str += ch; + } + } + + const ch0 = src[start]; + + switch (ch0) { + case '\t': + { + const msg = 'Plain value cannot start with a tab character'; + const errors = [new YAMLSemanticError(this, msg)]; + return { + errors, + str + }; + } + + case '@': + case '`': + { + const msg = `Plain value cannot start with reserved character ${ch0}`; + const errors = [new YAMLSemanticError(this, msg)]; + return { + errors, + str + }; + } + + default: + return str; + } + } + + parseBlockValue(start) { + const { + indent, + inFlow, + src + } = this.context; + let offset = start; + let valueEnd = start; + + for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { + if (Node$2.atDocumentBoundary(src, offset + 1)) break; + const end = Node$2.endOfBlockIndent(src, indent, offset + 1); + if (end === null || src[end] === '#') break; + + if (src[end] === '\n') { + offset = end; + } else { + valueEnd = PlainValue$6.endOfLine(src, end, inFlow); + offset = valueEnd; + } + } + + if (this.valueRange.isEmpty()) this.valueRange.start = start; + this.valueRange.end = valueEnd; + return valueEnd; + } + /** + * Parses a plain value from the source + * + * Accepted forms are: + * ``` + * #comment + * + * first line + * + * first line #comment + * + * first line + * block + * lines + * + * #comment + * block + * lines + * ``` + * where block lines are empty or have an indent level greater than `indent`. + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar, may be `\n` + */ + + + parse(context, start) { + this.context = context; + const { + inFlow, + src + } = context; + let offset = start; + const ch = src[offset]; + + if (ch && ch !== '#' && ch !== '\n') { + offset = PlainValue$6.endOfLine(src, start, inFlow); + } + + this.valueRange = new Range(start, offset); + offset = Node$2.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + + if (!this.hasComment || this.valueRange.isEmpty()) { + offset = this.parseBlockValue(offset); + } + + return offset; + } + +} + +PlainValueEc8e588e.Char = Char; +PlainValueEc8e588e.Node = Node$2; +PlainValueEc8e588e.PlainValue = PlainValue$6; +PlainValueEc8e588e.Range = Range; +PlainValueEc8e588e.Type = Type; +PlainValueEc8e588e.YAMLError = YAMLError; +PlainValueEc8e588e.YAMLReferenceError = YAMLReferenceError; +PlainValueEc8e588e.YAMLSemanticError = YAMLSemanticError; +PlainValueEc8e588e.YAMLSyntaxError = YAMLSyntaxError; +PlainValueEc8e588e.YAMLWarning = YAMLWarning; +PlainValueEc8e588e._defineProperty = _defineProperty; +PlainValueEc8e588e.defaultTagPrefix = defaultTagPrefix; +PlainValueEc8e588e.defaultTags = defaultTags; + +var PlainValue$5 = PlainValueEc8e588e; + +class BlankLine extends PlainValue$5.Node { + constructor() { + super(PlainValue$5.Type.BLANK_LINE); + } + /* istanbul ignore next */ + + + get includesTrailingLines() { + // This is never called from anywhere, but if it were, + // this is the value it should return. + return true; + } + /** + * Parses a blank line from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first \n character + * @returns {number} - Index of the character after this + */ + + + parse(context, start) { + this.context = context; + this.range = new PlainValue$5.Range(start, start + 1); + return start + 1; + } + +} + +class CollectionItem extends PlainValue$5.Node { + constructor(type, props) { + super(type, props); + this.node = null; + } + + get includesTrailingLines() { + return !!this.node && this.node.includesTrailingLines; + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + + parse(context, start) { + this.context = context; + const { + parseNode, + src + } = context; + let { + atLineStart, + lineStart + } = context; + if (!atLineStart && this.type === PlainValue$5.Type.SEQ_ITEM) this.error = new PlainValue$5.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line'); + const indent = atLineStart ? start - lineStart : context.indent; + let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1); + let ch = src[offset]; + const inlineComment = ch === '#'; + const comments = []; + let blankLine = null; + + while (ch === '\n' || ch === '#') { + if (ch === '#') { + const end = PlainValue$5.Node.endOfLine(src, offset + 1); + comments.push(new PlainValue$5.Range(offset, end)); + offset = end; + } else { + atLineStart = true; + lineStart = offset + 1; + const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); + + if (src[wsEnd] === '\n' && comments.length === 0) { + blankLine = new BlankLine(); + lineStart = blankLine.parse({ + src + }, lineStart); + } + + offset = PlainValue$5.Node.endOfIndent(src, lineStart); + } + + ch = src[offset]; + } + + if (PlainValue$5.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValue$5.Type.SEQ_ITEM)) { + this.node = parseNode({ + atLineStart, + inCollection: false, + indent, + lineStart, + parent: this + }, offset); + } else if (ch && lineStart > start + 1) { + offset = lineStart - 1; + } + + if (this.node) { + if (blankLine) { + // Only blank lines preceding non-empty nodes are captured. Note that + // this means that collection item range start indices do not always + // increase monotonically. -- eemeli/yaml#126 + const items = context.parent.items || context.parent.contents; + if (items) items.push(blankLine); + } + + if (comments.length) Array.prototype.push.apply(this.props, comments); + offset = this.node.range.end; + } else { + if (inlineComment) { + const c = comments[0]; + this.props.push(c); + offset = c.end; + } else { + offset = PlainValue$5.Node.endOfLine(src, start + 1); + } + } + + const end = this.node ? this.node.valueRange.end : offset; + this.valueRange = new PlainValue$5.Range(start, end); + return offset; + } + + setOrigRanges(cr, offset) { + offset = super.setOrigRanges(cr, offset); + return this.node ? this.node.setOrigRanges(cr, offset) : offset; + } + + toString() { + const { + context: { + src + }, + node, + range, + value + } = this; + if (value != null) return value; + const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end); + return PlainValue$5.Node.addStringTerminator(src, range.end, str); + } + +} + +class Comment extends PlainValue$5.Node { + constructor() { + super(PlainValue$5.Type.COMMENT); + } + /** + * Parses a comment line from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + + + parse(context, start) { + this.context = context; + const offset = this.parseComment(start); + this.range = new PlainValue$5.Range(start, offset); + return offset; + } + +} + +function grabCollectionEndComments(node) { + let cnode = node; + + while (cnode instanceof CollectionItem) cnode = cnode.node; + + if (!(cnode instanceof Collection$1)) return null; + const len = cnode.items.length; + let ci = -1; + + for (let i = len - 1; i >= 0; --i) { + const n = cnode.items[i]; + + if (n.type === PlainValue$5.Type.COMMENT) { + // Keep sufficiently indented comments with preceding node + const { + indent, + lineStart + } = n.context; + if (indent > 0 && n.range.start >= lineStart + indent) break; + ci = i; + } else if (n.type === PlainValue$5.Type.BLANK_LINE) ci = i;else break; + } + + if (ci === -1) return null; + const ca = cnode.items.splice(ci, len - ci); + const prevEnd = ca[0].range.start; + + while (true) { + cnode.range.end = prevEnd; + if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd; + if (cnode === node) break; + cnode = cnode.context.parent; + } + + return ca; +} +class Collection$1 extends PlainValue$5.Node { + static nextContentHasIndent(src, offset, indent) { + const lineStart = PlainValue$5.Node.endOfLine(src, offset) + 1; + offset = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); + const ch = src[offset]; + if (!ch) return false; + if (offset >= lineStart + indent) return true; + if (ch !== '#' && ch !== '\n') return false; + return Collection$1.nextContentHasIndent(src, offset, indent); + } + + constructor(firstItem) { + super(firstItem.type === PlainValue$5.Type.SEQ_ITEM ? PlainValue$5.Type.SEQ : PlainValue$5.Type.MAP); + + for (let i = firstItem.props.length - 1; i >= 0; --i) { + if (firstItem.props[i].start < firstItem.context.lineStart) { + // props on previous line are assumed by the collection + this.props = firstItem.props.slice(0, i + 1); + firstItem.props = firstItem.props.slice(i + 1); + const itemRange = firstItem.props[0] || firstItem.valueRange; + firstItem.range.start = itemRange.start; + break; + } + } + + this.items = [firstItem]; + const ec = grabCollectionEndComments(firstItem); + if (ec) Array.prototype.push.apply(this.items, ec); + } + + get includesTrailingLines() { + return this.items.length > 0; + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + + parse(context, start) { + this.context = context; + const { + parseNode, + src + } = context; // It's easier to recalculate lineStart here rather than tracking down the + // last context from which to read it -- eemeli/yaml#2 + + let lineStart = PlainValue$5.Node.startOfLine(src, start); + const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling + // -- eemeli/yaml#17 + + firstItem.context.parent = this; + this.valueRange = PlainValue$5.Range.copy(firstItem.valueRange); + const indent = firstItem.range.start - firstItem.context.lineStart; + let offset = start; + offset = PlainValue$5.Node.normalizeOffset(src, offset); + let ch = src[offset]; + let atLineStart = PlainValue$5.Node.endOfWhiteSpace(src, lineStart) === offset; + let prevIncludesTrailingLines = false; + + while (ch) { + while (ch === '\n' || ch === '#') { + if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) { + const blankLine = new BlankLine(); + offset = blankLine.parse({ + src + }, offset); + this.valueRange.end = offset; + + if (offset >= src.length) { + ch = null; + break; + } + + this.items.push(blankLine); + offset -= 1; // blankLine.parse() consumes terminal newline + } else if (ch === '#') { + if (offset < lineStart + indent && !Collection$1.nextContentHasIndent(src, offset, indent)) { + return offset; + } + + const comment = new Comment(); + offset = comment.parse({ + indent, + lineStart, + src + }, offset); + this.items.push(comment); + this.valueRange.end = offset; + + if (offset >= src.length) { + ch = null; + break; + } + } + + lineStart = offset + 1; + offset = PlainValue$5.Node.endOfIndent(src, lineStart); + + if (PlainValue$5.Node.atBlank(src, offset)) { + const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, offset); + const next = src[wsEnd]; + + if (!next || next === '\n' || next === '#') { + offset = wsEnd; + } + } + + ch = src[offset]; + atLineStart = true; + } + + if (!ch) { + break; + } + + if (offset !== lineStart + indent && (atLineStart || ch !== ':')) { + if (offset < lineStart + indent) { + if (lineStart > start) offset = lineStart; + break; + } else if (!this.error) { + const msg = 'All collection items must start at the same column'; + this.error = new PlainValue$5.YAMLSyntaxError(this, msg); + } + } + + if (firstItem.type === PlainValue$5.Type.SEQ_ITEM) { + if (ch !== '-') { + if (lineStart > start) offset = lineStart; + break; + } + } else if (ch === '-' && !this.error) { + // map key may start with -, as long as it's followed by a non-whitespace char + const next = src[offset + 1]; + + if (!next || next === '\n' || next === '\t' || next === ' ') { + const msg = 'A collection cannot be both a mapping and a sequence'; + this.error = new PlainValue$5.YAMLSyntaxError(this, msg); + } + } + + const node = parseNode({ + atLineStart, + inCollection: true, + indent, + lineStart, + parent: this + }, offset); + if (!node) return offset; // at next document start + + this.items.push(node); + this.valueRange.end = node.valueRange.end; + offset = PlainValue$5.Node.normalizeOffset(src, node.range.end); + ch = src[offset]; + atLineStart = false; + prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range + // has advanced to check the current line's indentation level + // -- eemeli/yaml#10 & eemeli/yaml#38 + + if (ch) { + let ls = offset - 1; + let prev = src[ls]; + + while (prev === ' ' || prev === '\t') prev = src[--ls]; + + if (prev === '\n') { + lineStart = ls + 1; + atLineStart = true; + } + } + + const ec = grabCollectionEndComments(node); + if (ec) Array.prototype.push.apply(this.items, ec); + } + + return offset; + } + + setOrigRanges(cr, offset) { + offset = super.setOrigRanges(cr, offset); + this.items.forEach(node => { + offset = node.setOrigRanges(cr, offset); + }); + return offset; + } + + toString() { + const { + context: { + src + }, + items, + range, + value + } = this; + if (value != null) return value; + let str = src.slice(range.start, items[0].range.start) + String(items[0]); + + for (let i = 1; i < items.length; ++i) { + const item = items[i]; + const { + atLineStart, + indent + } = item.context; + if (atLineStart) for (let i = 0; i < indent; ++i) str += ' '; + str += String(item); + } + + return PlainValue$5.Node.addStringTerminator(src, range.end, str); + } + +} + +class Directive extends PlainValue$5.Node { + constructor() { + super(PlainValue$5.Type.DIRECTIVE); + this.name = null; + } + + get parameters() { + const raw = this.rawValue; + return raw ? raw.trim().split(/[ \t]+/) : []; + } + + parseName(start) { + const { + src + } = this.context; + let offset = start; + let ch = src[offset]; + + while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1]; + + this.name = src.slice(start, offset); + return offset; + } + + parseParameters(start) { + const { + src + } = this.context; + let offset = start; + let ch = src[offset]; + + while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1]; + + this.valueRange = new PlainValue$5.Range(start, offset); + return offset; + } + + parse(context, start) { + this.context = context; + let offset = this.parseName(start + 1); + offset = this.parseParameters(offset); + offset = this.parseComment(offset); + this.range = new PlainValue$5.Range(start, offset); + return offset; + } + +} + +class Document$3 extends PlainValue$5.Node { + static startCommentOrEndBlankLine(src, start) { + const offset = PlainValue$5.Node.endOfWhiteSpace(src, start); + const ch = src[offset]; + return ch === '#' || ch === '\n' ? offset : start; + } + + constructor() { + super(PlainValue$5.Type.DOCUMENT); + this.directives = null; + this.contents = null; + this.directivesEndMarker = null; + this.documentEndMarker = null; + } + + parseDirectives(start) { + const { + src + } = this.context; + this.directives = []; + let atLineStart = true; + let hasDirectives = false; + let offset = start; + + while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DIRECTIVES_END)) { + offset = Document$3.startCommentOrEndBlankLine(src, offset); + + switch (src[offset]) { + case '\n': + if (atLineStart) { + const blankLine = new BlankLine(); + offset = blankLine.parse({ + src + }, offset); + + if (offset < src.length) { + this.directives.push(blankLine); + } + } else { + offset += 1; + atLineStart = true; + } + + break; + + case '#': + { + const comment = new Comment(); + offset = comment.parse({ + src + }, offset); + this.directives.push(comment); + atLineStart = false; + } + break; + + case '%': + { + const directive = new Directive(); + offset = directive.parse({ + parent: this, + src + }, offset); + this.directives.push(directive); + hasDirectives = true; + atLineStart = false; + } + break; + + default: + if (hasDirectives) { + this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line'); + } else if (this.directives.length > 0) { + this.contents = this.directives; + this.directives = []; + } + + return offset; + } + } + + if (src[offset]) { + this.directivesEndMarker = new PlainValue$5.Range(offset, offset + 3); + return offset + 3; + } + + if (hasDirectives) { + this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line'); + } else if (this.directives.length > 0) { + this.contents = this.directives; + this.directives = []; + } + + return offset; + } + + parseContents(start) { + const { + parseNode, + src + } = this.context; + if (!this.contents) this.contents = []; + let lineStart = start; + + while (src[lineStart - 1] === '-') lineStart -= 1; + + let offset = PlainValue$5.Node.endOfWhiteSpace(src, start); + let atLineStart = lineStart === start; + this.valueRange = new PlainValue$5.Range(offset); + + while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DOCUMENT_END)) { + switch (src[offset]) { + case '\n': + if (atLineStart) { + const blankLine = new BlankLine(); + offset = blankLine.parse({ + src + }, offset); + + if (offset < src.length) { + this.contents.push(blankLine); + } + } else { + offset += 1; + atLineStart = true; + } + + lineStart = offset; + break; + + case '#': + { + const comment = new Comment(); + offset = comment.parse({ + src + }, offset); + this.contents.push(comment); + atLineStart = false; + } + break; + + default: + { + const iEnd = PlainValue$5.Node.endOfIndent(src, offset); + const context = { + atLineStart, + indent: -1, + inFlow: false, + inCollection: false, + lineStart, + parent: this + }; + const node = parseNode(context, iEnd); + if (!node) return this.valueRange.end = iEnd; // at next document start + + this.contents.push(node); + offset = node.range.end; + atLineStart = false; + const ec = grabCollectionEndComments(node); + if (ec) Array.prototype.push.apply(this.contents, ec); + } + } + + offset = Document$3.startCommentOrEndBlankLine(src, offset); + } + + this.valueRange.end = offset; + + if (src[offset]) { + this.documentEndMarker = new PlainValue$5.Range(offset, offset + 3); + offset += 3; + + if (src[offset]) { + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + + if (src[offset] === '#') { + const comment = new Comment(); + offset = comment.parse({ + src + }, offset); + this.contents.push(comment); + } + + switch (src[offset]) { + case '\n': + offset += 1; + break; + + case undefined: + break; + + default: + this.error = new PlainValue$5.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix'); + } + } + } + + return offset; + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + + parse(context, start) { + context.root = this; + this.context = context; + const { + src + } = context; + let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM + + offset = this.parseDirectives(offset); + offset = this.parseContents(offset); + return offset; + } + + setOrigRanges(cr, offset) { + offset = super.setOrigRanges(cr, offset); + this.directives.forEach(node => { + offset = node.setOrigRanges(cr, offset); + }); + if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset); + this.contents.forEach(node => { + offset = node.setOrigRanges(cr, offset); + }); + if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset); + return offset; + } + + toString() { + const { + contents, + directives, + value + } = this; + if (value != null) return value; + let str = directives.join(''); + + if (contents.length > 0) { + if (directives.length > 0 || contents[0].type === PlainValue$5.Type.COMMENT) str += '---\n'; + str += contents.join(''); + } + + if (str[str.length - 1] !== '\n') str += '\n'; + return str; + } + +} + +class Alias$1 extends PlainValue$5.Node { + /** + * Parses an *alias from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + parse(context, start) { + this.context = context; + const { + src + } = context; + let offset = PlainValue$5.Node.endOfIdentifier(src, start + 1); + this.valueRange = new PlainValue$5.Range(start + 1, offset); + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + return offset; + } + +} + +const Chomp = { + CLIP: 'CLIP', + KEEP: 'KEEP', + STRIP: 'STRIP' +}; +class BlockValue extends PlainValue$5.Node { + constructor(type, props) { + super(type, props); + this.blockIndent = null; + this.chomping = Chomp.CLIP; + this.header = null; + } + + get includesTrailingLines() { + return this.chomping === Chomp.KEEP; + } + + get strValue() { + if (!this.valueRange || !this.context) return null; + let { + start, + end + } = this.valueRange; + const { + indent, + src + } = this.context; + if (this.valueRange.isEmpty()) return ''; + let lastNewLine = null; + let ch = src[end - 1]; + + while (ch === '\n' || ch === '\t' || ch === ' ') { + end -= 1; + + if (end <= start) { + if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens + } + + if (ch === '\n') lastNewLine = end; + ch = src[end - 1]; + } + + let keepStart = end + 1; + + if (lastNewLine) { + if (this.chomping === Chomp.KEEP) { + keepStart = lastNewLine; + end = this.valueRange.end; + } else { + end = lastNewLine; + } + } + + const bi = indent + this.blockIndent; + const folded = this.type === PlainValue$5.Type.BLOCK_FOLDED; + let atStart = true; + let str = ''; + let sep = ''; + let prevMoreIndented = false; + + for (let i = start; i < end; ++i) { + for (let j = 0; j < bi; ++j) { + if (src[i] !== ' ') break; + i += 1; + } + + const ch = src[i]; + + if (ch === '\n') { + if (sep === '\n') str += '\n';else sep = '\n'; + } else { + const lineEnd = PlainValue$5.Node.endOfLine(src, i); + const line = src.slice(i, lineEnd); + i = lineEnd; + + if (folded && (ch === ' ' || ch === '\t') && i < keepStart) { + if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n'; + str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '') + + sep = lineEnd < end && src[lineEnd] || ''; + prevMoreIndented = true; + } else { + str += sep + line; + sep = folded && i < keepStart ? ' ' : '\n'; + prevMoreIndented = false; + } + + if (atStart && line !== '') atStart = false; + } + } + + return this.chomping === Chomp.STRIP ? str : str + '\n'; + } + + parseBlockHeader(start) { + const { + src + } = this.context; + let offset = start + 1; + let bi = ''; + + while (true) { + const ch = src[offset]; + + switch (ch) { + case '-': + this.chomping = Chomp.STRIP; + break; + + case '+': + this.chomping = Chomp.KEEP; + break; + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + bi += ch; + break; + + default: + this.blockIndent = Number(bi) || null; + this.header = new PlainValue$5.Range(start, offset); + return offset; + } + + offset += 1; + } + } + + parseBlockValue(start) { + const { + indent, + src + } = this.context; + const explicit = !!this.blockIndent; + let offset = start; + let valueEnd = start; + let minBlockIndent = 1; + + for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { + offset += 1; + if (PlainValue$5.Node.atDocumentBoundary(src, offset)) break; + const end = PlainValue$5.Node.endOfBlockIndent(src, indent, offset); // should not include tab? + + if (end === null) break; + const ch = src[end]; + const lineIndent = end - (offset + indent); + + if (!this.blockIndent) { + // no explicit block indent, none yet detected + if (src[end] !== '\n') { + // first line with non-whitespace content + if (lineIndent < minBlockIndent) { + const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator'; + this.error = new PlainValue$5.YAMLSemanticError(this, msg); + } + + this.blockIndent = lineIndent; + } else if (lineIndent > minBlockIndent) { + // empty line with more whitespace + minBlockIndent = lineIndent; + } + } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) { + if (src[end] === '#') break; + + if (!this.error) { + const src = explicit ? 'explicit indentation indicator' : 'first line'; + const msg = `Block scalars must not be less indented than their ${src}`; + this.error = new PlainValue$5.YAMLSemanticError(this, msg); + } + } + + if (src[end] === '\n') { + offset = end; + } else { + offset = valueEnd = PlainValue$5.Node.endOfLine(src, end); + } + } + + if (this.chomping !== Chomp.KEEP) { + offset = src[valueEnd] ? valueEnd + 1 : valueEnd; + } + + this.valueRange = new PlainValue$5.Range(start + 1, offset); + return offset; + } + /** + * Parses a block value from the source + * + * Accepted forms are: + * ``` + * BS + * block + * lines + * + * BS #comment + * block + * lines + * ``` + * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines + * are empty or have an indent level greater than `indent`. + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this block + */ + + + parse(context, start) { + this.context = context; + const { + src + } = context; + let offset = this.parseBlockHeader(start); + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + offset = this.parseBlockValue(offset); + return offset; + } + + setOrigRanges(cr, offset) { + offset = super.setOrigRanges(cr, offset); + return this.header ? this.header.setOrigRange(cr, offset) : offset; + } + +} + +class FlowCollection extends PlainValue$5.Node { + constructor(type, props) { + super(type, props); + this.items = null; + } + + prevNodeIsJsonLike(idx = this.items.length) { + const node = this.items[idx - 1]; + return !!node && (node.jsonLike || node.type === PlainValue$5.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1)); + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + + parse(context, start) { + this.context = context; + const { + parseNode, + src + } = context; + let { + indent, + lineStart + } = context; + let char = src[start]; // { or [ + + this.items = [{ + char, + offset: start + }]; + let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1); + char = src[offset]; + + while (char && char !== ']' && char !== '}') { + switch (char) { + case '\n': + { + lineStart = offset + 1; + const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); + + if (src[wsEnd] === '\n') { + const blankLine = new BlankLine(); + lineStart = blankLine.parse({ + src + }, lineStart); + this.items.push(blankLine); + } + + offset = PlainValue$5.Node.endOfIndent(src, lineStart); + + if (offset <= lineStart + indent) { + char = src[offset]; + + if (offset < lineStart + indent || char !== ']' && char !== '}') { + const msg = 'Insufficient indentation in flow collection'; + this.error = new PlainValue$5.YAMLSemanticError(this, msg); + } + } + } + break; + + case ',': + { + this.items.push({ + char, + offset + }); + offset += 1; + } + break; + + case '#': + { + const comment = new Comment(); + offset = comment.parse({ + src + }, offset); + this.items.push(comment); + } + break; + + case '?': + case ':': + { + const next = src[offset + 1]; + + if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace + char === ':' && this.prevNodeIsJsonLike()) { + this.items.push({ + char, + offset + }); + offset += 1; + break; + } + } + // fallthrough + + default: + { + const node = parseNode({ + atLineStart: false, + inCollection: false, + inFlow: true, + indent: -1, + lineStart, + parent: this + }, offset); + + if (!node) { + // at next document start + this.valueRange = new PlainValue$5.Range(start, offset); + return offset; + } + + this.items.push(node); + offset = PlainValue$5.Node.normalizeOffset(src, node.range.end); + } + } + + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + char = src[offset]; + } + + this.valueRange = new PlainValue$5.Range(start, offset + 1); + + if (char) { + this.items.push({ + char, + offset + }); + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset + 1); + offset = this.parseComment(offset); + } + + return offset; + } + + setOrigRanges(cr, offset) { + offset = super.setOrigRanges(cr, offset); + this.items.forEach(node => { + if (node instanceof PlainValue$5.Node) { + offset = node.setOrigRanges(cr, offset); + } else if (cr.length === 0) { + node.origOffset = node.offset; + } else { + let i = offset; + + while (i < cr.length) { + if (cr[i] > node.offset) break;else ++i; + } + + node.origOffset = node.offset + i; + offset = i; + } + }); + return offset; + } + + toString() { + const { + context: { + src + }, + items, + range, + value + } = this; + if (value != null) return value; + const nodes = items.filter(item => item instanceof PlainValue$5.Node); + let str = ''; + let prevEnd = range.start; + nodes.forEach(node => { + const prefix = src.slice(prevEnd, node.range.start); + prevEnd = node.range.end; + str += prefix + String(node); + + if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') { + // Comment range does not include the terminal newline, but its + // stringified value does. Without this fix, newlines at comment ends + // get duplicated. + prevEnd += 1; + } + }); + str += src.slice(prevEnd, range.end); + return PlainValue$5.Node.addStringTerminator(src, range.end, str); + } + +} + +class QuoteDouble extends PlainValue$5.Node { + static endOfQuote(src, offset) { + let ch = src[offset]; + + while (ch && ch !== '"') { + offset += ch === '\\' ? 2 : 1; + ch = src[offset]; + } + + return offset + 1; + } + /** + * @returns {string | { str: string, errors: YAMLSyntaxError[] }} + */ + + + get strValue() { + if (!this.valueRange || !this.context) return null; + const errors = []; + const { + start, + end + } = this.valueRange; + const { + indent, + src + } = this.context; + if (src[end - 1] !== '"') errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by + // escaped backslashes; also, this should be faster. + + let str = ''; + + for (let i = start + 1; i < end - 1; ++i) { + const ch = src[i]; + + if (ch === '\n') { + if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); + const { + fold, + offset, + error + } = PlainValue$5.Node.foldNewline(src, i, indent); + str += fold; + i = offset; + if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented')); + } else if (ch === '\\') { + i += 1; + + switch (src[i]) { + case '0': + str += '\0'; + break; + // null character + + case 'a': + str += '\x07'; + break; + // bell character + + case 'b': + str += '\b'; + break; + // backspace + + case 'e': + str += '\x1b'; + break; + // escape character + + case 'f': + str += '\f'; + break; + // form feed + + case 'n': + str += '\n'; + break; + // line feed + + case 'r': + str += '\r'; + break; + // carriage return + + case 't': + str += '\t'; + break; + // horizontal tab + + case 'v': + str += '\v'; + break; + // vertical tab + + case 'N': + str += '\u0085'; + break; + // Unicode next line + + case '_': + str += '\u00a0'; + break; + // Unicode non-breaking space + + case 'L': + str += '\u2028'; + break; + // Unicode line separator + + case 'P': + str += '\u2029'; + break; + // Unicode paragraph separator + + case ' ': + str += ' '; + break; + + case '"': + str += '"'; + break; + + case '/': + str += '/'; + break; + + case '\\': + str += '\\'; + break; + + case '\t': + str += '\t'; + break; + + case 'x': + str += this.parseCharCode(i + 1, 2, errors); + i += 2; + break; + + case 'u': + str += this.parseCharCode(i + 1, 4, errors); + i += 4; + break; + + case 'U': + str += this.parseCharCode(i + 1, 8, errors); + i += 8; + break; + + case '\n': + // skip escaped newlines, but still trim the following line + while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1; + + break; + + default: + errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`)); + str += '\\' + src[i]; + } + } else if (ch === ' ' || ch === '\t') { + // trim trailing whitespace + const wsStart = i; + let next = src[i + 1]; + + while (next === ' ' || next === '\t') { + i += 1; + next = src[i + 1]; + } + + if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; + } else { + str += ch; + } + } + + return errors.length > 0 ? { + errors, + str + } : str; + } + + parseCharCode(offset, length, errors) { + const { + src + } = this.context; + const cc = src.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + + if (isNaN(code)) { + errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`)); + return src.substr(offset - 2, length + 2); + } + + return String.fromCodePoint(code); + } + /** + * Parses a "double quoted" value from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + + + parse(context, start) { + this.context = context; + const { + src + } = context; + let offset = QuoteDouble.endOfQuote(src, start + 1); + this.valueRange = new PlainValue$5.Range(start, offset); + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + return offset; + } + +} + +class QuoteSingle extends PlainValue$5.Node { + static endOfQuote(src, offset) { + let ch = src[offset]; + + while (ch) { + if (ch === "'") { + if (src[offset + 1] !== "'") break; + ch = src[offset += 2]; + } else { + ch = src[offset += 1]; + } + } + + return offset + 1; + } + /** + * @returns {string | { str: string, errors: YAMLSyntaxError[] }} + */ + + + get strValue() { + if (!this.valueRange || !this.context) return null; + const errors = []; + const { + start, + end + } = this.valueRange; + const { + indent, + src + } = this.context; + if (src[end - 1] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, "Missing closing 'quote")); + let str = ''; + + for (let i = start + 1; i < end - 1; ++i) { + const ch = src[i]; + + if (ch === '\n') { + if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); + const { + fold, + offset, + error + } = PlainValue$5.Node.foldNewline(src, i, indent); + str += fold; + i = offset; + if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented')); + } else if (ch === "'") { + str += ch; + i += 1; + if (src[i] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.')); + } else if (ch === ' ' || ch === '\t') { + // trim trailing whitespace + const wsStart = i; + let next = src[i + 1]; + + while (next === ' ' || next === '\t') { + i += 1; + next = src[i + 1]; + } + + if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; + } else { + str += ch; + } + } + + return errors.length > 0 ? { + errors, + str + } : str; + } + /** + * Parses a 'single quoted' value from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + + + parse(context, start) { + this.context = context; + const { + src + } = context; + let offset = QuoteSingle.endOfQuote(src, start + 1); + this.valueRange = new PlainValue$5.Range(start, offset); + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + return offset; + } + +} + +function createNewNode(type, props) { + switch (type) { + case PlainValue$5.Type.ALIAS: + return new Alias$1(type, props); + + case PlainValue$5.Type.BLOCK_FOLDED: + case PlainValue$5.Type.BLOCK_LITERAL: + return new BlockValue(type, props); + + case PlainValue$5.Type.FLOW_MAP: + case PlainValue$5.Type.FLOW_SEQ: + return new FlowCollection(type, props); + + case PlainValue$5.Type.MAP_KEY: + case PlainValue$5.Type.MAP_VALUE: + case PlainValue$5.Type.SEQ_ITEM: + return new CollectionItem(type, props); + + case PlainValue$5.Type.COMMENT: + case PlainValue$5.Type.PLAIN: + return new PlainValue$5.PlainValue(type, props); + + case PlainValue$5.Type.QUOTE_DOUBLE: + return new QuoteDouble(type, props); + + case PlainValue$5.Type.QUOTE_SINGLE: + return new QuoteSingle(type, props); + + /* istanbul ignore next */ + + default: + return null; + // should never happen + } +} +/** + * @param {boolean} atLineStart - Node starts at beginning of line + * @param {boolean} inFlow - true if currently in a flow context + * @param {boolean} inCollection - true if currently in a collection context + * @param {number} indent - Current level of indentation + * @param {number} lineStart - Start of the current line + * @param {Node} parent - The parent of the node + * @param {string} src - Source of the YAML document + */ + + +class ParseContext { + static parseType(src, offset, inFlow) { + switch (src[offset]) { + case '*': + return PlainValue$5.Type.ALIAS; + + case '>': + return PlainValue$5.Type.BLOCK_FOLDED; + + case '|': + return PlainValue$5.Type.BLOCK_LITERAL; + + case '{': + return PlainValue$5.Type.FLOW_MAP; + + case '[': + return PlainValue$5.Type.FLOW_SEQ; + + case '?': + return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_KEY : PlainValue$5.Type.PLAIN; + + case ':': + return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_VALUE : PlainValue$5.Type.PLAIN; + + case '-': + return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.SEQ_ITEM : PlainValue$5.Type.PLAIN; + + case '"': + return PlainValue$5.Type.QUOTE_DOUBLE; + + case "'": + return PlainValue$5.Type.QUOTE_SINGLE; + + default: + return PlainValue$5.Type.PLAIN; + } + } + + constructor(orig = {}, { + atLineStart, + inCollection, + inFlow, + indent, + lineStart, + parent + } = {}) { + PlainValue$5._defineProperty(this, "parseNode", (overlay, start) => { + if (PlainValue$5.Node.atDocumentBoundary(this.src, start)) return null; + const context = new ParseContext(this, overlay); + const { + props, + type, + valueStart + } = context.parseProps(start); + const node = createNewNode(type, props); + let offset = node.parse(context, valueStart); + node.range = new PlainValue$5.Range(start, offset); + /* istanbul ignore if */ + + if (offset <= start) { + // This should never happen, but if it does, let's make sure to at least + // step one character forward to avoid a busy loop. + node.error = new Error(`Node#parse consumed no characters`); + node.error.parseEnd = offset; + node.error.source = node; + node.range.end = start + 1; + } + + if (context.nodeStartsCollection(node)) { + if (!node.error && !context.atLineStart && context.parent.type === PlainValue$5.Type.DOCUMENT) { + node.error = new PlainValue$5.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)'); + } + + const collection = new Collection$1(node); + offset = collection.parse(new ParseContext(context), offset); + collection.range = new PlainValue$5.Range(start, offset); + return collection; + } + + return node; + }); + + this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false; + this.inCollection = inCollection != null ? inCollection : orig.inCollection || false; + this.inFlow = inFlow != null ? inFlow : orig.inFlow || false; + this.indent = indent != null ? indent : orig.indent; + this.lineStart = lineStart != null ? lineStart : orig.lineStart; + this.parent = parent != null ? parent : orig.parent || {}; + this.root = orig.root; + this.src = orig.src; + } + + nodeStartsCollection(node) { + const { + inCollection, + inFlow, + src + } = this; + if (inCollection || inFlow) return false; + if (node instanceof CollectionItem) return true; // check for implicit key + + let offset = node.range.end; + if (src[offset] === '\n' || src[offset - 1] === '\n') return false; + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + return src[offset] === ':'; + } // Anchor and tag are before type, which determines the node implementation + // class; hence this intermediate step. + + + parseProps(offset) { + const { + inFlow, + parent, + src + } = this; + const props = []; + let lineHasProps = false; + offset = this.atLineStart ? PlainValue$5.Node.endOfIndent(src, offset) : PlainValue$5.Node.endOfWhiteSpace(src, offset); + let ch = src[offset]; + + while (ch === PlainValue$5.Char.ANCHOR || ch === PlainValue$5.Char.COMMENT || ch === PlainValue$5.Char.TAG || ch === '\n') { + if (ch === '\n') { + let inEnd = offset; + let lineStart; + + do { + lineStart = inEnd + 1; + inEnd = PlainValue$5.Node.endOfIndent(src, lineStart); + } while (src[inEnd] === '\n'); + + const indentDiff = inEnd - (lineStart + this.indent); + const noIndicatorAsIndent = parent.type === PlainValue$5.Type.SEQ_ITEM && parent.context.atLineStart; + if (src[inEnd] !== '#' && !PlainValue$5.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break; + this.atLineStart = true; + this.lineStart = lineStart; + lineHasProps = false; + offset = inEnd; + } else if (ch === PlainValue$5.Char.COMMENT) { + const end = PlainValue$5.Node.endOfLine(src, offset + 1); + props.push(new PlainValue$5.Range(offset, end)); + offset = end; + } else { + let end = PlainValue$5.Node.endOfIdentifier(src, offset + 1); + + if (ch === PlainValue$5.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) { + // Let's presume we're dealing with a YAML 1.0 domain tag here, rather + // than an empty but 'foo.bar' private-tagged node in a flow collection + // followed without whitespace by a plain string starting with a year + // or date divided by something. + end = PlainValue$5.Node.endOfIdentifier(src, end + 5); + } + + props.push(new PlainValue$5.Range(offset, end)); + lineHasProps = true; + offset = PlainValue$5.Node.endOfWhiteSpace(src, end); + } + + ch = src[offset]; + } // '- &a : b' has an anchor on an empty node + + + if (lineHasProps && ch === ':' && PlainValue$5.Node.atBlank(src, offset + 1, true)) offset -= 1; + const type = ParseContext.parseType(src, offset, inFlow); + return { + props, + type, + valueStart: offset + }; + } + /** + * Parses a node from the source + * @param {ParseContext} overlay + * @param {number} start - Index of first non-whitespace character for the node + * @returns {?Node} - null if at a document boundary + */ + + +} + +// Published as 'yaml/parse-cst' +function parse$g(src) { + const cr = []; + + if (src.indexOf('\r') !== -1) { + src = src.replace(/\r\n?/g, (match, offset) => { + if (match.length > 1) cr.push(offset); + return '\n'; + }); + } + + const documents = []; + let offset = 0; + + do { + const doc = new Document$3(); + const context = new ParseContext({ + src + }); + offset = doc.parse(context, offset); + documents.push(doc); + } while (offset < src.length); + + documents.setOrigRanges = () => { + if (cr.length === 0) return false; + + for (let i = 1; i < cr.length; ++i) cr[i] -= i; + + let crOffset = 0; + + for (let i = 0; i < documents.length; ++i) { + crOffset = documents[i].setOrigRanges(cr, crOffset); + } + + cr.splice(0, cr.length); + return true; + }; + + documents.toString = () => documents.join('...\n'); + + return documents; +} + +parseCst$1.parse = parse$g; + +var Document9b4560a1 = {}; + +var resolveSeqD03cb037 = {}; + +var PlainValue$4 = PlainValueEc8e588e; + +function addCommentBefore(str, indent, comment) { + if (!comment) return str; + const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`); + return `#${cc}\n${indent}${str}`; +} +function addComment(str, indent, comment) { + return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`); +} + +class Node$1 {} + +function toJSON(value, arg, ctx) { + if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx)); + + if (value && typeof value.toJSON === 'function') { + const anchor = ctx && ctx.anchors && ctx.anchors.get(value); + if (anchor) ctx.onCreate = res => { + anchor.res = res; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (anchor && ctx.onCreate) ctx.onCreate(res); + return res; + } + + if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value); + return value; +} + +class Scalar extends Node$1 { + constructor(value) { + super(); + this.value = value; + } + + toJSON(arg, ctx) { + return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx); + } + + toString() { + return String(this.value); + } + +} + +function collectionFromPath(schema, path, value) { + let v = value; + + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + + if (Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + const o = {}; + Object.defineProperty(o, k, { + value: v, + writable: true, + enumerable: true, + configurable: true + }); + v = o; + } + } + + return schema.createNode(v, false); +} // null, undefined, or an empty non-string iterable (e.g. []) + + +const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done; +class Collection extends Node$1 { + constructor(schema) { + super(); + + PlainValue$4._defineProperty(this, "items", []); + + this.schema = schema; + } + + addIn(path, value) { + if (isEmptyPath(path)) this.add(value);else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + + deleteIn([key, ...rest]) { + if (rest.length === 0) return this.delete(key); + const node = this.get(key, true); + if (node instanceof Collection) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + + getIn([key, ...rest], keepScalar) { + const node = this.get(key, true); + if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined; + } + + hasAllNullValues() { + return this.items.every(node => { + if (!node || node.type !== 'PAIR') return false; + const n = node.value; + return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + + hasIn([key, ...rest]) { + if (rest.length === 0) return this.has(key); + const node = this.get(key, true); + return node instanceof Collection ? node.hasIn(rest) : false; + } + + setIn([key, ...rest], value) { + if (rest.length === 0) { + this.set(key, value); + } else { + const node = this.get(key, true); + if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } // overridden in implementations + + /* istanbul ignore next */ + + + toJSON() { + return null; + } + + toString(ctx, { + blockItem, + flowChars, + isMap, + itemIndent + }, onComment, onChompKeep) { + const { + indent, + indentStep, + stringify + } = ctx; + const inFlow = this.type === PlainValue$4.Type.FLOW_MAP || this.type === PlainValue$4.Type.FLOW_SEQ || ctx.inFlow; + if (inFlow) itemIndent += indentStep; + const allNullValues = isMap && this.hasAllNullValues(); + ctx = Object.assign({}, ctx, { + allNullValues, + indent: itemIndent, + inFlow, + type: null + }); + let chompKeep = false; + let hasItemWithNewLine = false; + const nodes = this.items.reduce((nodes, item, i) => { + let comment; + + if (item) { + if (!chompKeep && item.spaceBefore) nodes.push({ + type: 'comment', + str: '' + }); + if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => { + nodes.push({ + type: 'comment', + str: `#${line}` + }); + }); + if (item.comment) comment = item.comment; + if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true; + } + + chompKeep = false; + let str = stringify(item, ctx, () => comment = null, () => chompKeep = true); + if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true; + if (inFlow && i < this.items.length - 1) str += ','; + str = addComment(str, itemIndent, comment); + if (chompKeep && (comment || inFlow)) chompKeep = false; + nodes.push({ + type: 'item', + str + }); + return nodes; + }, []); + let str; + + if (nodes.length === 0) { + str = flowChars.start + flowChars.end; + } else if (inFlow) { + const { + start, + end + } = flowChars; + const strings = nodes.map(n => n.str); + + if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection.maxFlowStringSingleLineLength) { + str = start; + + for (const s of strings) { + str += s ? `\n${indentStep}${indent}${s}` : '\n'; + } + + str += `\n${indent}${end}`; + } else { + str = `${start} ${strings.join(' ')} ${end}`; + } + } else { + const strings = nodes.map(blockItem); + str = strings.shift(); + + for (const s of strings) str += s ? `\n${indent}${s}` : '\n'; + } + + if (this.comment) { + str += '\n' + this.comment.replace(/^/gm, `${indent}#`); + if (onComment) onComment(); + } else if (chompKeep && onChompKeep) onChompKeep(); + + return str; + } + +} + +PlainValue$4._defineProperty(Collection, "maxFlowStringSingleLineLength", 60); + +function asItemIndex(key) { + let idx = key instanceof Scalar ? key.value : key; + if (idx && typeof idx === 'string') idx = Number(idx); + return Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +class YAMLSeq extends Collection { + add(value) { + this.items.push(value); + } + + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') return undefined; + const it = this.items[idx]; + return !keepScalar && it instanceof Scalar ? it.value : it; + } + + has(key) { + const idx = asItemIndex(key); + return typeof idx === 'number' && idx < this.items.length; + } + + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`); + this.items[idx] = value; + } + + toJSON(_, ctx) { + const seq = []; + if (ctx && ctx.onCreate) ctx.onCreate(seq); + let i = 0; + + for (const item of this.items) seq.push(toJSON(item, String(i++), ctx)); + + return seq; + } + + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + return super.toString(ctx, { + blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`, + flowChars: { + start: '[', + end: ']' + }, + isMap: false, + itemIndent: (ctx.indent || '') + ' ' + }, onComment, onChompKeep); + } + +} + +const stringifyKey = (key, jsKey, ctx) => { + if (jsKey === null) return ''; + if (typeof jsKey !== 'object') return String(jsKey); + if (key instanceof Node$1 && ctx && ctx.doc) return key.toString({ + anchors: Object.create(null), + doc: ctx.doc, + indent: '', + indentStep: ctx.indentStep, + inFlow: true, + inStringifyKey: true, + stringify: ctx.stringify + }); + return JSON.stringify(jsKey); +}; + +class Pair extends Node$1 { + constructor(key, value = null) { + super(); + this.key = key; + this.value = value; + this.type = Pair.Type.PAIR; + } + + get commentBefore() { + return this.key instanceof Node$1 ? this.key.commentBefore : undefined; + } + + set commentBefore(cb) { + if (this.key == null) this.key = new Scalar(null); + if (this.key instanceof Node$1) this.key.commentBefore = cb;else { + const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.'; + throw new Error(msg); + } + } + + addToJSMap(ctx, map) { + const key = toJSON(this.key, '', ctx); + + if (map instanceof Map) { + const value = toJSON(this.value, key, ctx); + map.set(key, value); + } else if (map instanceof Set) { + map.add(key); + } else { + const stringKey = stringifyKey(this.key, key, ctx); + const value = toJSON(this.value, stringKey, ctx); + if (stringKey in map) Object.defineProperty(map, stringKey, { + value, + writable: true, + enumerable: true, + configurable: true + });else map[stringKey] = value; + } + + return map; + } + + toJSON(_, ctx) { + const pair = ctx && ctx.mapAsMap ? new Map() : {}; + return this.addToJSMap(ctx, pair); + } + + toString(ctx, onComment, onChompKeep) { + if (!ctx || !ctx.doc) return JSON.stringify(this); + const { + indent: indentSize, + indentSeq, + simpleKeys + } = ctx.doc.options; + let { + key, + value + } = this; + let keyComment = key instanceof Node$1 && key.comment; + + if (simpleKeys) { + if (keyComment) { + throw new Error('With simple keys, key nodes cannot have comments'); + } + + if (key instanceof Collection) { + const msg = 'With simple keys, collection cannot be used as a key value'; + throw new Error(msg); + } + } + + let explicitKey = !simpleKeys && (!key || keyComment || (key instanceof Node$1 ? key instanceof Collection || key.type === PlainValue$4.Type.BLOCK_FOLDED || key.type === PlainValue$4.Type.BLOCK_LITERAL : typeof key === 'object')); + const { + doc, + indent, + indentStep, + stringify + } = ctx; + ctx = Object.assign({}, ctx, { + implicitKey: !explicitKey, + indent: indent + indentStep + }); + let chompKeep = false; + let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true); + str = addComment(str, ctx.indent, keyComment); + + if (!explicitKey && str.length > 1024) { + if (simpleKeys) throw new Error('With simple keys, single line scalar must not span more than 1024 characters'); + explicitKey = true; + } + + if (ctx.allNullValues && !simpleKeys) { + if (this.comment) { + str = addComment(str, ctx.indent, this.comment); + if (onComment) onComment(); + } else if (chompKeep && !keyComment && onChompKeep) onChompKeep(); + + return ctx.inFlow && !explicitKey ? str : `? ${str}`; + } + + str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`; + + if (this.comment) { + // expected (but not strictly required) to be a single-line comment + str = addComment(str, ctx.indent, this.comment); + if (onComment) onComment(); + } + + let vcb = ''; + let valueComment = null; + + if (value instanceof Node$1) { + if (value.spaceBefore) vcb = '\n'; + + if (value.commentBefore) { + const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`); + vcb += `\n${cs}`; + } + + valueComment = value.comment; + } else if (value && typeof value === 'object') { + value = doc.schema.createNode(value, true); + } + + ctx.implicitKey = false; + if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1; + chompKeep = false; + + if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValue$4.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) { + // If indentSeq === false, consider '- ' as part of indentation where possible + ctx.indent = ctx.indent.substr(2); + } + + const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true); + let ws = ' '; + + if (vcb || this.comment) { + ws = `${vcb}\n${ctx.indent}`; + } else if (!explicitKey && value instanceof Collection) { + const flow = valueStr[0] === '[' || valueStr[0] === '{'; + if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`; + } else if (valueStr[0] === '\n') ws = ''; + + if (chompKeep && !valueComment && onChompKeep) onChompKeep(); + return addComment(str + ws + valueStr, ctx.indent, valueComment); + } + +} + +PlainValue$4._defineProperty(Pair, "Type", { + PAIR: 'PAIR', + MERGE_PAIR: 'MERGE_PAIR' +}); + +const getAliasCount = (node, anchors) => { + if (node instanceof Alias) { + const anchor = anchors.get(node.source); + return anchor.count * anchor.aliasCount; + } else if (node instanceof Collection) { + let count = 0; + + for (const item of node.items) { + const c = getAliasCount(item, anchors); + if (c > count) count = c; + } + + return count; + } else if (node instanceof Pair) { + const kc = getAliasCount(node.key, anchors); + const vc = getAliasCount(node.value, anchors); + return Math.max(kc, vc); + } + + return 1; +}; + +class Alias extends Node$1 { + static stringify({ + range, + source + }, { + anchors, + doc, + implicitKey, + inStringifyKey + }) { + let anchor = Object.keys(anchors).find(a => anchors[a] === source); + if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName(); + if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`; + const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node'; + throw new Error(`${msg} [${range}]`); + } + + constructor(source) { + super(); + this.source = source; + this.type = PlainValue$4.Type.ALIAS; + } + + set tag(t) { + throw new Error('Alias nodes cannot have tags'); + } + + toJSON(arg, ctx) { + if (!ctx) return toJSON(this.source, arg, ctx); + const { + anchors, + maxAliasCount + } = ctx; + const anchor = anchors.get(this.source); + /* istanbul ignore if */ + + if (!anchor || anchor.res === undefined) { + const msg = 'This should not happen: Alias anchor was not resolved?'; + if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); + } + + if (maxAliasCount >= 0) { + anchor.count += 1; + if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors); + + if (anchor.count * anchor.aliasCount > maxAliasCount) { + const msg = 'Excessive alias count indicates a resource exhaustion attack'; + if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); + } + } + + return anchor.res; + } // Only called when stringifying an alias mapping key while constructing + // Object output. + + + toString(ctx) { + return Alias.stringify(this, ctx); + } + +} + +PlainValue$4._defineProperty(Alias, "default", true); + +function findPair(items, key) { + const k = key instanceof Scalar ? key.value : key; + + for (const it of items) { + if (it instanceof Pair) { + if (it.key === key || it.key === k) return it; + if (it.key && it.key.value === k) return it; + } + } + + return undefined; +} +class YAMLMap extends Collection { + add(pair, overwrite) { + if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value); + const prev = findPair(this.items, pair.key); + const sortEntries = this.schema && this.schema.sortMapEntries; + + if (prev) { + if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`); + } else if (sortEntries) { + const i = this.items.findIndex(item => sortEntries(pair, item) < 0); + if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair); + } else { + this.items.push(pair); + } + } + + delete(key) { + const it = findPair(this.items, key); + if (!it) return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it && it.value; + return !keepScalar && node instanceof Scalar ? node.value : node; + } + + has(key) { + return !!findPair(this.items, key); + } + + set(key, value) { + this.add(new Pair(key, value), true); + } + /** + * @param {*} arg ignored + * @param {*} ctx Conversion context, originally set in Document#toJSON() + * @param {Class} Type If set, forces the returned collection type + * @returns {*} Instance of Type, Map, or Object + */ + + + toJSON(_, ctx, Type) { + const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {}; + if (ctx && ctx.onCreate) ctx.onCreate(map); + + for (const item of this.items) item.addToJSMap(ctx, map); + + return map; + } + + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + + for (const item of this.items) { + if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + + return super.toString(ctx, { + blockItem: n => n.str, + flowChars: { + start: '{', + end: '}' + }, + isMap: true, + itemIndent: ctx.indent || '' + }, onComment, onChompKeep); + } + +} + +const MERGE_KEY = '<<'; +class Merge extends Pair { + constructor(pair) { + if (pair instanceof Pair) { + let seq = pair.value; + + if (!(seq instanceof YAMLSeq)) { + seq = new YAMLSeq(); + seq.items.push(pair.value); + seq.range = pair.value.range; + } + + super(pair.key, seq); + this.range = pair.range; + } else { + super(new Scalar(MERGE_KEY), new YAMLSeq()); + } + + this.type = Pair.Type.MERGE_PAIR; + } // If the value associated with a merge key is a single mapping node, each of + // its key/value pairs is inserted into the current mapping, unless the key + // already exists in it. If the value associated with the merge key is a + // sequence, then this sequence is expected to contain mapping nodes and each + // of these nodes is merged in turn according to its order in the sequence. + // Keys in mapping nodes earlier in the sequence override keys specified in + // later mapping nodes. -- http://yaml.org/type/merge.html + + + addToJSMap(ctx, map) { + for (const { + source + } of this.value.items) { + if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps'); + const srcMap = source.toJSON(null, ctx, Map); + + for (const [key, value] of srcMap) { + if (map instanceof Map) { + if (!map.has(key)) map.set(key, value); + } else if (map instanceof Set) { + map.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map, key)) { + Object.defineProperty(map, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + } + } + + return map; + } + + toString(ctx, onComment) { + const seq = this.value; + if (seq.items.length > 1) return super.toString(ctx, onComment); + this.value = seq.items[0]; + const str = super.toString(ctx, onComment); + this.value = seq; + return str; + } + +} + +const binaryOptions = { + defaultType: PlainValue$4.Type.BLOCK_LITERAL, + lineWidth: 76 +}; +const boolOptions = { + trueStr: 'true', + falseStr: 'false' +}; +const intOptions = { + asBigInt: false +}; +const nullOptions = { + nullStr: 'null' +}; +const strOptions = { + defaultType: PlainValue$4.Type.PLAIN, + doubleQuoted: { + jsonEncoding: false, + minMultiLineLength: 40 + }, + fold: { + lineWidth: 80, + minContentWidth: 20 + } +}; + +function resolveScalar(str, tags, scalarFallback) { + for (const { + format, + test, + resolve + } of tags) { + if (test) { + const match = str.match(test); + + if (match) { + let res = resolve.apply(null, match); + if (!(res instanceof Scalar)) res = new Scalar(res); + if (format) res.format = format; + return res; + } + } + } + + if (scalarFallback) str = scalarFallback(str); + return new Scalar(str); +} + +const FOLD_FLOW = 'flow'; +const FOLD_BLOCK = 'block'; +const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line +// returns index of last newline in more-indented block + +const consumeMoreIndentedLines = (text, i) => { + let ch = text[i + 1]; + + while (ch === ' ' || ch === '\t') { + do { + ch = text[i += 1]; + } while (ch && ch !== '\n'); + + ch = text[i + 1]; + } + + return i; +}; +/** + * Tries to keep input at up to `lineWidth` characters, splitting only on spaces + * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are + * terminated with `\n` and started with `indent`. + * + * @param {string} text + * @param {string} indent + * @param {string} [mode='flow'] `'block'` prevents more-indented lines + * from being folded; `'quoted'` allows for `\` escapes, including escaped + * newlines + * @param {Object} options + * @param {number} [options.indentAtStart] Accounts for leading contents on + * the first line, defaulting to `indent.length` + * @param {number} [options.lineWidth=80] + * @param {number} [options.minContentWidth=20] Allow highly indented lines to + * stretch the line width or indent content from the start + * @param {function} options.onFold Called once if the text is folded + * @param {function} options.onFold Called once if any line of text exceeds + * lineWidth characters + */ + + +function foldFlowLines(text, indent, mode, { + indentAtStart, + lineWidth = 80, + minContentWidth = 20, + onFold, + onOverflow +}) { + if (!lineWidth || lineWidth < 0) return text; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + + if (typeof indentAtStart === 'number') { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0);else end = lineWidth - indentAtStart; + } + + let split = undefined; + let prev = undefined; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i); + if (i !== -1) end = i + endStep; + } + + for (let ch; ch = text[i += 1];) { + if (mode === FOLD_QUOTED && ch === '\\') { + escStart = i; + + switch (text[i + 1]) { + case 'x': + i += 3; + break; + + case 'u': + i += 5; + break; + + case 'U': + i += 9; + break; + + default: + i += 1; + } + + escEnd = i; + } + + if (ch === '\n') { + if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i); + end = i + endStep; + split = undefined; + } else { + if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') { + // space surrounded by non-space can be replaced with newline + indent + const next = text[i + 1]; + if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i; + } + + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = undefined; + } else if (mode === FOLD_QUOTED) { + // white-space collected at end may stretch past lineWidth + while (prev === ' ' || prev === '\t') { + prev = ch; + ch = text[i += 1]; + overflow = true; + } // Account for newline escape, but don't break preceding escape + + + const j = i > escEnd + 1 ? i - 2 : escStart - 1; // Bail out if lineWidth & minContentWidth are shorter than an escape string + + if (escapedFolds[j]) return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = undefined; + } else { + overflow = true; + } + } + } + + prev = ch; + } + + if (overflow && onOverflow) onOverflow(); + if (folds.length === 0) return text; + if (onFold) onFold(); + let res = text.slice(0, folds[0]); + + for (let i = 0; i < folds.length; ++i) { + const fold = folds[i]; + const end = folds[i + 1] || text.length; + if (fold === 0) res = `\n${indent}${text.slice(0, end)}`;else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`; + res += `\n${indent}${text.slice(fold + 1, end)}`; + } + } + + return res; +} + +const getFoldOptions = ({ + indentAtStart +}) => indentAtStart ? Object.assign({ + indentAtStart +}, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will +// presume that's starting a new document. + + +const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str); + +function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) return false; + + for (let i = 0, start = 0; i < strLen; ++i) { + if (str[i] === '\n') { + if (i - start > limit) return true; + start = i + 1; + if (strLen - start <= limit) return false; + } + } + + return true; +} + +function doubleQuotedString(value, ctx) { + const { + implicitKey + } = ctx; + const { + jsonEncoding, + minMultiLineLength + } = strOptions.doubleQuoted; + const json = JSON.stringify(value); + if (jsonEncoding) return json; + const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); + let str = ''; + let start = 0; + + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') { + // space before newline needs to be escaped to not be folded + str += json.slice(start, i) + '\\ '; + i += 1; + start = i; + ch = '\\'; + } + + if (ch === '\\') switch (json[i + 1]) { + case 'u': + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + + switch (code) { + case '0000': + str += '\\0'; + break; + + case '0007': + str += '\\a'; + break; + + case '000b': + str += '\\v'; + break; + + case '001b': + str += '\\e'; + break; + + case '0085': + str += '\\N'; + break; + + case '00a0': + str += '\\_'; + break; + + case '2028': + str += '\\L'; + break; + + case '2029': + str += '\\P'; + break; + + default: + if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6); + } + + i += 5; + start = i + 1; + } + break; + + case 'n': + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + // folding will eat first newline + str += json.slice(start, i) + '\n\n'; + + while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') { + str += '\n'; + i += 2; + } + + str += indent; // space after newline needs to be escaped to not be folded + + if (json[i + 2] === ' ') str += '\\'; + i += 1; + start = i + 1; + } + + break; + + default: + i += 1; + } + } + + str = start ? str + json.slice(start) : json; + return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx)); +} + +function singleQuotedString(value, ctx) { + if (ctx.implicitKey) { + if (/\n/.test(value)) return doubleQuotedString(value, ctx); + } else { + // single quoted string can't have leading or trailing whitespace around newline + if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx); + } + + const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx)); +} + +function blockString({ + comment, + type, + value +}, ctx, onComment, onChompKeep) { + // 1. Block can't end in whitespace unless the last line is non-empty. + // 2. Strings consisting of only whitespace are best rendered explicitly. + if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) { + return doubleQuotedString(value, ctx); + } + + const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : ''); + const indentSize = indent ? '2' : '1'; // root is at -1 + + const literal = type === PlainValue$4.Type.BLOCK_FOLDED ? false : type === PlainValue$4.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth, indent.length); + let header = literal ? '|' : '>'; + if (!value) return header + '\n'; + let wsStart = ''; + let wsEnd = ''; + value = value.replace(/[\n\t ]*$/, ws => { + const n = ws.indexOf('\n'); + + if (n === -1) { + header += '-'; // strip + } else if (value === ws || n !== ws.length - 1) { + header += '+'; // keep + + if (onChompKeep) onChompKeep(); + } + + wsEnd = ws.replace(/\n$/, ''); + return ''; + }).replace(/^[\n ]*/, ws => { + if (ws.indexOf(' ') !== -1) header += indentSize; + const m = ws.match(/ +$/); + + if (m) { + wsStart = ws.slice(0, -m[0].length); + return m[0]; + } else { + wsStart = ws; + return ''; + } + }); + if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`); + if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`); + + if (comment) { + header += ' #' + comment.replace(/ ?[\r\n]+/g, ' '); + if (onComment) onComment(); + } + + if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`; + + if (literal) { + value = value.replace(/\n+/g, `$&${indent}`); + return `${header}\n${indent}${wsStart}${value}${wsEnd}`; + } + + value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded + // ^ ind.line ^ empty ^ capture next empty lines only at end of indent + .replace(/\n+/g, `$&${indent}`); + const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold); + return `${header}\n${indent}${body}`; +} + +function plainString(item, ctx, onComment, onChompKeep) { + const { + comment, + type, + value + } = item; + const { + actualString, + implicitKey, + indent, + inFlow + } = ctx; + + if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) { + return doubleQuotedString(value, ctx); + } + + if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + // not allowed: + // - empty string, '-' or '?' + // - start with an indicator character (except [?:-]) or /[?-] / + // - '\n ', ': ' or ' \n' anywhere + // - '#' not preceded by a non-space char + // - end with ' ' or ':' + return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + + if (!implicitKey && !inFlow && type !== PlainValue$4.Type.PLAIN && value.indexOf('\n') !== -1) { + // Where allowed & type not set explicitly, prefer block style for multiline strings + return blockString(item, ctx, onComment, onChompKeep); + } + + if (indent === '' && containsDocumentMarker(value)) { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } + + const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and + // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'), + // and others in v1.1. + + if (actualString) { + const { + tags + } = ctx.doc.schema; + const resolved = resolveScalar(str, tags, tags.scalarFallback).value; + if (typeof resolved !== 'string') return doubleQuotedString(value, ctx); + } + + const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx)); + + if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) { + if (onComment) onComment(); + return addCommentBefore(body, indent, comment); + } + + return body; +} + +function stringifyString(item, ctx, onComment, onChompKeep) { + const { + defaultType + } = strOptions; + const { + implicitKey, + inFlow + } = ctx; + let { + type, + value + } = item; + + if (typeof value !== 'string') { + value = String(value); + item = Object.assign({}, item, { + value + }); + } + + const _stringify = _type => { + switch (_type) { + case PlainValue$4.Type.BLOCK_FOLDED: + case PlainValue$4.Type.BLOCK_LITERAL: + return blockString(item, ctx, onComment, onChompKeep); + + case PlainValue$4.Type.QUOTE_DOUBLE: + return doubleQuotedString(value, ctx); + + case PlainValue$4.Type.QUOTE_SINGLE: + return singleQuotedString(value, ctx); + + case PlainValue$4.Type.PLAIN: + return plainString(item, ctx, onComment, onChompKeep); + + default: + return null; + } + }; + + if (type !== PlainValue$4.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) { + // force double quotes on control characters + type = PlainValue$4.Type.QUOTE_DOUBLE; + } else if ((implicitKey || inFlow) && (type === PlainValue$4.Type.BLOCK_FOLDED || type === PlainValue$4.Type.BLOCK_LITERAL)) { + // should not happen; blocks are not valid inside flow containers + type = PlainValue$4.Type.QUOTE_DOUBLE; + } + + let res = _stringify(type); + + if (res === null) { + res = _stringify(defaultType); + if (res === null) throw new Error(`Unsupported default string type ${defaultType}`); + } + + return res; +} + +function stringifyNumber({ + format, + minFractionDigits, + tag, + value +}) { + if (typeof value === 'bigint') return String(value); + if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf'; + let n = JSON.stringify(value); + + if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) { + let i = n.indexOf('.'); + + if (i < 0) { + i = n.length; + n += '.'; + } + + let d = minFractionDigits - (n.length - i - 1); + + while (d-- > 0) n += '0'; + } + + return n; +} + +function checkFlowCollectionEnd(errors, cst) { + let char, name; + + switch (cst.type) { + case PlainValue$4.Type.FLOW_MAP: + char = '}'; + name = 'flow map'; + break; + + case PlainValue$4.Type.FLOW_SEQ: + char = ']'; + name = 'flow sequence'; + break; + + default: + errors.push(new PlainValue$4.YAMLSemanticError(cst, 'Not a flow collection!?')); + return; + } + + let lastItem; + + for (let i = cst.items.length - 1; i >= 0; --i) { + const item = cst.items[i]; + + if (!item || item.type !== PlainValue$4.Type.COMMENT) { + lastItem = item; + break; + } + } + + if (lastItem && lastItem.char !== char) { + const msg = `Expected ${name} to end with ${char}`; + let err; + + if (typeof lastItem.offset === 'number') { + err = new PlainValue$4.YAMLSemanticError(cst, msg); + err.offset = lastItem.offset + 1; + } else { + err = new PlainValue$4.YAMLSemanticError(lastItem, msg); + if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start; + } + + errors.push(err); + } +} +function checkFlowCommentSpace(errors, comment) { + const prev = comment.context.src[comment.range.start - 1]; + + if (prev !== '\n' && prev !== '\t' && prev !== ' ') { + const msg = 'Comments must be separated from other tokens by white space characters'; + errors.push(new PlainValue$4.YAMLSemanticError(comment, msg)); + } +} +function getLongKeyError(source, key) { + const sk = String(key); + const k = sk.substr(0, 8) + '...' + sk.substr(-8); + return new PlainValue$4.YAMLSemanticError(source, `The "${k}" key is too long`); +} +function resolveComments(collection, comments) { + for (const { + afterKey, + before, + comment + } of comments) { + let item = collection.items[before]; + + if (!item) { + if (comment !== undefined) { + if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment; + } + } else { + if (afterKey && item.value) item = item.value; + + if (comment === undefined) { + if (afterKey || !item.commentBefore) item.spaceBefore = true; + } else { + if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment; + } + } + } +} + +// on error, will return { str: string, errors: Error[] } +function resolveString(doc, node) { + const res = node.strValue; + if (!res) return ''; + if (typeof res === 'string') return res; + res.errors.forEach(error => { + if (!error.source) error.source = node; + doc.errors.push(error); + }); + return res.str; +} + +function resolveTagHandle(doc, node) { + const { + handle, + suffix + } = node.tag; + let prefix = doc.tagPrefixes.find(p => p.handle === handle); + + if (!prefix) { + const dtp = doc.getDefaults().tagPrefixes; + if (dtp) prefix = dtp.find(p => p.handle === handle); + if (!prefix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`); + } + + if (!suffix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag has no suffix.`); + + if (handle === '!' && (doc.version || doc.options.version) === '1.0') { + if (suffix[0] === '^') { + doc.warnings.push(new PlainValue$4.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported')); + return suffix; + } + + if (/[:/]/.test(suffix)) { + // word/foo -> tag:word.yaml.org,2002:foo + const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i); + return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`; + } + } + + return prefix.prefix + decodeURIComponent(suffix); +} + +function resolveTagName(doc, node) { + const { + tag, + type + } = node; + let nonSpecific = false; + + if (tag) { + const { + handle, + suffix, + verbatim + } = tag; + + if (verbatim) { + if (verbatim !== '!' && verbatim !== '!!') return verbatim; + const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`; + doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); + } else if (handle === '!' && !suffix) { + nonSpecific = true; + } else { + try { + return resolveTagHandle(doc, node); + } catch (error) { + doc.errors.push(error); + } + } + } + + switch (type) { + case PlainValue$4.Type.BLOCK_FOLDED: + case PlainValue$4.Type.BLOCK_LITERAL: + case PlainValue$4.Type.QUOTE_DOUBLE: + case PlainValue$4.Type.QUOTE_SINGLE: + return PlainValue$4.defaultTags.STR; + + case PlainValue$4.Type.FLOW_MAP: + case PlainValue$4.Type.MAP: + return PlainValue$4.defaultTags.MAP; + + case PlainValue$4.Type.FLOW_SEQ: + case PlainValue$4.Type.SEQ: + return PlainValue$4.defaultTags.SEQ; + + case PlainValue$4.Type.PLAIN: + return nonSpecific ? PlainValue$4.defaultTags.STR : null; + + default: + return null; + } +} + +function resolveByTagName(doc, node, tagName) { + const { + tags + } = doc.schema; + const matchWithTest = []; + + for (const tag of tags) { + if (tag.tag === tagName) { + if (tag.test) matchWithTest.push(tag);else { + const res = tag.resolve(doc, node); + return res instanceof Collection ? res : new Scalar(res); + } + } + } + + const str = resolveString(doc, node); + if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback); + return null; +} + +function getFallbackTagName({ + type +}) { + switch (type) { + case PlainValue$4.Type.FLOW_MAP: + case PlainValue$4.Type.MAP: + return PlainValue$4.defaultTags.MAP; + + case PlainValue$4.Type.FLOW_SEQ: + case PlainValue$4.Type.SEQ: + return PlainValue$4.defaultTags.SEQ; + + default: + return PlainValue$4.defaultTags.STR; + } +} + +function resolveTag(doc, node, tagName) { + try { + const res = resolveByTagName(doc, node, tagName); + + if (res) { + if (tagName && node.tag) res.tag = tagName; + return res; + } + } catch (error) { + /* istanbul ignore if */ + if (!error.source) error.source = node; + doc.errors.push(error); + return null; + } + + try { + const fallback = getFallbackTagName(node); + if (!fallback) throw new Error(`The tag ${tagName} is unavailable`); + const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`; + doc.warnings.push(new PlainValue$4.YAMLWarning(node, msg)); + const res = resolveByTagName(doc, node, fallback); + res.tag = tagName; + return res; + } catch (error) { + const refError = new PlainValue$4.YAMLReferenceError(node, error.message); + refError.stack = error.stack; + doc.errors.push(refError); + return null; + } +} + +const isCollectionItem = node => { + if (!node) return false; + const { + type + } = node; + return type === PlainValue$4.Type.MAP_KEY || type === PlainValue$4.Type.MAP_VALUE || type === PlainValue$4.Type.SEQ_ITEM; +}; + +function resolveNodeProps(errors, node) { + const comments = { + before: [], + after: [] + }; + let hasAnchor = false; + let hasTag = false; + const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props; + + for (const { + start, + end + } of props) { + switch (node.context.src[start]) { + case PlainValue$4.Char.COMMENT: + { + if (!node.commentHasRequiredWhitespace(start)) { + const msg = 'Comments must be separated from other tokens by white space characters'; + errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); + } + + const { + header, + valueRange + } = node; + const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before; + cc.push(node.context.src.slice(start + 1, end)); + break; + } + // Actual anchor & tag resolution is handled by schema, here we just complain + + case PlainValue$4.Char.ANCHOR: + if (hasAnchor) { + const msg = 'A node can have at most one anchor'; + errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); + } + + hasAnchor = true; + break; + + case PlainValue$4.Char.TAG: + if (hasTag) { + const msg = 'A node can have at most one tag'; + errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); + } + + hasTag = true; + break; + } + } + + return { + comments, + hasAnchor, + hasTag + }; +} + +function resolveNodeValue(doc, node) { + const { + anchors, + errors, + schema + } = doc; + + if (node.type === PlainValue$4.Type.ALIAS) { + const name = node.rawValue; + const src = anchors.getNode(name); + + if (!src) { + const msg = `Aliased anchor not found: ${name}`; + errors.push(new PlainValue$4.YAMLReferenceError(node, msg)); + return null; + } // Lazy resolution for circular references + + + const res = new Alias(src); + + anchors._cstAliases.push(res); + + return res; + } + + const tagName = resolveTagName(doc, node); + if (tagName) return resolveTag(doc, node, tagName); + + if (node.type !== PlainValue$4.Type.PLAIN) { + const msg = `Failed to resolve ${node.type} node here`; + errors.push(new PlainValue$4.YAMLSyntaxError(node, msg)); + return null; + } + + try { + const str = resolveString(doc, node); + return resolveScalar(str, schema.tags, schema.tags.scalarFallback); + } catch (error) { + if (!error.source) error.source = node; + errors.push(error); + return null; + } +} // sets node.resolved on success + + +function resolveNode(doc, node) { + if (!node) return null; + if (node.error) doc.errors.push(node.error); + const { + comments, + hasAnchor, + hasTag + } = resolveNodeProps(doc.errors, node); + + if (hasAnchor) { + const { + anchors + } = doc; + const name = node.anchor; + const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor + // name have already been resolved, so it may safely be renamed. + + if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as + // anchors need to be available during resolution to allow for + // circular references. + + anchors.map[name] = node; + } + + if (node.type === PlainValue$4.Type.ALIAS && (hasAnchor || hasTag)) { + const msg = 'An alias node must not specify any properties'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); + } + + const res = resolveNodeValue(doc, node); + + if (res) { + res.range = [node.range.start, node.range.end]; + if (doc.options.keepCstNodes) res.cstNode = node; + if (doc.options.keepNodeTypes) res.type = node.type; + const cb = comments.before.join('\n'); + + if (cb) { + res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb; + } + + const ca = comments.after.join('\n'); + if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca; + } + + return node.resolved = res; +} + +function resolveMap(doc, cst) { + if (cst.type !== PlainValue$4.Type.MAP && cst.type !== PlainValue$4.Type.FLOW_MAP) { + const msg = `A ${cst.type} node cannot be resolved as a mapping`; + doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg)); + return null; + } + + const { + comments, + items + } = cst.type === PlainValue$4.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst); + const map = new YAMLMap(); + map.items = items; + resolveComments(map, comments); + let hasCollectionKey = false; + + for (let i = 0; i < items.length; ++i) { + const { + key: iKey + } = items[i]; + if (iKey instanceof Collection) hasCollectionKey = true; + + if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) { + items[i] = new Merge(items[i]); + const sources = items[i].value.items; + let error = null; + sources.some(node => { + if (node instanceof Alias) { + // During parsing, alias sources are CST nodes; to account for + // circular references their resolved values can't be used here. + const { + type + } = node.source; + if (type === PlainValue$4.Type.MAP || type === PlainValue$4.Type.FLOW_MAP) return false; + return error = 'Merge nodes aliases can only point to maps'; + } + + return error = 'Merge nodes can only have Alias nodes as values'; + }); + if (error) doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, error)); + } else { + for (let j = i + 1; j < items.length; ++j) { + const { + key: jKey + } = items[j]; + + if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) { + const msg = `Map keys must be unique; "${iKey}" is repeated`; + doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, msg)); + break; + } + } + } + } + + if (hasCollectionKey && !doc.options.mapAsMap) { + const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; + doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn)); + } + + cst.resolved = map; + return map; +} + +const valueHasPairComment = ({ + context: { + lineStart, + node, + src + }, + props +}) => { + if (props.length === 0) return false; + const { + start + } = props[0]; + if (node && start > node.valueRange.start) return false; + if (src[start] !== PlainValue$4.Char.COMMENT) return false; + + for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false; + + return true; +}; + +function resolvePairComment(item, pair) { + if (!valueHasPairComment(item)) return; + const comment = item.getPropValue(0, PlainValue$4.Char.COMMENT, true); + let found = false; + const cb = pair.value.commentBefore; + + if (cb && cb.startsWith(comment)) { + pair.value.commentBefore = cb.substr(comment.length + 1); + found = true; + } else { + const cc = pair.value.comment; + + if (!item.node && cc && cc.startsWith(comment)) { + pair.value.comment = cc.substr(comment.length + 1); + found = true; + } + } + + if (found) pair.comment = comment; +} + +function resolveBlockMapItems(doc, cst) { + const comments = []; + const items = []; + let key = undefined; + let keyStart = null; + + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + + switch (item.type) { + case PlainValue$4.Type.BLANK_LINE: + comments.push({ + afterKey: !!key, + before: items.length + }); + break; + + case PlainValue$4.Type.COMMENT: + comments.push({ + afterKey: !!key, + before: items.length, + comment: item.comment + }); + break; + + case PlainValue$4.Type.MAP_KEY: + if (key !== undefined) items.push(new Pair(key)); + if (item.error) doc.errors.push(item.error); + key = resolveNode(doc, item.node); + keyStart = null; + break; + + case PlainValue$4.Type.MAP_VALUE: + { + if (key === undefined) key = null; + if (item.error) doc.errors.push(item.error); + + if (!item.context.atLineStart && item.node && item.node.type === PlainValue$4.Type.MAP && !item.node.context.atLineStart) { + const msg = 'Nested mappings are not allowed in compact mappings'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(item.node, msg)); + } + + let valueNode = item.node; + + if (!valueNode && item.props.length > 0) { + // Comments on an empty mapping value need to be preserved, so we + // need to construct a minimal empty node here to use instead of the + // missing `item.node`. -- eemeli/yaml#19 + valueNode = new PlainValue$4.PlainValue(PlainValue$4.Type.PLAIN, []); + valueNode.context = { + parent: item, + src: item.context.src + }; + const pos = item.range.start + 1; + valueNode.range = { + start: pos, + end: pos + }; + valueNode.valueRange = { + start: pos, + end: pos + }; + + if (typeof item.range.origStart === 'number') { + const origPos = item.range.origStart + 1; + valueNode.range.origStart = valueNode.range.origEnd = origPos; + valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos; + } + } + + const pair = new Pair(key, resolveNode(doc, valueNode)); + resolvePairComment(item, pair); + items.push(pair); + + if (key && typeof keyStart === 'number') { + if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); + } + + key = undefined; + keyStart = null; + } + break; + + default: + if (key !== undefined) items.push(new Pair(key)); + key = resolveNode(doc, item); + keyStart = item.range.start; + if (item.error) doc.errors.push(item.error); + + next: for (let j = i + 1;; ++j) { + const nextItem = cst.items[j]; + + switch (nextItem && nextItem.type) { + case PlainValue$4.Type.BLANK_LINE: + case PlainValue$4.Type.COMMENT: + continue next; + + case PlainValue$4.Type.MAP_VALUE: + break next; + + default: + { + const msg = 'Implicit map keys need to be followed by map values'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); + break next; + } + } + } + + if (item.valueRangeContainsNewline) { + const msg = 'Implicit map keys need to be on a single line'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); + } + + } + } + + if (key !== undefined) items.push(new Pair(key)); + return { + comments, + items + }; +} + +function resolveFlowMapItems(doc, cst) { + const comments = []; + const items = []; + let key = undefined; + let explicitKey = false; + let next = '{'; + + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + + if (typeof item.char === 'string') { + const { + char, + offset + } = item; + + if (char === '?' && key === undefined && !explicitKey) { + explicitKey = true; + next = ':'; + continue; + } + + if (char === ':') { + if (key === undefined) key = null; + + if (next === ':') { + next = ','; + continue; + } + } else { + if (explicitKey) { + if (key === undefined && char !== ',') key = null; + explicitKey = false; + } + + if (key !== undefined) { + items.push(new Pair(key)); + key = undefined; + + if (char === ',') { + next = ':'; + continue; + } + } + } + + if (char === '}') { + if (i === cst.items.length - 1) continue; + } else if (char === next) { + next = ':'; + continue; + } + + const msg = `Flow map contains an unexpected ${char}`; + const err = new PlainValue$4.YAMLSyntaxError(cst, msg); + err.offset = offset; + doc.errors.push(err); + } else if (item.type === PlainValue$4.Type.BLANK_LINE) { + comments.push({ + afterKey: !!key, + before: items.length + }); + } else if (item.type === PlainValue$4.Type.COMMENT) { + checkFlowCommentSpace(doc.errors, item); + comments.push({ + afterKey: !!key, + before: items.length, + comment: item.comment + }); + } else if (key === undefined) { + if (next === ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Separator , missing in flow map')); + key = resolveNode(doc, item); + } else { + if (next !== ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Indicator : missing in flow map entry')); + items.push(new Pair(key, resolveNode(doc, item))); + key = undefined; + explicitKey = false; + } + } + + checkFlowCollectionEnd(doc.errors, cst); + if (key !== undefined) items.push(new Pair(key)); + return { + comments, + items + }; +} + +function resolveSeq$3(doc, cst) { + if (cst.type !== PlainValue$4.Type.SEQ && cst.type !== PlainValue$4.Type.FLOW_SEQ) { + const msg = `A ${cst.type} node cannot be resolved as a sequence`; + doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg)); + return null; + } + + const { + comments, + items + } = cst.type === PlainValue$4.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst); + const seq = new YAMLSeq(); + seq.items = items; + resolveComments(seq, comments); + + if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection)) { + const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; + doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn)); + } + + cst.resolved = seq; + return seq; +} + +function resolveBlockSeqItems(doc, cst) { + const comments = []; + const items = []; + + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + + switch (item.type) { + case PlainValue$4.Type.BLANK_LINE: + comments.push({ + before: items.length + }); + break; + + case PlainValue$4.Type.COMMENT: + comments.push({ + comment: item.comment, + before: items.length + }); + break; + + case PlainValue$4.Type.SEQ_ITEM: + if (item.error) doc.errors.push(item.error); + items.push(resolveNode(doc, item.node)); + + if (item.hasProps) { + const msg = 'Sequence items cannot have tags or anchors before the - indicator'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); + } + + break; + + default: + if (item.error) doc.errors.push(item.error); + doc.errors.push(new PlainValue$4.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`)); + } + } + + return { + comments, + items + }; +} + +function resolveFlowSeqItems(doc, cst) { + const comments = []; + const items = []; + let explicitKey = false; + let key = undefined; + let keyStart = null; + let next = '['; + let prevItem = null; + + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + + if (typeof item.char === 'string') { + const { + char, + offset + } = item; + + if (char !== ':' && (explicitKey || key !== undefined)) { + if (explicitKey && key === undefined) key = next ? items.pop() : null; + items.push(new Pair(key)); + explicitKey = false; + key = undefined; + keyStart = null; + } + + if (char === next) { + next = null; + } else if (!next && char === '?') { + explicitKey = true; + } else if (next !== '[' && char === ':' && key === undefined) { + if (next === ',') { + key = items.pop(); + + if (key instanceof Pair) { + const msg = 'Chaining flow sequence pairs is invalid'; + const err = new PlainValue$4.YAMLSemanticError(cst, msg); + err.offset = offset; + doc.errors.push(err); + } + + if (!explicitKey && typeof keyStart === 'number') { + const keyEnd = item.range ? item.range.start : item.offset; + if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); + const { + src + } = prevItem.context; + + for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') { + const msg = 'Implicit keys of flow sequence pairs need to be on a single line'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(prevItem, msg)); + break; + } + } + } else { + key = null; + } + + keyStart = null; + explicitKey = false; + next = null; + } else if (next === '[' || char !== ']' || i < cst.items.length - 1) { + const msg = `Flow sequence contains an unexpected ${char}`; + const err = new PlainValue$4.YAMLSyntaxError(cst, msg); + err.offset = offset; + doc.errors.push(err); + } + } else if (item.type === PlainValue$4.Type.BLANK_LINE) { + comments.push({ + before: items.length + }); + } else if (item.type === PlainValue$4.Type.COMMENT) { + checkFlowCommentSpace(doc.errors, item); + comments.push({ + comment: item.comment, + before: items.length + }); + } else { + if (next) { + const msg = `Expected a ${next} in flow sequence`; + doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); + } + + const value = resolveNode(doc, item); + + if (key === undefined) { + items.push(value); + prevItem = item; + } else { + items.push(new Pair(key, value)); + key = undefined; + } + + keyStart = item.range.start; + next = ','; + } + } + + checkFlowCollectionEnd(doc.errors, cst); + if (key !== undefined) items.push(new Pair(key)); + return { + comments, + items + }; +} + +resolveSeqD03cb037.Alias = Alias; +resolveSeqD03cb037.Collection = Collection; +resolveSeqD03cb037.Merge = Merge; +resolveSeqD03cb037.Node = Node$1; +resolveSeqD03cb037.Pair = Pair; +resolveSeqD03cb037.Scalar = Scalar; +resolveSeqD03cb037.YAMLMap = YAMLMap; +resolveSeqD03cb037.YAMLSeq = YAMLSeq; +resolveSeqD03cb037.addComment = addComment; +resolveSeqD03cb037.binaryOptions = binaryOptions; +resolveSeqD03cb037.boolOptions = boolOptions; +resolveSeqD03cb037.findPair = findPair; +resolveSeqD03cb037.intOptions = intOptions; +resolveSeqD03cb037.isEmptyPath = isEmptyPath; +resolveSeqD03cb037.nullOptions = nullOptions; +resolveSeqD03cb037.resolveMap = resolveMap; +resolveSeqD03cb037.resolveNode = resolveNode; +resolveSeqD03cb037.resolveSeq = resolveSeq$3; +resolveSeqD03cb037.resolveString = resolveString; +resolveSeqD03cb037.strOptions = strOptions; +resolveSeqD03cb037.stringifyNumber = stringifyNumber; +resolveSeqD03cb037.stringifyString = stringifyString; +resolveSeqD03cb037.toJSON = toJSON; + +var Schema88e323a7 = {}; + +var warnings1000a372 = {}; + +var PlainValue$3 = PlainValueEc8e588e; +var resolveSeq$2 = resolveSeqD03cb037; + +/* global atob, btoa, Buffer */ +const binary = { + identify: value => value instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: 'tag:yaml.org,2002:binary', + + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve: (doc, node) => { + const src = resolveSeq$2.resolveString(doc, node); + + if (typeof Buffer === 'function') { + return Buffer.from(src, 'base64'); + } else if (typeof atob === 'function') { + // On IE 11, atob() can't handle newlines + const str = atob(src.replace(/[\n\r]/g, '')); + const buffer = new Uint8Array(str.length); + + for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i); + + return buffer; + } else { + const msg = 'This environment does not support reading binary tags; either Buffer or atob is required'; + doc.errors.push(new PlainValue$3.YAMLReferenceError(node, msg)); + return null; + } + }, + options: resolveSeq$2.binaryOptions, + stringify: ({ + comment, + type, + value + }, ctx, onComment, onChompKeep) => { + let src; + + if (typeof Buffer === 'function') { + src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64'); + } else if (typeof btoa === 'function') { + let s = ''; + + for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]); + + src = btoa(s); + } else { + throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required'); + } + + if (!type) type = resolveSeq$2.binaryOptions.defaultType; + + if (type === PlainValue$3.Type.QUOTE_DOUBLE) { + value = src; + } else { + const { + lineWidth + } = resolveSeq$2.binaryOptions; + const n = Math.ceil(src.length / lineWidth); + const lines = new Array(n); + + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines[i] = src.substr(o, lineWidth); + } + + value = lines.join(type === PlainValue$3.Type.BLOCK_LITERAL ? '\n' : ' '); + } + + return resolveSeq$2.stringifyString({ + comment, + type, + value + }, ctx, onComment, onChompKeep); + } +}; + +function parsePairs(doc, cst) { + const seq = resolveSeq$2.resolveSeq(doc, cst); + + for (let i = 0; i < seq.items.length; ++i) { + let item = seq.items[i]; + if (item instanceof resolveSeq$2.Pair) continue;else if (item instanceof resolveSeq$2.YAMLMap) { + if (item.items.length > 1) { + const msg = 'Each pair must have its own sequence indicator'; + throw new PlainValue$3.YAMLSemanticError(cst, msg); + } + + const pair = item.items[0] || new resolveSeq$2.Pair(); + if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore; + if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment; + item = pair; + } + seq.items[i] = item instanceof resolveSeq$2.Pair ? item : new resolveSeq$2.Pair(item); + } + + return seq; +} +function createPairs(schema, iterable, ctx) { + const pairs = new resolveSeq$2.YAMLSeq(schema); + pairs.tag = 'tag:yaml.org,2002:pairs'; + + for (const it of iterable) { + let key, value; + + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } else throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else throw new TypeError(`Expected { key: value } tuple: ${it}`); + } else { + key = it; + } + + const pair = schema.createPair(key, value, ctx); + pairs.items.push(pair); + } + + return pairs; +} +const pairs = { + default: false, + tag: 'tag:yaml.org,2002:pairs', + resolve: parsePairs, + createNode: createPairs +}; + +class YAMLOMap extends resolveSeq$2.YAMLSeq { + constructor() { + super(); + + PlainValue$3._defineProperty(this, "add", resolveSeq$2.YAMLMap.prototype.add.bind(this)); + + PlainValue$3._defineProperty(this, "delete", resolveSeq$2.YAMLMap.prototype.delete.bind(this)); + + PlainValue$3._defineProperty(this, "get", resolveSeq$2.YAMLMap.prototype.get.bind(this)); + + PlainValue$3._defineProperty(this, "has", resolveSeq$2.YAMLMap.prototype.has.bind(this)); + + PlainValue$3._defineProperty(this, "set", resolveSeq$2.YAMLMap.prototype.set.bind(this)); + + this.tag = YAMLOMap.tag; + } + + toJSON(_, ctx) { + const map = new Map(); + if (ctx && ctx.onCreate) ctx.onCreate(map); + + for (const pair of this.items) { + let key, value; + + if (pair instanceof resolveSeq$2.Pair) { + key = resolveSeq$2.toJSON(pair.key, '', ctx); + value = resolveSeq$2.toJSON(pair.value, key, ctx); + } else { + key = resolveSeq$2.toJSON(pair, '', ctx); + } + + if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys'); + map.set(key, value); + } + + return map; + } + +} + +PlainValue$3._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap'); + +function parseOMap(doc, cst) { + const pairs = parsePairs(doc, cst); + const seenKeys = []; + + for (const { + key + } of pairs.items) { + if (key instanceof resolveSeq$2.Scalar) { + if (seenKeys.includes(key.value)) { + const msg = 'Ordered maps must not include duplicate keys'; + throw new PlainValue$3.YAMLSemanticError(cst, msg); + } else { + seenKeys.push(key.value); + } + } + } + + return Object.assign(new YAMLOMap(), pairs); +} + +function createOMap(schema, iterable, ctx) { + const pairs = createPairs(schema, iterable, ctx); + const omap = new YAMLOMap(); + omap.items = pairs.items; + return omap; +} + +const omap = { + identify: value => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: 'tag:yaml.org,2002:omap', + resolve: parseOMap, + createNode: createOMap +}; + +class YAMLSet extends resolveSeq$2.YAMLMap { + constructor() { + super(); + this.tag = YAMLSet.tag; + } + + add(key) { + const pair = key instanceof resolveSeq$2.Pair ? key : new resolveSeq$2.Pair(key); + const prev = resolveSeq$2.findPair(this.items, pair.key); + if (!prev) this.items.push(pair); + } + + get(key, keepPair) { + const pair = resolveSeq$2.findPair(this.items, key); + return !keepPair && pair instanceof resolveSeq$2.Pair ? pair.key instanceof resolveSeq$2.Scalar ? pair.key.value : pair.key : pair; + } + + set(key, value) { + if (typeof value !== 'boolean') throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = resolveSeq$2.findPair(this.items, key); + + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value) { + this.items.push(new resolveSeq$2.Pair(key)); + } + } + + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values'); + } + +} + +PlainValue$3._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set'); + +function parseSet(doc, cst) { + const map = resolveSeq$2.resolveMap(doc, cst); + if (!map.hasAllNullValues()) throw new PlainValue$3.YAMLSemanticError(cst, 'Set items must all have null values'); + return Object.assign(new YAMLSet(), map); +} + +function createSet(schema, iterable, ctx) { + const set = new YAMLSet(); + + for (const value of iterable) set.items.push(schema.createPair(value, null, ctx)); + + return set; +} + +const set = { + identify: value => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: 'tag:yaml.org,2002:set', + resolve: parseSet, + createNode: createSet +}; + +const parseSexagesimal = (sign, parts) => { + const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0); + return sign === '-' ? -n : n; +}; // hhhh:mm:ss.sss + + +const stringifySexagesimal = ({ + value +}) => { + if (isNaN(value) || !isFinite(value)) return resolveSeq$2.stringifyNumber(value); + let sign = ''; + + if (value < 0) { + sign = '-'; + value = Math.abs(value); + } + + const parts = [value % 60]; // seconds, including ms + + if (value < 60) { + parts.unshift(0); // at least one : is required + } else { + value = Math.round((value - parts[0]) / 60); + parts.unshift(value % 60); // minutes + + if (value >= 60) { + value = Math.round((value - parts[0]) / 60); + parts.unshift(value); // hours + } + } + + return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error + ; +}; + +const intTime = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'TIME', + test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/, + resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), + stringify: stringifySexagesimal +}; +const floatTime = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'TIME', + test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/, + resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), + stringify: stringifySexagesimal +}; +const timestamp = { + identify: value => value instanceof Date, + default: true, + tag: 'tag:yaml.org,2002:timestamp', + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd + '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)? + '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30 + ')?' + ')$'), + resolve: (str, year, month, day, hour, minute, second, millisec, tz) => { + if (millisec) millisec = (millisec + '00').substr(1, 3); + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0); + + if (tz && tz !== 'Z') { + let d = parseSexagesimal(tz[0], tz.slice(1)); + if (Math.abs(d) < 30) d *= 60; + date -= 60000 * d; + } + + return new Date(date); + }, + stringify: ({ + value + }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '') +}; + +/* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */ +function shouldWarn(deprecation) { + const env = typeof process !== 'undefined' && process.env || {}; + + if (deprecation) { + if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS; + return !env.YAML_SILENCE_DEPRECATION_WARNINGS; + } + + if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS; + return !env.YAML_SILENCE_WARNINGS; +} + +function warn(warning, type) { + if (shouldWarn(false)) { + const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to + // https://github.com/facebook/jest/issues/2549 + + if (emit) emit(warning, type);else { + // eslint-disable-next-line no-console + console.warn(type ? `${type}: ${warning}` : warning); + } + } +} +function warnFileDeprecation(filename) { + if (shouldWarn(true)) { + const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/'); + warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning'); + } +} +const warned = {}; +function warnOptionDeprecation(name, alternative) { + if (!warned[name] && shouldWarn(true)) { + warned[name] = true; + let msg = `The option '${name}' will be removed in a future release`; + msg += alternative ? `, use '${alternative}' instead.` : '.'; + warn(msg, 'DeprecationWarning'); + } +} + +warnings1000a372.binary = binary; +warnings1000a372.floatTime = floatTime; +warnings1000a372.intTime = intTime; +warnings1000a372.omap = omap; +warnings1000a372.pairs = pairs; +warnings1000a372.set = set; +warnings1000a372.timestamp = timestamp; +warnings1000a372.warn = warn; +warnings1000a372.warnFileDeprecation = warnFileDeprecation; +warnings1000a372.warnOptionDeprecation = warnOptionDeprecation; + +var PlainValue$2 = PlainValueEc8e588e; +var resolveSeq$1 = resolveSeqD03cb037; +var warnings$1 = warnings1000a372; + +function createMap(schema, obj, ctx) { + const map = new resolveSeq$1.YAMLMap(schema); + + if (obj instanceof Map) { + for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx)); + } else if (obj && typeof obj === 'object') { + for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx)); + } + + if (typeof schema.sortMapEntries === 'function') { + map.items.sort(schema.sortMapEntries); + } + + return map; +} + +const map = { + createNode: createMap, + default: true, + nodeClass: resolveSeq$1.YAMLMap, + tag: 'tag:yaml.org,2002:map', + resolve: resolveSeq$1.resolveMap +}; + +function createSeq(schema, obj, ctx) { + const seq = new resolveSeq$1.YAMLSeq(schema); + + if (obj && obj[Symbol.iterator]) { + for (const it of obj) { + const v = schema.createNode(it, ctx.wrapScalars, null, ctx); + seq.items.push(v); + } + } + + return seq; +} + +const seq = { + createNode: createSeq, + default: true, + nodeClass: resolveSeq$1.YAMLSeq, + tag: 'tag:yaml.org,2002:seq', + resolve: resolveSeq$1.resolveSeq +}; + +const string = { + identify: value => typeof value === 'string', + default: true, + tag: 'tag:yaml.org,2002:str', + resolve: resolveSeq$1.resolveString, + + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ + actualString: true + }, ctx); + return resolveSeq$1.stringifyString(item, ctx, onComment, onChompKeep); + }, + + options: resolveSeq$1.strOptions +}; + +const failsafe = [map, seq, string]; + +/* global BigInt */ + +const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value); + +const intResolve$1 = (src, part, radix) => resolveSeq$1.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix); + +function intStringify$1(node, radix, prefix) { + const { + value + } = node; + if (intIdentify$2(value) && value >= 0) return prefix + value.toString(radix); + return resolveSeq$1.stringifyNumber(node); +} + +const nullObj = { + identify: value => value == null, + createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => null, + options: resolveSeq$1.nullOptions, + stringify: () => resolveSeq$1.nullOptions.nullStr +}; +const boolObj = { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: str => str[0] === 't' || str[0] === 'T', + options: resolveSeq$1.boolOptions, + stringify: ({ + value + }) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr +}; +const octObj = { + identify: value => intIdentify$2(value) && value >= 0, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'OCT', + test: /^0o([0-7]+)$/, + resolve: (str, oct) => intResolve$1(str, oct, 8), + options: resolveSeq$1.intOptions, + stringify: node => intStringify$1(node, 8, '0o') +}; +const intObj = { + identify: intIdentify$2, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^[-+]?[0-9]+$/, + resolve: str => intResolve$1(str, str, 10), + options: resolveSeq$1.intOptions, + stringify: resolveSeq$1.stringifyNumber +}; +const hexObj = { + identify: value => intIdentify$2(value) && value >= 0, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'HEX', + test: /^0x([0-9a-fA-F]+)$/, + resolve: (str, hex) => intResolve$1(str, hex, 16), + options: resolveSeq$1.intOptions, + stringify: node => intStringify$1(node, 16, '0x') +}; +const nanObj = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.inf|(\.nan))$/i, + resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: resolveSeq$1.stringifyNumber +}; +const expObj = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'EXP', + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: str => parseFloat(str), + stringify: ({ + value + }) => Number(value).toExponential() +}; +const floatObj = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/, + + resolve(str, frac1, frac2) { + const frac = frac1 || frac2; + const node = new resolveSeq$1.Scalar(parseFloat(str)); + if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length; + return node; + }, + + stringify: resolveSeq$1.stringifyNumber +}; +const core$2 = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]); + +/* global BigInt */ + +const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value); + +const stringifyJSON = ({ + value +}) => JSON.stringify(value); + +const json = [map, seq, { + identify: value => typeof value === 'string', + default: true, + tag: 'tag:yaml.org,2002:str', + resolve: resolveSeq$1.resolveString, + stringify: stringifyJSON +}, { + identify: value => value == null, + createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON +}, { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^true|false$/, + resolve: str => str === 'true', + stringify: stringifyJSON +}, { + identify: intIdentify$1, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: str => resolveSeq$1.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ + value + }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value) +}, { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: str => parseFloat(str), + stringify: stringifyJSON +}]; + +json.scalarFallback = str => { + throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`); +}; + +/* global BigInt */ + +const boolStringify = ({ + value +}) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr; + +const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value); + +function intResolve(sign, src, radix) { + let str = src.replace(/_/g, ''); + + if (resolveSeq$1.intOptions.asBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + + case 8: + str = `0o${str}`; + break; + + case 16: + str = `0x${str}`; + break; + } + + const n = BigInt(str); + return sign === '-' ? BigInt(-1) * n : n; + } + + const n = parseInt(str, radix); + return sign === '-' ? -1 * n : n; +} + +function intStringify(node, radix, prefix) { + const { + value + } = node; + + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? '-' + prefix + str.substr(1) : prefix + str; + } + + return resolveSeq$1.stringifyNumber(node); +} + +const yaml11 = failsafe.concat([{ + identify: value => value == null, + createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => null, + options: resolveSeq$1.nullOptions, + stringify: () => resolveSeq$1.nullOptions.nullStr +}, { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => true, + options: resolveSeq$1.boolOptions, + stringify: boolStringify +}, { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i, + resolve: () => false, + options: resolveSeq$1.boolOptions, + stringify: boolStringify +}, { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'BIN', + test: /^([-+]?)0b([0-1_]+)$/, + resolve: (str, sign, bin) => intResolve(sign, bin, 2), + stringify: node => intStringify(node, 2, '0b') +}, { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'OCT', + test: /^([-+]?)0([0-7_]+)$/, + resolve: (str, sign, oct) => intResolve(sign, oct, 8), + stringify: node => intStringify(node, 8, '0') +}, { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^([-+]?)([0-9][0-9_]*)$/, + resolve: (str, sign, abs) => intResolve(sign, abs, 10), + stringify: resolveSeq$1.stringifyNumber +}, { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'HEX', + test: /^([-+]?)0x([0-9a-fA-F_]+)$/, + resolve: (str, sign, hex) => intResolve(sign, hex, 16), + stringify: node => intStringify(node, 16, '0x') +}, { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.inf|(\.nan))$/i, + resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: resolveSeq$1.stringifyNumber +}, { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'EXP', + test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: str => parseFloat(str.replace(/_/g, '')), + stringify: ({ + value + }) => Number(value).toExponential() +}, { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/, + + resolve(str, frac) { + const node = new resolveSeq$1.Scalar(parseFloat(str.replace(/_/g, ''))); + + if (frac) { + const f = frac.replace(/_/g, ''); + if (f[f.length - 1] === '0') node.minFractionDigits = f.length; + } + + return node; + }, + + stringify: resolveSeq$1.stringifyNumber +}], warnings$1.binary, warnings$1.omap, warnings$1.pairs, warnings$1.set, warnings$1.intTime, warnings$1.floatTime, warnings$1.timestamp); + +const schemas = { + core: core$2, + failsafe, + json, + yaml11 +}; +const tags = { + binary: warnings$1.binary, + bool: boolObj, + float: floatObj, + floatExp: expObj, + floatNaN: nanObj, + floatTime: warnings$1.floatTime, + int: intObj, + intHex: hexObj, + intOct: octObj, + intTime: warnings$1.intTime, + map, + null: nullObj, + omap: warnings$1.omap, + pairs: warnings$1.pairs, + seq, + set: warnings$1.set, + timestamp: warnings$1.timestamp +}; + +function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter(t => t.tag === tagName); + const tagObj = match.find(t => !t.format) || match[0]; + if (!tagObj) throw new Error(`Tag ${tagName} not found`); + return tagObj; + } // TODO: deprecate/remove class check + + + return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format); +} + +function createNode$1(value, tagName, ctx) { + if (value instanceof resolveSeq$1.Node) return value; + const { + defaultPrefix, + onTagObj, + prevObjects, + schema, + wrapScalars + } = ctx; + if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema.tags); + + if (!tagObj) { + if (typeof value.toJSON === 'function') value = value.toJSON(); + if (!value || typeof value !== 'object') return wrapScalars ? new resolveSeq$1.Scalar(value) : value; + tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map; + } + + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } // Detect duplicate references to the same object & use Alias nodes for all + // after first. The `obj` wrapper allows for circular references to resolve. + + + const obj = { + value: undefined, + node: undefined + }; + + if (value && typeof value === 'object' && prevObjects) { + const prev = prevObjects.get(value); + + if (prev) { + const alias = new resolveSeq$1.Alias(prev); // leaves source dirty; must be cleaned by caller + + ctx.aliasNodes.push(alias); // defined along with prevObjects + + return alias; + } + + obj.value = value; + prevObjects.set(value, obj); + } + + obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq$1.Scalar(value) : value; + if (tagName && obj.node instanceof resolveSeq$1.Node) obj.node.tag = tagName; + return obj.node; +} + +function getSchemaTags(schemas, knownTags, customTags, schemaId) { + let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11' + + if (!tags) { + const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', '); + throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`); + } + + if (Array.isArray(customTags)) { + for (const tag of customTags) tags = tags.concat(tag); + } else if (typeof customTags === 'function') { + tags = customTags(tags.slice()); + } + + for (let i = 0; i < tags.length; ++i) { + const tag = tags[i]; + + if (typeof tag === 'string') { + const tagObj = knownTags[tag]; + + if (!tagObj) { + const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', '); + throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`); + } + + tags[i] = tagObj; + } + } + + return tags; +} + +const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; + +class Schema$2 { + // TODO: remove in v2 + // TODO: remove in v2 + constructor({ + customTags, + merge, + schema, + sortMapEntries, + tags: deprecatedCustomTags + }) { + this.merge = !!merge; + this.name = schema; + this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null; + if (!customTags && deprecatedCustomTags) warnings$1.warnOptionDeprecation('tags', 'customTags'); + this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema); + } + + createNode(value, wrapScalars, tagName, ctx) { + const baseCtx = { + defaultPrefix: Schema$2.defaultPrefix, + schema: this, + wrapScalars + }; + const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx; + return createNode$1(value, tagName, createCtx); + } + + createPair(key, value, ctx) { + if (!ctx) ctx = { + wrapScalars: true + }; + const k = this.createNode(key, ctx.wrapScalars, null, ctx); + const v = this.createNode(value, ctx.wrapScalars, null, ctx); + return new resolveSeq$1.Pair(k, v); + } + +} + +PlainValue$2._defineProperty(Schema$2, "defaultPrefix", PlainValue$2.defaultTagPrefix); + +PlainValue$2._defineProperty(Schema$2, "defaultTags", PlainValue$2.defaultTags); + +Schema88e323a7.Schema = Schema$2; + +var PlainValue$1 = PlainValueEc8e588e; +var resolveSeq = resolveSeqD03cb037; +var Schema$1 = Schema88e323a7; + +const defaultOptions$1 = { + anchorPrefix: 'a', + customTags: null, + indent: 2, + indentSeq: true, + keepCstNodes: false, + keepNodeTypes: true, + keepBlobsInJSON: true, + mapAsMap: false, + maxAliasCount: 100, + prettyErrors: false, + // TODO Set true in v2 + simpleKeys: false, + version: '1.2' +}; +const scalarOptions = { + get binary() { + return resolveSeq.binaryOptions; + }, + + set binary(opt) { + Object.assign(resolveSeq.binaryOptions, opt); + }, + + get bool() { + return resolveSeq.boolOptions; + }, + + set bool(opt) { + Object.assign(resolveSeq.boolOptions, opt); + }, + + get int() { + return resolveSeq.intOptions; + }, + + set int(opt) { + Object.assign(resolveSeq.intOptions, opt); + }, + + get null() { + return resolveSeq.nullOptions; + }, + + set null(opt) { + Object.assign(resolveSeq.nullOptions, opt); + }, + + get str() { + return resolveSeq.strOptions; + }, + + set str(opt) { + Object.assign(resolveSeq.strOptions, opt); + } + +}; +const documentOptions = { + '1.0': { + schema: 'yaml-1.1', + merge: true, + tagPrefixes: [{ + handle: '!', + prefix: PlainValue$1.defaultTagPrefix + }, { + handle: '!!', + prefix: 'tag:private.yaml.org,2002:' + }] + }, + 1.1: { + schema: 'yaml-1.1', + merge: true, + tagPrefixes: [{ + handle: '!', + prefix: '!' + }, { + handle: '!!', + prefix: PlainValue$1.defaultTagPrefix + }] + }, + 1.2: { + schema: 'core', + merge: false, + tagPrefixes: [{ + handle: '!', + prefix: '!' + }, { + handle: '!!', + prefix: PlainValue$1.defaultTagPrefix + }] + } +}; + +function stringifyTag(doc, tag) { + if ((doc.version || doc.options.version) === '1.0') { + const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/); + if (priv) return '!' + priv[1]; + const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/); + return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`; + } + + let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0); + + if (!p) { + const dtp = doc.getDefaults().tagPrefixes; + p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0); + } + + if (!p) return tag[0] === '!' ? tag : `!<${tag}>`; + const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({ + '!': '%21', + ',': '%2C', + '[': '%5B', + ']': '%5D', + '{': '%7B', + '}': '%7D' + })[ch]); + return p.handle + suffix; +} + +function getTagObject(tags, item) { + if (item instanceof resolveSeq.Alias) return resolveSeq.Alias; + + if (item.tag) { + const match = tags.filter(t => t.tag === item.tag); + if (match.length > 0) return match.find(t => t.format === item.format) || match[0]; + } + + let tagObj, obj; + + if (item instanceof resolveSeq.Scalar) { + obj = item.value; // TODO: deprecate/remove class check + + const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class); + tagObj = match.find(t => t.format === item.format) || match.find(t => !t.format); + } else { + obj = item; + tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass); + } + + if (!tagObj) { + const name = obj && obj.constructor ? obj.constructor.name : typeof obj; + throw new Error(`Tag not resolved for ${name} value`); + } + + return tagObj; +} // needs to be called before value stringifier to allow for circular anchor refs + + +function stringifyProps(node, tagObj, { + anchors, + doc +}) { + const props = []; + const anchor = doc.anchors.getName(node); + + if (anchor) { + anchors[anchor] = node; + props.push(`&${anchor}`); + } + + if (node.tag) { + props.push(stringifyTag(doc, node.tag)); + } else if (!tagObj.default) { + props.push(stringifyTag(doc, tagObj.tag)); + } + + return props.join(' '); +} + +function stringify$2(item, ctx, onComment, onChompKeep) { + const { + anchors, + schema + } = ctx.doc; + let tagObj; + + if (!(item instanceof resolveSeq.Node)) { + const createCtx = { + aliasNodes: [], + onTagObj: o => tagObj = o, + prevObjects: new Map() + }; + item = schema.createNode(item, true, null, createCtx); + + for (const alias of createCtx.aliasNodes) { + alias.source = alias.source.node; + let name = anchors.getName(alias.source); + + if (!name) { + name = anchors.newName(); + anchors.map[name] = alias.source; + } + } + } + + if (item instanceof resolveSeq.Pair) return item.toString(ctx, onComment, onChompKeep); + if (!tagObj) tagObj = getTagObject(schema.tags, item); + const props = stringifyProps(item, tagObj, ctx); + if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1; + const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq.Scalar ? resolveSeq.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep); + if (!props) return str; + return item instanceof resolveSeq.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`; +} + +class Anchors { + static validAnchorNode(node) { + return node instanceof resolveSeq.Scalar || node instanceof resolveSeq.YAMLSeq || node instanceof resolveSeq.YAMLMap; + } + + constructor(prefix) { + PlainValue$1._defineProperty(this, "map", Object.create(null)); + + this.prefix = prefix; + } + + createAlias(node, name) { + this.setAnchor(node, name); + return new resolveSeq.Alias(node); + } + + createMergePair(...sources) { + const merge = new resolveSeq.Merge(); + merge.value.items = sources.map(s => { + if (s instanceof resolveSeq.Alias) { + if (s.source instanceof resolveSeq.YAMLMap) return s; + } else if (s instanceof resolveSeq.YAMLMap) { + return this.createAlias(s); + } + + throw new Error('Merge sources must be Map nodes or their Aliases'); + }); + return merge; + } + + getName(node) { + const { + map + } = this; + return Object.keys(map).find(a => map[a] === node); + } + + getNames() { + return Object.keys(this.map); + } + + getNode(name) { + return this.map[name]; + } + + newName(prefix) { + if (!prefix) prefix = this.prefix; + const names = Object.keys(this.map); + + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!names.includes(name)) return name; + } + } // During parsing, map & aliases contain CST nodes + + + resolveNodes() { + const { + map, + _cstAliases + } = this; + Object.keys(map).forEach(a => { + map[a] = map[a].resolved; + }); + + _cstAliases.forEach(a => { + a.source = a.source.resolved; + }); + + delete this._cstAliases; + } + + setAnchor(node, name) { + if (node != null && !Anchors.validAnchorNode(node)) { + throw new Error('Anchors may only be set for Scalar, Seq and Map nodes'); + } + + if (name && /[\x00-\x19\s,[\]{}]/.test(name)) { + throw new Error('Anchor names must not contain whitespace or control characters'); + } + + const { + map + } = this; + const prev = node && Object.keys(map).find(a => map[a] === node); + + if (prev) { + if (!name) { + return prev; + } else if (prev !== name) { + delete map[prev]; + map[name] = node; + } + } else { + if (!name) { + if (!node) return null; + name = this.newName(); + } + + map[name] = node; + } + + return name; + } + +} + +const visit$1 = (node, tags) => { + if (node && typeof node === 'object') { + const { + tag + } = node; + + if (node instanceof resolveSeq.Collection) { + if (tag) tags[tag] = true; + node.items.forEach(n => visit$1(n, tags)); + } else if (node instanceof resolveSeq.Pair) { + visit$1(node.key, tags); + visit$1(node.value, tags); + } else if (node instanceof resolveSeq.Scalar) { + if (tag) tags[tag] = true; + } + } + + return tags; +}; + +const listTagNames = node => Object.keys(visit$1(node, {})); + +function parseContents(doc, contents) { + const comments = { + before: [], + after: [] + }; + let body = undefined; + let spaceBefore = false; + + for (const node of contents) { + if (node.valueRange) { + if (body !== undefined) { + const msg = 'Document contains trailing content not separated by a ... or --- line'; + doc.errors.push(new PlainValue$1.YAMLSyntaxError(node, msg)); + break; + } + + const res = resolveSeq.resolveNode(doc, node); + + if (spaceBefore) { + res.spaceBefore = true; + spaceBefore = false; + } + + body = res; + } else if (node.comment !== null) { + const cc = body === undefined ? comments.before : comments.after; + cc.push(node.comment); + } else if (node.type === PlainValue$1.Type.BLANK_LINE) { + spaceBefore = true; + + if (body === undefined && comments.before.length > 0 && !doc.commentBefore) { + // space-separated comments at start are parsed as document comments + doc.commentBefore = comments.before.join('\n'); + comments.before = []; + } + } + } + + doc.contents = body || null; + + if (!body) { + doc.comment = comments.before.concat(comments.after).join('\n') || null; + } else { + const cb = comments.before.join('\n'); + + if (cb) { + const cbNode = body instanceof resolveSeq.Collection && body.items[0] ? body.items[0] : body; + cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb; + } + + doc.comment = comments.after.join('\n') || null; + } +} + +function resolveTagDirective({ + tagPrefixes +}, directive) { + const [handle, prefix] = directive.parameters; + + if (!handle || !prefix) { + const msg = 'Insufficient parameters given for %TAG directive'; + throw new PlainValue$1.YAMLSemanticError(directive, msg); + } + + if (tagPrefixes.some(p => p.handle === handle)) { + const msg = 'The %TAG directive must only be given at most once per handle in the same document.'; + throw new PlainValue$1.YAMLSemanticError(directive, msg); + } + + return { + handle, + prefix + }; +} + +function resolveYamlDirective(doc, directive) { + let [version] = directive.parameters; + if (directive.name === 'YAML:1.0') version = '1.0'; + + if (!version) { + const msg = 'Insufficient parameters given for %YAML directive'; + throw new PlainValue$1.YAMLSemanticError(directive, msg); + } + + if (!documentOptions[version]) { + const v0 = doc.version || doc.options.version; + const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`; + doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg)); + } + + return version; +} + +function parseDirectives(doc, directives, prevDoc) { + const directiveComments = []; + let hasDirectives = false; + + for (const directive of directives) { + const { + comment, + name + } = directive; + + switch (name) { + case 'TAG': + try { + doc.tagPrefixes.push(resolveTagDirective(doc, directive)); + } catch (error) { + doc.errors.push(error); + } + + hasDirectives = true; + break; + + case 'YAML': + case 'YAML:1.0': + if (doc.version) { + const msg = 'The %YAML directive must only be given at most once per document.'; + doc.errors.push(new PlainValue$1.YAMLSemanticError(directive, msg)); + } + + try { + doc.version = resolveYamlDirective(doc, directive); + } catch (error) { + doc.errors.push(error); + } + + hasDirectives = true; + break; + + default: + if (name) { + const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`; + doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg)); + } + + } + + if (comment) directiveComments.push(comment); + } + + if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) { + const copyTagPrefix = ({ + handle, + prefix + }) => ({ + handle, + prefix + }); + + doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix); + doc.version = prevDoc.version; + } + + doc.commentBefore = directiveComments.join('\n') || null; +} + +function assertCollection(contents) { + if (contents instanceof resolveSeq.Collection) return true; + throw new Error('Expected a YAML collection as document contents'); +} + +class Document$2 { + constructor(options) { + this.anchors = new Anchors(options.anchorPrefix); + this.commentBefore = null; + this.comment = null; + this.contents = null; + this.directivesEndMarker = null; + this.errors = []; + this.options = options; + this.schema = null; + this.tagPrefixes = []; + this.version = null; + this.warnings = []; + } + + add(value) { + assertCollection(this.contents); + return this.contents.add(value); + } + + addIn(path, value) { + assertCollection(this.contents); + this.contents.addIn(path, value); + } + + delete(key) { + assertCollection(this.contents); + return this.contents.delete(key); + } + + deleteIn(path) { + if (resolveSeq.isEmptyPath(path)) { + if (this.contents == null) return false; + this.contents = null; + return true; + } + + assertCollection(this.contents); + return this.contents.deleteIn(path); + } + + getDefaults() { + return Document$2.defaults[this.version] || Document$2.defaults[this.options.version] || {}; + } + + get(key, keepScalar) { + return this.contents instanceof resolveSeq.Collection ? this.contents.get(key, keepScalar) : undefined; + } + + getIn(path, keepScalar) { + if (resolveSeq.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq.Scalar ? this.contents.value : this.contents; + return this.contents instanceof resolveSeq.Collection ? this.contents.getIn(path, keepScalar) : undefined; + } + + has(key) { + return this.contents instanceof resolveSeq.Collection ? this.contents.has(key) : false; + } + + hasIn(path) { + if (resolveSeq.isEmptyPath(path)) return this.contents !== undefined; + return this.contents instanceof resolveSeq.Collection ? this.contents.hasIn(path) : false; + } + + set(key, value) { + assertCollection(this.contents); + this.contents.set(key, value); + } + + setIn(path, value) { + if (resolveSeq.isEmptyPath(path)) this.contents = value;else { + assertCollection(this.contents); + this.contents.setIn(path, value); + } + } + + setSchema(id, customTags) { + if (!id && !customTags && this.schema) return; + if (typeof id === 'number') id = id.toFixed(1); + + if (id === '1.0' || id === '1.1' || id === '1.2') { + if (this.version) this.version = id;else this.options.version = id; + delete this.options.schema; + } else if (id && typeof id === 'string') { + this.options.schema = id; + } + + if (Array.isArray(customTags)) this.options.customTags = customTags; + const opt = Object.assign({}, this.getDefaults(), this.options); + this.schema = new Schema$1.Schema(opt); + } + + parse(node, prevDoc) { + if (this.options.keepCstNodes) this.cstNode = node; + if (this.options.keepNodeTypes) this.type = 'DOCUMENT'; + const { + directives = [], + contents = [], + directivesEndMarker, + error, + valueRange + } = node; + + if (error) { + if (!error.source) error.source = this; + this.errors.push(error); + } + + parseDirectives(this, directives, prevDoc); + if (directivesEndMarker) this.directivesEndMarker = true; + this.range = valueRange ? [valueRange.start, valueRange.end] : null; + this.setSchema(); + this.anchors._cstAliases = []; + parseContents(this, contents); + this.anchors.resolveNodes(); + + if (this.options.prettyErrors) { + for (const error of this.errors) if (error instanceof PlainValue$1.YAMLError) error.makePretty(); + + for (const warn of this.warnings) if (warn instanceof PlainValue$1.YAMLError) warn.makePretty(); + } + + return this; + } + + listNonDefaultTags() { + return listTagNames(this.contents).filter(t => t.indexOf(Schema$1.Schema.defaultPrefix) !== 0); + } + + setTagPrefix(handle, prefix) { + if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !'); + + if (prefix) { + const prev = this.tagPrefixes.find(p => p.handle === handle); + if (prev) prev.prefix = prefix;else this.tagPrefixes.push({ + handle, + prefix + }); + } else { + this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle); + } + } + + toJSON(arg, onAnchor) { + const { + keepBlobsInJSON, + mapAsMap, + maxAliasCount + } = this.options; + const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq.Scalar)); + const ctx = { + doc: this, + indentStep: ' ', + keep, + mapAsMap: keep && !!mapAsMap, + maxAliasCount, + stringify: stringify$2 // Requiring directly in Pair would create circular dependencies + + }; + const anchorNames = Object.keys(this.anchors.map); + if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], { + alias: [], + aliasCount: 0, + count: 1 + }])); + const res = resolveSeq.toJSON(this.contents, arg, ctx); + if (typeof onAnchor === 'function' && ctx.anchors) for (const { + count, + res + } of ctx.anchors.values()) onAnchor(res, count); + return res; + } + + toString() { + if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified'); + const indentSize = this.options.indent; + + if (!Number.isInteger(indentSize) || indentSize <= 0) { + const s = JSON.stringify(indentSize); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + + this.setSchema(); + const lines = []; + let hasDirectives = false; + + if (this.version) { + let vd = '%YAML 1.2'; + + if (this.schema.name === 'yaml-1.1') { + if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1'; + } + + lines.push(vd); + hasDirectives = true; + } + + const tagNames = this.listNonDefaultTags(); + this.tagPrefixes.forEach(({ + handle, + prefix + }) => { + if (tagNames.some(t => t.indexOf(prefix) === 0)) { + lines.push(`%TAG ${handle} ${prefix}`); + hasDirectives = true; + } + }); + if (hasDirectives || this.directivesEndMarker) lines.push('---'); + + if (this.commentBefore) { + if (hasDirectives || !this.directivesEndMarker) lines.unshift(''); + lines.unshift(this.commentBefore.replace(/^/gm, '#')); + } + + const ctx = { + anchors: Object.create(null), + doc: this, + indent: '', + indentStep: ' '.repeat(indentSize), + stringify: stringify$2 // Requiring directly in nodes would create circular dependencies + + }; + let chompKeep = false; + let contentComment = null; + + if (this.contents) { + if (this.contents instanceof resolveSeq.Node) { + if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push(''); + if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment + + ctx.forceBlockIndent = !!this.comment; + contentComment = this.contents.comment; + } + + const onChompKeep = contentComment ? null : () => chompKeep = true; + const body = stringify$2(this.contents, ctx, () => contentComment = null, onChompKeep); + lines.push(resolveSeq.addComment(body, '', contentComment)); + } else if (this.contents !== undefined) { + lines.push(stringify$2(this.contents, ctx)); + } + + if (this.comment) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push(''); + lines.push(this.comment.replace(/^/gm, '#')); + } + + return lines.join('\n') + '\n'; + } + +} + +PlainValue$1._defineProperty(Document$2, "defaults", documentOptions); + +Document9b4560a1.Document = Document$2; +Document9b4560a1.defaultOptions = defaultOptions$1; +Document9b4560a1.scalarOptions = scalarOptions; + +var parseCst = parseCst$1; +var Document$1 = Document9b4560a1; +var Schema = Schema88e323a7; +var PlainValue = PlainValueEc8e588e; +var warnings = warnings1000a372; + + +function createNode(value, wrapScalars = true, tag) { + if (tag === undefined && typeof wrapScalars === 'string') { + tag = wrapScalars; + wrapScalars = true; + } + + const options = Object.assign({}, Document$1.Document.defaults[Document$1.defaultOptions.version], Document$1.defaultOptions); + const schema = new Schema.Schema(options); + return schema.createNode(value, wrapScalars, tag); +} + +class Document extends Document$1.Document { + constructor(options) { + super(Object.assign({}, Document$1.defaultOptions, options)); + } + +} + +function parseAllDocuments(src, options) { + const stream = []; + let prev; + + for (const cstDoc of parseCst.parse(src)) { + const doc = new Document(options); + doc.parse(cstDoc, prev); + stream.push(doc); + prev = doc; + } + + return stream; +} + +function parseDocument(src, options) { + const cst = parseCst.parse(src); + const doc = new Document(options).parse(cst[0]); + + if (cst.length > 1) { + const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()'; + doc.errors.unshift(new PlainValue.YAMLSemanticError(cst[1], errMsg)); + } + + return doc; +} + +function parse$f(src, options) { + const doc = parseDocument(src, options); + doc.warnings.forEach(warning => warnings.warn(warning)); + if (doc.errors.length > 0) throw doc.errors[0]; + return doc.toJSON(); +} + +function stringify$1(value, options) { + const doc = new Document(options); + doc.contents = value; + return String(doc); +} + +const YAML = { + createNode, + defaultOptions: Document$1.defaultOptions, + Document, + parse: parse$f, + parseAllDocuments, + parseCST: parseCst.parse, + parseDocument, + scalarOptions: Document$1.scalarOptions, + stringify: stringify$1 +}; + +dist$2.YAML = YAML; + +var yaml$1 = dist$2.YAML; + +var importCwd = {exports: {}}; + +var importFrom$1 = {exports: {}}; + +var resolveFrom$2 = {exports: {}}; + +const path$l = path__default; +const Module = require$$0__default$5; +const fs$m = fs__default; + +const resolveFrom$1 = (fromDirectory, moduleId, silent) => { + if (typeof fromDirectory !== 'string') { + throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``); + } + + if (typeof moduleId !== 'string') { + throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``); + } + + try { + fromDirectory = fs$m.realpathSync(fromDirectory); + } catch (error) { + if (error.code === 'ENOENT') { + fromDirectory = path$l.resolve(fromDirectory); + } else if (silent) { + return; + } else { + throw error; + } + } + + const fromFile = path$l.join(fromDirectory, 'noop.js'); + + const resolveFileName = () => Module._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: Module._nodeModulePaths(fromDirectory) + }); + + if (silent) { + try { + return resolveFileName(); + } catch (error) { + return; + } + } + + return resolveFileName(); +}; + +resolveFrom$2.exports = (fromDirectory, moduleId) => resolveFrom$1(fromDirectory, moduleId); +resolveFrom$2.exports.silent = (fromDirectory, moduleId) => resolveFrom$1(fromDirectory, moduleId, true); + +const resolveFrom = resolveFrom$2.exports; + +importFrom$1.exports = (fromDirectory, moduleId) => eval('require')(resolveFrom(fromDirectory, moduleId)); + +importFrom$1.exports.silent = (fromDirectory, moduleId) => { + try { + return eval('require')(resolveFrom(fromDirectory, moduleId)); + } catch (_) {} +}; + +const importFrom = importFrom$1.exports; + +importCwd.exports = moduleId => importFrom(process.cwd(), moduleId); +importCwd.exports.silent = moduleId => importFrom.silent(process.cwd(), moduleId); + +const req$1 = importCwd.exports; + +/** + * Load Options + * + * @private + * @method options + * + * @param {Object} config PostCSS Config + * + * @return {Object} options PostCSS Options + */ +const options = (config, file) => { + if (config.parser && typeof config.parser === 'string') { + try { + config.parser = req$1(config.parser); + } catch (err) { + throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`) + } + } + + if (config.syntax && typeof config.syntax === 'string') { + try { + config.syntax = req$1(config.syntax); + } catch (err) { + throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`) + } + } + + if (config.stringifier && typeof config.stringifier === 'string') { + try { + config.stringifier = req$1(config.stringifier); + } catch (err) { + throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`) + } + } + + if (config.plugins) { + delete config.plugins; + } + + return config +}; + +var options_1 = options; + +const req = importCwd.exports; + +/** + * Plugin Loader + * + * @private + * @method load + * + * @param {String} plugin PostCSS Plugin Name + * @param {Object} options PostCSS Plugin Options + * + * @return {Function} PostCSS Plugin + */ +const load$1 = (plugin, options, file) => { + try { + if ( + options === null || + options === undefined || + Object.keys(options).length === 0 + ) { + return req(plugin) + } else { + return req(plugin)(options) + } + } catch (err) { + throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`) + } +}; + +/** + * Load Plugins + * + * @private + * @method plugins + * + * @param {Object} config PostCSS Config Plugins + * + * @return {Array} plugins PostCSS Plugins + */ +const plugins = (config, file) => { + let plugins = []; + + if (Array.isArray(config.plugins)) { + plugins = config.plugins.filter(Boolean); + } else { + plugins = Object.keys(config.plugins) + .filter((plugin) => { + return config.plugins[plugin] !== false ? plugin : '' + }) + .map((plugin) => { + return load$1(plugin, config.plugins[plugin], file) + }); + } + + if (plugins.length && plugins.length > 0) { + plugins.forEach((plugin, i) => { + if (plugin.default) { + plugin = plugin.default; + } + + if (plugin.postcss === true) { + plugin = plugin(); + } else if (plugin.postcss) { + plugin = plugin.postcss; + } + + if ( + // eslint-disable-next-line + !( + (typeof plugin === 'object' && Array.isArray(plugin.plugins)) || + (typeof plugin === 'object' && plugin.postcssPlugin) || + (typeof plugin === 'function') + ) + ) { + throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`) + } + }); + } + + return plugins +}; + +var plugins_1 = plugins; + +var dist$1 = {}; + +var sourceMapSupport = {exports: {}}; + +var sourceMap = {}; + +var sourceMapConsumer$1 = {}; + +var util$9 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +(function (exports) { +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } + throw new Error('"' + aName + '" is a required argument.'); + +} +exports.getArg = getArg; + +const urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +const dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + const match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + let url = ""; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ":"; + } + url += "//"; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + "@"; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port; + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +const MAX_CACHED_INPUTS = 32; + +/** + * Takes some function `f(input) -> result` and returns a memoized version of + * `f`. + * + * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The + * memoization is a dumb-simple, linear least-recently-used cache. + */ +function lruMemoize(f) { + const cache = []; + + return function(input) { + for (let i = 0; i < cache.length; i++) { + if (cache[i].input === input) { + const temp = cache[0]; + cache[0] = cache[i]; + cache[i] = temp; + return cache[0].result; + } + } + + const result = f(input); + + cache.unshift({ + input, + result, + }); + + if (cache.length > MAX_CACHED_INPUTS) { + cache.pop(); + } + + return result; + }; +} + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +const normalize = lruMemoize(function normalize(aPath) { + let path = aPath; + const url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + const isAbsolute = exports.isAbsolute(path); + + // Split the path into parts between `/` characters. This is much faster than + // using `.split(/\/+/g)`. + const parts = []; + let start = 0; + let i = 0; + while (true) { + start = i; + i = path.indexOf("/", start); + if (i === -1) { + parts.push(path.slice(start)); + break; + } else { + parts.push(path.slice(start, i)); + while (i < path.length && path[i] === "/") { + i++; + } + } + } + + let up = 0; + for (i = parts.length - 1; i >= 0; i--) { + const part = parts[i]; + if (part === ".") { + parts.splice(i, 1); + } else if (part === "..") { + up++; + } else if (up > 0) { + if (part === "") { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join("/"); + + if (path === "") { + path = isAbsolute ? "/" : "."; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +}); +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + const aPathUrl = urlParse(aPath); + const aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || "/"; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + const joined = aPath.charAt(0) === "/" + ? aPath + : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function(aPath) { + return aPath.charAt(0) === "/" || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ""); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + let level = 0; + while (aPath.indexOf(aRoot + "/") !== 0) { + const index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +const supportsNullProto = (function() { + const obj = Object.create(null); + return !("__proto__" in obj); +}()); + +function identity(s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return "$" + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + const length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + /* eslint-disable no-multi-spaces */ + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + /* eslint-enable no-multi-spaces */ + + for (let i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + let cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + let cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + let cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, "")); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ""; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") { + sourceRoot += "/"; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + const parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + const index = parsed.path.lastIndexOf("/"); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; +}(util$9)); + +var binarySearch$3 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +(function (exports) { +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + const mid = Math.floor((aHigh - aLow) / 2) + aLow; + const cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } + return mid; + } + + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } + return aLow < 0 ? -1 : aLow; +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + let index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; +}(binarySearch$3)); + +var arraySet$1 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +class ArraySet$4 { + constructor() { + this._array = []; + this._set = new Map(); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + static fromArray(aArray, aAllowDuplicates) { + const set = new ArraySet$4(); + for (let i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + } + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + size() { + return this._set.size; + } + + /** + * Add the given string to this set. + * + * @param String aStr + */ + add(aStr, aAllowDuplicates) { + const isDuplicate = this.has(aStr); + const idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set.set(aStr, idx); + } + } + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + has(aStr) { + return this._set.has(aStr); + } + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + indexOf(aStr) { + const idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + throw new Error('"' + aStr + '" is not in the set.'); + } + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error("No element indexed by " + aIdx); + } + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + toArray() { + return this._array.slice(); + } +} +arraySet$1.ArraySet = ArraySet$4; + +var readWasm$2 = {exports: {}}; + +// Node version of reading a wasm file into an array buffer. +const fs$l = fs__default; +const path$k = path__default; + +readWasm$2.exports = function readWasm() { + return new Promise((resolve, reject) => { + const wasmPath = path$k.join(__dirname, "mappings.wasm"); + fs$l.readFile(wasmPath, null, (error, data) => { + if (error) { + reject(error); + return; + } + + resolve(data.buffer); + }); + }); +}; +readWasm$2.exports.sync = function readWasmSync() { + const wasmPath = path$k.join(__dirname, "mappings.wasm"); + return fs$l.readFileSync(wasmPath).buffer; +}; + +readWasm$2.exports.initialize = _ => { + console.debug("SourceMapConsumer.initialize is a no-op when running in node.js"); +}; + +var wasm$1 = {exports: {}}; + +const readWasm$1 = readWasm$2.exports; + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping$1() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.lastGeneratedColumn = null; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +let cachedWasm = null; +let cachedWasmSync = null; + +wasm$1.exports = async function wasm() { + if (cachedWasm) { + return cachedWasm; + } + + // At every step of the way, if a sync load already succeeded, abort and return + // the sync-loaded module. + cachedWasm = async () => { + try { + const callbackStack = []; + + const buffer = await readWasm$1(); + if (cachedWasmSync) return cachedWasmSync; + const Wasm = await WebAssembly.instantiate(buffer, getImportObject({callbackStack})); + if (cachedWasmSync) return cachedWasmSync; + + cachedWasmSync = { + exports: Wasm.instance.exports, + withMappingCallback: (mappingCallback, f) => { + callbackStack.push(mappingCallback); + try { + f(); + } finally { + callbackStack.pop(); + } + } + }; + } catch (e) { + if (cachedWasmSync) return cachedWasmSync; + cachedWasm = null; + throw e; + } + return cachedWasmSync; + }; + + return cachedWasm; +}; + +wasm$1.exports.sync = function wasmSync() { + if (cachedWasmSync) { + return cachedWasmSync; + } + + const callbackStack = []; + + try { + + const cachedWasmBuffer = readWasm$1.sync(); + const wasmModule = new WebAssembly.Module(cachedWasmBuffer); + const Wasm = new WebAssembly.Instance(wasmModule, getImportObject({callbackStack})); + + cachedWasmSync = { + exports: Wasm.exports, + withMappingCallback: (mappingCallback, f) => { + callbackStack.push(mappingCallback); + try { + f(); + } finally { + callbackStack.pop(); + } + } + }; + } catch (e) { + cachedWasmSync = null; + throw e; + } + + return cachedWasmSync; +}; + +function getImportObject({callbackStack}) { + return { + env: { + mapping_callback( + generatedLine, + generatedColumn, + + hasLastGeneratedColumn, + lastGeneratedColumn, + + hasOriginal, + source, + originalLine, + originalColumn, + + hasName, + name + ) { + const mapping = new Mapping$1(); + // JS uses 1-based line numbers, wasm uses 0-based. + mapping.generatedLine = generatedLine + 1; + mapping.generatedColumn = generatedColumn; + + if (hasLastGeneratedColumn) { + // JS uses inclusive last generated column, wasm uses exclusive. + mapping.lastGeneratedColumn = lastGeneratedColumn - 1; + } + + if (hasOriginal) { + mapping.source = source; + // JS uses 1-based line numbers, wasm uses 0-based. + mapping.originalLine = originalLine + 1; + mapping.originalColumn = originalColumn; + + if (hasName) { + mapping.name = name; + } + } + + callbackStack[callbackStack.length - 1](mapping); + }, + + start_all_generated_locations_for() { console.time("all_generated_locations_for"); }, + end_all_generated_locations_for() { console.timeEnd("all_generated_locations_for"); }, + + start_compute_column_spans() { console.time("compute_column_spans"); }, + end_compute_column_spans() { console.timeEnd("compute_column_spans"); }, + + start_generated_location_for() { console.time("generated_location_for"); }, + end_generated_location_for() { console.timeEnd("generated_location_for"); }, + + start_original_location_for() { console.time("original_location_for"); }, + end_original_location_for() { console.timeEnd("original_location_for"); }, + + start_parse_mappings() { console.time("parse_mappings"); }, + end_parse_mappings() { console.timeEnd("parse_mappings"); }, + + start_sort_by_generated_location() { console.time("sort_by_generated_location"); }, + end_sort_by_generated_location() { console.timeEnd("sort_by_generated_location"); }, + + start_sort_by_original_location() { console.time("sort_by_original_location"); }, + end_sort_by_original_location() { console.timeEnd("sort_by_original_location"); }, + } + }; +} + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +const util$8 = util$9; +const binarySearch$2 = binarySearch$3; +const ArraySet$3 = arraySet$1.ArraySet; +const readWasm = readWasm$2.exports; +const wasm = wasm$1.exports; + +const INTERNAL = Symbol("smcInternal"); + +class SourceMapConsumer$2 { + constructor(aSourceMap, aSourceMapURL) { + if (aSourceMap === INTERNAL) return this; + return _factory(aSourceMap, aSourceMapURL); + } + + static initialize(opts) { + readWasm.initialize(opts["lib/mappings.wasm"]); + } + + static fromSourceMap(aSourceMap, aSourceMapURL) { + return _factoryBSM(aSourceMap, aSourceMapURL); + } + + /** + * Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl` + * (see the `SourceMapConsumer` constructor for details. Then, invoke the `async + * function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait + * for `f` to complete, call `destroy` on the consumer, and return `f`'s return + * value. + * + * You must not use the consumer after `f` completes! + * + * By using `with`, you do not have to remember to manually call `destroy` on + * the consumer, since it will be called automatically once `f` completes. + * + * ```js + * const xSquared = await SourceMapConsumer.with( + * myRawSourceMap, + * null, + * async function (consumer) { + * // Use `consumer` inside here and don't worry about remembering + * // to call `destroy`. + * + * const x = await whatever(consumer); + * return x * x; + * } + * ); + * + * // You may not use that `consumer` anymore out here; it has + * // been destroyed. But you can use `xSquared`. + * console.log(xSquared); + * ``` + */ + static async with(rawSourceMap, sourceMapUrl, f) { + // Note: The `acorn` version that `webpack` currently depends on doesn't + // support `async` functions, and the nodes that we support don't all have + // `.finally`. Therefore, this is written a bit more convolutedly than it + // should really be. + + let consumer = null; + try { + consumer = new SourceMapConsumer$2(rawSourceMap, sourceMapUrl); + return await f(consumer); + } finally { + if (consumer) { + consumer.destroy(); + } + } + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + _parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + } + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + eachMapping(aCallback, aContext, aOrder) { + throw new Error("Subclasses must implement eachMapping"); + } + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + allGeneratedPositionsFor(aArgs) { + throw new Error("Subclasses must implement allGeneratedPositionsFor"); + } + + destroy() { + throw new Error("Subclasses must implement destroy"); + } +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer$2.prototype._version = 3; +SourceMapConsumer$2.GENERATED_ORDER = 1; +SourceMapConsumer$2.ORIGINAL_ORDER = 2; + +SourceMapConsumer$2.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer$2.LEAST_UPPER_BOUND = 2; + +sourceMapConsumer$1.SourceMapConsumer = SourceMapConsumer$2; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +class BasicSourceMapConsumer$1 extends SourceMapConsumer$2 { + constructor(aSourceMap, aSourceMapURL) { + super(INTERNAL); + let sourceMap = aSourceMap; + if (typeof aSourceMap === "string") { + sourceMap = util$8.parseSourceMapInput(aSourceMap); + } + + const version = util$8.getArg(sourceMap, "version"); + let sources = util$8.getArg(sourceMap, "sources"); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + const names = util$8.getArg(sourceMap, "names", []); + let sourceRoot = util$8.getArg(sourceMap, "sourceRoot", null); + const sourcesContent = util$8.getArg(sourceMap, "sourcesContent", null); + const mappings = util$8.getArg(sourceMap, "mappings"); + const file = util$8.getArg(sourceMap, "file", null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error("Unsupported version: " + version); + } + + if (sourceRoot) { + sourceRoot = util$8.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util$8.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function(source) { + return sourceRoot && util$8.isAbsolute(sourceRoot) && util$8.isAbsolute(source) + ? util$8.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet$3.fromArray(names.map(String), true); + this._sources = ArraySet$3.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function(s) { + return util$8.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + + this._computedColumnSpans = false; + this._mappingsPtr = 0; + this._wasm = null; + + const w = wasm.sync(); + this._wasm = w; + } + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + _findSourceIndex(aSource) { + let relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util$8.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + for (let i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + } + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + static fromSourceMap(aSourceMap, aSourceMapURL) { + return new BasicSourceMapConsumer$1(aSourceMap.toString()); + } + + get sources() { + return this._absoluteSources.slice(); + } + + _getMappingsPtr() { + if (this._mappingsPtr === 0) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this._mappingsPtr; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + _parseMappings(aStr, aSourceRoot) { + const size = aStr.length; + + const mappingsBufPtr = this._wasm.exports.allocate_mappings(size); + const mappingsBuf = new Uint8Array(this._wasm.exports.memory.buffer, mappingsBufPtr, size); + for (let i = 0; i < size; i++) { + mappingsBuf[i] = aStr.charCodeAt(i); + } + + const mappingsPtr = this._wasm.exports.parse_mappings(mappingsBufPtr); + + if (!mappingsPtr) { + const error = this._wasm.exports.get_last_error(); + let msg = `Error parsing mappings (code ${error}): `; + + // XXX: keep these error codes in sync with `fitzgen/source-map-mappings`. + switch (error) { + case 1: + msg += "the mappings contained a negative line, column, source index, or name index"; + break; + case 2: + msg += "the mappings contained a number larger than 2**32"; + break; + case 3: + msg += "reached EOF while in the middle of parsing a VLQ"; + break; + case 4: + msg += "invalid base 64 character while parsing a VLQ"; + break; + default: + msg += "unknown error code"; + break; + } + + throw new Error(msg); + } + + this._mappingsPtr = mappingsPtr; + } + + eachMapping(aCallback, aContext, aOrder) { + const context = aContext || null; + const order = aOrder || SourceMapConsumer$2.GENERATED_ORDER; + const sourceRoot = this.sourceRoot; + + this._wasm.withMappingCallback( + mapping => { + if (mapping.source !== null) { + mapping.source = this._sources.at(mapping.source); + mapping.source = util$8.computeSourceURL(sourceRoot, mapping.source, this._sourceMapURL); + + if (mapping.name !== null) { + mapping.name = this._names.at(mapping.name); + } + } + + aCallback.call(context, mapping); + }, + () => { + switch (order) { + case SourceMapConsumer$2.GENERATED_ORDER: + this._wasm.exports.by_generated_location(this._getMappingsPtr()); + break; + case SourceMapConsumer$2.ORIGINAL_ORDER: + this._wasm.exports.by_original_location(this._getMappingsPtr()); + break; + default: + throw new Error("Unknown order of iteration."); + } + } + ); + } + + allGeneratedPositionsFor(aArgs) { + let source = util$8.getArg(aArgs, "source"); + const originalLine = util$8.getArg(aArgs, "line"); + const originalColumn = aArgs.column || 0; + + source = this._findSourceIndex(source); + if (source < 0) { + return []; + } + + if (originalLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (originalColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + const mappings = []; + + this._wasm.withMappingCallback( + m => { + let lastColumn = m.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + mappings.push({ + line: m.generatedLine, + column: m.generatedColumn, + lastColumn, + }); + }, () => { + this._wasm.exports.all_generated_locations_for( + this._getMappingsPtr(), + source, + originalLine - 1, + "column" in aArgs, + originalColumn + ); + } + ); + + return mappings; + } + + destroy() { + if (this._mappingsPtr !== 0) { + this._wasm.exports.free_mappings(this._mappingsPtr); + this._mappingsPtr = 0; + } + } + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + computeColumnSpans() { + if (this._computedColumnSpans) { + return; + } + + this._wasm.exports.compute_column_spans(this._getMappingsPtr()); + this._computedColumnSpans = true; + } + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + originalPositionFor(aArgs) { + const needle = { + generatedLine: util$8.getArg(aArgs, "line"), + generatedColumn: util$8.getArg(aArgs, "column") + }; + + if (needle.generatedLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (needle.generatedColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + let bias = util$8.getArg(aArgs, "bias", SourceMapConsumer$2.GREATEST_LOWER_BOUND); + if (bias == null) { + bias = SourceMapConsumer$2.GREATEST_LOWER_BOUND; + } + + let mapping; + this._wasm.withMappingCallback(m => mapping = m, () => { + this._wasm.exports.original_location_for( + this._getMappingsPtr(), + needle.generatedLine - 1, + needle.generatedColumn, + bias + ); + }); + + if (mapping) { + if (mapping.generatedLine === needle.generatedLine) { + let source = util$8.getArg(mapping, "source", null); + if (source !== null) { + source = this._sources.at(source); + source = util$8.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + + let name = util$8.getArg(mapping, "name", null); + if (name !== null) { + name = this._names.at(name); + } + + return { + source, + line: util$8.getArg(mapping, "originalLine", null), + column: util$8.getArg(mapping, "originalColumn", null), + name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + } + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function(sc) { return sc == null; }); + } + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + const index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + let relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util$8.relative(this.sourceRoot, relativeSource); + } + + let url; + if (this.sourceRoot != null + && (url = util$8.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + const fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + generatedPositionFor(aArgs) { + let source = util$8.getArg(aArgs, "source"); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + const needle = { + source, + originalLine: util$8.getArg(aArgs, "line"), + originalColumn: util$8.getArg(aArgs, "column") + }; + + if (needle.originalLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (needle.originalColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + let bias = util$8.getArg(aArgs, "bias", SourceMapConsumer$2.GREATEST_LOWER_BOUND); + if (bias == null) { + bias = SourceMapConsumer$2.GREATEST_LOWER_BOUND; + } + + let mapping; + this._wasm.withMappingCallback(m => mapping = m, () => { + this._wasm.exports.generated_location_for( + this._getMappingsPtr(), + needle.source, + needle.originalLine - 1, + needle.originalColumn, + bias + ); + }); + + if (mapping) { + if (mapping.source === needle.source) { + let lastColumn = mapping.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + return { + line: util$8.getArg(mapping, "generatedLine", null), + column: util$8.getArg(mapping, "generatedColumn", null), + lastColumn, + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + } +} + +BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$2; +sourceMapConsumer$1.BasicSourceMapConsumer = BasicSourceMapConsumer$1; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +class IndexedSourceMapConsumer$1 extends SourceMapConsumer$2 { + constructor(aSourceMap, aSourceMapURL) { + super(INTERNAL); + let sourceMap = aSourceMap; + if (typeof aSourceMap === "string") { + sourceMap = util$8.parseSourceMapInput(aSourceMap); + } + + const version = util$8.getArg(sourceMap, "version"); + const sections = util$8.getArg(sourceMap, "sections"); + + if (version != this._version) { + throw new Error("Unsupported version: " + version); + } + + this._sources = new ArraySet$3(); + this._names = new ArraySet$3(); + this.__generatedMappings = null; + this.__originalMappings = null; + this.__generatedMappingsUnsorted = null; + this.__originalMappingsUnsorted = null; + + let lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(s => { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error("Support for url field in sections not implemented."); + } + const offset = util$8.getArg(s, "offset"); + const offsetLine = util$8.getArg(offset, "line"); + const offsetColumn = util$8.getArg(offset, "column"); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error("Section offsets must be ordered and non-overlapping."); + } + lastOffset = offset; + + const consumer = new SourceMapConsumer$2(util$8.getArg(s, "map"), aSourceMapURL); + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer + }; + }); + } + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + get _generatedMappings() { + if (!this.__generatedMappings) { + this._sortGeneratedMappings(); + } + + return this.__generatedMappings; + } + + get _originalMappings() { + if (!this.__originalMappings) { + this._sortOriginalMappings(); + } + + return this.__originalMappings; + } + + get _generatedMappingsUnsorted() { + if (!this.__generatedMappingsUnsorted) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappingsUnsorted; + } + + get _originalMappingsUnsorted() { + if (!this.__originalMappingsUnsorted) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappingsUnsorted; + } + + _sortGeneratedMappings() { + const mappings = this._generatedMappingsUnsorted; + mappings.sort(util$8.compareByGeneratedPositionsDeflated); + this.__generatedMappings = mappings; + } + + _sortOriginalMappings() { + const mappings = this._originalMappingsUnsorted; + mappings.sort(util$8.compareByOriginalPositions); + this.__originalMappings = mappings; + } + + /** + * The list of original sources. + */ + get sources() { + const sources = []; + for (let i = 0; i < this._sections.length; i++) { + for (let j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + originalPositionFor(aArgs) { + const needle = { + generatedLine: util$8.getArg(aArgs, "line"), + generatedColumn: util$8.getArg(aArgs, "column") + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + const sectionIndex = binarySearch$2.search(needle, this._sections, + function(aNeedle, section) { + const cmp = aNeedle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (aNeedle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + const section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + } + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + hasContentsOfAllSources() { + return this._sections.every(function(s) { + return s.consumer.hasContentsOfAllSources(); + }); + } + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + sourceContentFor(aSource, nullOnMissing) { + for (let i = 0; i < this._sections.length; i++) { + const section = this._sections[i]; + + const content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + generatedPositionFor(aArgs) { + for (let i = 0; i < this._sections.length; i++) { + const section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util$8.getArg(aArgs, "source")) === -1) { + continue; + } + const generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + const ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + _parseMappings(aStr, aSourceRoot) { + const generatedMappings = this.__generatedMappingsUnsorted = []; + const originalMappings = this.__originalMappingsUnsorted = []; + for (let i = 0; i < this._sections.length; i++) { + const section = this._sections[i]; + + const sectionMappings = []; + section.consumer.eachMapping(m => sectionMappings.push(m)); + + for (let j = 0; j < sectionMappings.length; j++) { + const mapping = sectionMappings[j]; + + // TODO: test if null is correct here. The original code used + // `source`, which would actually have gotten used as null because + // var's get hoisted. + // See: https://github.com/mozilla/source-map/issues/333 + let source = util$8.computeSourceURL(section.consumer.sourceRoot, null, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + let name = null; + if (mapping.name) { + this._names.add(mapping.name); + name = this._names.indexOf(mapping.name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + const adjustedMapping = { + source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name + }; + + generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === "number") { + originalMappings.push(adjustedMapping); + } + } + } + } + + eachMapping(aCallback, aContext, aOrder) { + const context = aContext || null; + const order = aOrder || SourceMapConsumer$2.GENERATED_ORDER; + + let mappings; + switch (order) { + case SourceMapConsumer$2.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer$2.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + const sourceRoot = this.sourceRoot; + mappings.map(function(mapping) { + let source = null; + if (mapping.source !== null) { + source = this._sources.at(mapping.source); + source = util$8.computeSourceURL(sourceRoot, source, this._sourceMapURL); + } + return { + source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + } + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + _findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError("Line must be greater than or equal to 1, got " + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError("Column must be greater than or equal to 0, got " + + aNeedle[aColumnName]); + } + + return binarySearch$2.search(aNeedle, aMappings, aComparator, aBias); + } + + allGeneratedPositionsFor(aArgs) { + const line = util$8.getArg(aArgs, "line"); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + const needle = { + source: util$8.getArg(aArgs, "source"), + originalLine: line, + originalColumn: util$8.getArg(aArgs, "column", 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + if (needle.originalLine < 1) { + throw new Error("Line numbers must be >= 1"); + } + + if (needle.originalColumn < 0) { + throw new Error("Column numbers must be >= 0"); + } + + const mappings = []; + + let index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util$8.compareByOriginalPositions, + binarySearch$2.LEAST_UPPER_BOUND); + if (index >= 0) { + let mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + const originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + let lastColumn = mapping.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + mappings.push({ + line: util$8.getArg(mapping, "generatedLine", null), + column: util$8.getArg(mapping, "generatedColumn", null), + lastColumn, + }); + + mapping = this._originalMappings[++index]; + } + } else { + const originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + let lastColumn = mapping.lastGeneratedColumn; + if (this._computedColumnSpans && lastColumn === null) { + lastColumn = Infinity; + } + mappings.push({ + line: util$8.getArg(mapping, "generatedLine", null), + column: util$8.getArg(mapping, "generatedColumn", null), + lastColumn, + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + } + + destroy() { + for (let i = 0; i < this._sections.length; i++) { + this._sections[i].consumer.destroy(); + } + } +} +sourceMapConsumer$1.IndexedSourceMapConsumer = IndexedSourceMapConsumer$1; + +/* + * Cheat to get around inter-twingled classes. `factory()` can be at the end + * where it has access to non-hoisted classes, but it gets hoisted itself. + */ +function _factory(aSourceMap, aSourceMapURL) { + let sourceMap = aSourceMap; + if (typeof aSourceMap === "string") { + sourceMap = util$8.parseSourceMapInput(aSourceMap); + } + + const consumer = sourceMap.sections != null + ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL); + return consumer; +} + +function _factoryBSM(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +sourceMap.SourceMapConsumer = sourceMapConsumer$1.SourceMapConsumer; + +(function (module, exports) { +var SourceMapConsumer = sourceMap.SourceMapConsumer; +var path = path__default; +var util = require$$0__default$3; + +var fs; +try { + fs = fs__default; + if (!fs.existsSync || !fs.readFileSync) { + // fs doesn't have all methods we need + fs = null; + } +} catch (err) { + /* nop */ +} + +/** + * Requires a module which is protected against bundler minification. + * + * @param {NodeModule} mod + * @param {string} request + */ +function dynamicRequire(mod, request) { + return mod.require(request); +} + +// Only install once if called multiple times +var errorFormatterInstalled = false; +var uncaughtShimInstalled = false; + +// If true, the caches are reset before a stack trace formatting operation +var emptyCacheBetweenOperations = false; + +// Supports {browser, node, auto} +var environment = "auto"; + +// Maps a file path to a string containing the file contents +var fileContentsCache = {}; + +// Maps a file path to a source map for that file +var sourceMapCache = {}; + +// Regex for detecting source maps +var reSourceMap = /^data:application\/json[^,]+base64,/; + +// Priority list of retrieve handlers +var retrieveFileHandlers = []; +var retrieveMapHandlers = []; + +function isInBrowser() { + if (environment === "browser") + return true; + if (environment === "node") + return false; + return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer")); +} + +function hasGlobalProcessEventEmitter() { + return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function')); +} + +function handlerExec(list) { + return function(arg) { + for (var i = 0; i < list.length; i++) { + var ret = list[i](arg); + if (ret) { + return ret; + } + } + return null; + }; +} + +var retrieveFile = handlerExec(retrieveFileHandlers); + +retrieveFileHandlers.push(function(path) { + // Trim the path to make sure there is no extra whitespace. + path = path.trim(); + if (/^file:/.test(path)) { + // existsSync/readFileSync can't handle file protocol, but once stripped, it works + path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) { + return drive ? + '' : // file:///C:/dir/file -> C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + if (path in fileContentsCache) { + return fileContentsCache[path]; + } + + var contents = ''; + try { + if (!fs) { + // Use SJAX if we are in the browser + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, /** async */ false); + xhr.send(null); + if (xhr.readyState === 4 && xhr.status === 200) { + contents = xhr.responseText; + } + } else if (fs.existsSync(path)) { + // Otherwise, use the filesystem + contents = fs.readFileSync(path, 'utf8'); + } + } catch (er) { + /* ignore any errors */ + } + + return fileContentsCache[path] = contents; +}); + +// Support URLs relative to a directory, but be careful about a protocol prefix +// in case we are in the browser (i.e. directories may start with "http://" or "file:///") +function supportRelativeURL(file, url) { + if (!file) return url; + var dir = path.dirname(file); + var match = /^\w+:\/\/[^\/]*/.exec(dir); + var protocol = match ? match[0] : ''; + var startPath = dir.slice(protocol.length); + if (protocol && /^\/\w\:/.test(startPath)) { + // handle file:///C:/ paths + protocol += '/'; + return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/'); + } + return protocol + path.resolve(dir.slice(protocol.length), url); +} + +function retrieveSourceMapURL(source) { + var fileData; + + if (isInBrowser()) { + try { + var xhr = new XMLHttpRequest(); + xhr.open('GET', source, false); + xhr.send(null); + fileData = xhr.readyState === 4 ? xhr.responseText : null; + + // Support providing a sourceMappingURL via the SourceMap header + var sourceMapHeader = xhr.getResponseHeader("SourceMap") || + xhr.getResponseHeader("X-SourceMap"); + if (sourceMapHeader) { + return sourceMapHeader; + } + } catch (e) { + } + } + + // Get the URL of the source map + fileData = retrieveFile(source); + var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; +} +// Can be overridden by the retrieveSourceMap option to install. Takes a +// generated source filename; returns a {map, optional url} object, or null if +// there is no source map. The map field may be either a string or the parsed +// JSON object (ie, it must be a valid argument to the SourceMapConsumer +// constructor). +var retrieveSourceMap = handlerExec(retrieveMapHandlers); +retrieveMapHandlers.push(function(source) { + var sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) return null; + + // Read the contents of the source map + var sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + // Support source map URL as a data url + var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); + sourceMapData = Buffer.from(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(sourceMappingURL); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = sourceMapCache[position.source]; + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = sourceMapCache[position.source] = { + url: urlAndMap.url, + map: new SourceMapConsumer(urlAndMap.map) + }; + + // Load all sources stored inline with the source map into the file cache + // to pretend like they are already loaded. They may not exist on disk. + if (sourceMap.map.sourcesContent) { + sourceMap.map.sources.forEach(function(source, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + var url = supportRelativeURL(sourceMap.url, source); + fileContentsCache[url] = contents; + } + }); + } + } else { + sourceMap = sourceMapCache[position.source] = { + url: null, + map: null + }; + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') { + var originalPosition = sourceMap.map.originalPositionFor(position); + + // Only return the original position if a matching line was found. If no + // matching line is found then we return position instead, which will cause + // the stack trace to print the path and line for the compiled file. It is + // better to give a precise location in the compiled file than a vague + // location in the original file. + if (originalPosition.source !== null) { + originalPosition.source = supportRelativeURL( + sourceMap.url, originalPosition.source); + return originalPosition; + } + } + + return position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition({ + source: match[2], + line: +match[3], + column: match[4] - 1 + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + (position.column + 1) + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +// This is copied almost verbatim from the V8 source code at +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The +// implementation of wrapCallSite() used to just forward to the actual source +// code of CallSite.prototype.toString but unfortunately a new release of V8 +// did something to the prototype chain and broke the shim. The only fix I +// could find was copy/paste. +function CallSiteToString() { + var fileName; + var fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; // Expecting source position to follow. + } + + if (fileName) { + fileLocation += fileName; + } else { + // Source code does not originate from a file and is not native, but we + // can still get the source position inside the source string, e.g. in + // an eval string. + fileLocation += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + var isAsync = this.isAsync ? this.isAsync() : false; + if(isAsync) { + line += 'async '; + var isPromiseAll = this.isPromiseAll ? this.isPromiseAll() : false; + var isPromiseAny = this.isPromiseAny ? this.isPromiseAny() : false; + if(isPromiseAny || isPromiseAll) { + line += isPromiseAll ? 'Promise.all (index ' : 'Promise.any (index '; + var promiseIndex = this.getPromiseIndex(); + line += promiseIndex + ')'; + } + } + var functionName = this.getFunctionName(); + var addSuffix = true; + var isConstructor = this.isConstructor(); + var isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + var typeName = this.getTypeName(); + // Fixes shim to be backward compatable with Node v0 to v4 + if (typeName === "[object Object]") { + typeName = "null"; + } + var methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) != 0) { + line += typeName + "."; + } + line += functionName; + if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { + line += " [as " + methodName + "]"; + } + } else { + line += typeName + "." + (methodName || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) { + line += " (" + fileLocation + ")"; + } + return line; +} + +function cloneCallSite(frame) { + var object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { + object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; + }); + object.toString = CallSiteToString; + return object; +} + +function wrapCallSite(frame, state) { + // provides interface backward compatibility + if (state === undefined) { + state = { nextPosition: null, curPosition: null }; + } + if(frame.isNative()) { + state.curPosition = null; + return frame; + } + + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//# sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + var line = frame.getLineNumber(); + var column = frame.getColumnNumber() - 1; + + // Fix position in Node where some (internal) code is prepended. + // See https://github.com/evanw/node-source-map-support/issues/36 + // Header removed in node at ^10.16 || >=11.11.0 + // v11 is not an LTS candidate, we can just test the one version with it. + // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11 + var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; + var headerLength = noHeader.test(process.version) ? 0 : 62; + if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { + column -= headerLength; + } + + var position = mapSourcePosition({ + source: source, + line: line, + column: column + }); + state.curPosition = position; + frame = cloneCallSite(frame); + var originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { + if (state.nextPosition == null) { + return originalFunctionName(); + } + return state.nextPosition.name || originalFunctionName(); + }; + frame.getFileName = function() { return position.source; }; + frame.getLineNumber = function() { return position.line; }; + frame.getColumnNumber = function() { return position.column + 1; }; + frame.getScriptNameOrSourceURL = function() { return position.source; }; + return frame; + } + + // Code called using eval() needs special handling + var origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { return origin; }; + return frame; + } + + // If we get here then we were unable to change the source position + return frame; +} + +var kIsNodeError = undefined; +try { + // Get a deliberate ERR_INVALID_ARG_TYPE + // TODO is there a better way to reliably get an instance of NodeError? + path.resolve(123); +} catch(e) { + const symbols = Object.getOwnPropertySymbols(e); + const symbol = symbols.find(function (s) {return s.toString().indexOf('kIsNodeError') >= 0}); + if(symbol) kIsNodeError = symbol; +} + +const ErrorPrototypeToString = (err) =>Error.prototype.toString.call(err); + +// This function is part of the V8 stack trace API, for more info see: +// https://v8.dev/docs/stack-trace-api +function prepareStackTrace(error, stack) { + if (emptyCacheBetweenOperations) { + fileContentsCache = {}; + sourceMapCache = {}; + } + + // node gives its own errors special treatment. Mimic that behavior + // https://github.com/nodejs/node/blob/3cbaabc4622df1b4009b9d026a1a970bdbae6e89/lib/internal/errors.js#L118-L128 + // https://github.com/nodejs/node/pull/39182 + var errorString; + if (kIsNodeError) { + if(kIsNodeError in error) { + errorString = `${error.name} [${error.code}]: ${error.message}`; + } else { + errorString = ErrorPrototypeToString(error); + } + } else { + var name = error.name || 'Error'; + var message = error.message || ''; + errorString = name + ": " + message; + } + + var state = { nextPosition: null, curPosition: null }; + var processedStack = []; + for (var i = stack.length - 1; i >= 0; i--) { + processedStack.push('\n at ' + wrapCallSite(stack[i], state)); + state.nextPosition = state.curPosition; + } + state.curPosition = state.nextPosition = null; + return errorString + processedStack.reverse().join(''); +} + +// Generate position and snippet of original source with pointer +function getErrorSource(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var source = match[1]; + var line = +match[2]; + var column = +match[3]; + + // Support the inline sourceContents inside the source map + var contents = fileContentsCache[source]; + + // Support files on disk + if (!contents && fs && fs.existsSync(source)) { + try { + contents = fs.readFileSync(source, 'utf8'); + } catch (er) { + contents = ''; + } + } + + // Format the line from the original source code like node does + if (contents) { + var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; + if (code) { + return source + ':' + line + '\n' + code + '\n' + + new Array(column).join(' ') + '^'; + } + } + } + return null; +} + +function printFatalErrorUponExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + if (process.stderr._handle && process.stderr._handle.setBlocking) { + process.stderr._handle.setBlocking(true); + } + + if (source) { + console.error(source); + } + + // Matches node's behavior for colorized output + console.error( + util.inspect(error, { + customInspect: false, + colors: process.stderr.isTTY + }) + ); +} + +function shimEmitUncaughtException () { + var origEmit = process.emit; + var isTerminatingDueToFatalException = false; + var fatalException; + + process.emit = function (type) { + const hadListeners = origEmit.apply(this, arguments); + if (type === 'uncaughtException' && !hadListeners) { + isTerminatingDueToFatalException = true; + fatalException = arguments[1]; + process.exit(1); + } + if (type === 'exit' && isTerminatingDueToFatalException) { + printFatalErrorUponExit(fatalException); + } + return hadListeners; + }; +} + +var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0); + +exports.wrapCallSite = wrapCallSite; +exports.getErrorSource = getErrorSource; +exports.mapSourcePosition = mapSourcePosition; +exports.retrieveSourceMap = retrieveSourceMap; + +exports.install = function(options) { + options = options || {}; + + if (options.environment) { + environment = options.environment; + if (["node", "browser", "auto"].indexOf(environment) === -1) { + throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + retrieveFileHandlers.length = 0; + } + + retrieveFileHandlers.unshift(options.retrieveFile); + } + + // Allow source maps to be found by methods other than reading the files + // directly from disk. + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) { + retrieveMapHandlers.length = 0; + } + + retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + // Use dynamicRequire to avoid including in browser bundles + var Module = dynamicRequire(module, 'module'); + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + fileContentsCache[filename] = content; + sourceMapCache[filename] = undefined; + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!emptyCacheBetweenOperations) { + emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + // Install the error reformatter + if (!errorFormatterInstalled) { + errorFormatterInstalled = true; + Error.prepareStackTrace = prepareStackTrace; + } + + if (!uncaughtShimInstalled) { + var installHandler = 'handleUncaughtExceptions' in options ? + options.handleUncaughtExceptions : true; + + // Do not override 'uncaughtException' with our own handler in Node.js + // Worker threads. Workers pass the error to the main thread as an event, + // rather than printing something to stderr and exiting. + try { + // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify. + var worker_threads = dynamicRequire(module, 'worker_threads'); + if (worker_threads.isMainThread === false) { + installHandler = false; + } + } catch(e) {} + + // Provide the option to not install the uncaught exception handler. This is + // to support other uncaught exception handlers (in test frameworks, for + // example). If this handler is not installed and there are no other uncaught + // exception handlers, uncaught exceptions will be caught by node's built-in + // exception handler and the process will still be terminated. However, the + // generated JavaScript code will be shown above the stack trace instead of + // the original source code. + if (installHandler && hasGlobalProcessEventEmitter()) { + uncaughtShimInstalled = true; + shimEmitUncaughtException(); + } + } +}; + +exports.resetRetrieveHandlers = function() { + retrieveFileHandlers.length = 0; + retrieveMapHandlers.length = 0; + + retrieveFileHandlers = originalRetrieveFileHandlers.slice(0); + retrieveMapHandlers = originalRetrieveMapHandlers.slice(0); + + retrieveSourceMap = handlerExec(retrieveMapHandlers); + retrieveFile = handlerExec(retrieveFileHandlers); +}; +}(sourceMapSupport, sourceMapSupport.exports)); + +var makeError$2 = {exports: {}}; + +(function (module, exports) { + +// =================================================================== + +var construct = typeof Reflect !== "undefined" ? Reflect.construct : undefined; +var defineProperty = Object.defineProperty; + +// ------------------------------------------------------------------- + +var captureStackTrace = Error.captureStackTrace; +if (captureStackTrace === undefined) { + captureStackTrace = function captureStackTrace(error) { + var container = new Error(); + + defineProperty(error, "stack", { + configurable: true, + get: function getStack() { + var stack = container.stack; + + // Replace property with value for faster future accesses. + defineProperty(this, "stack", { + configurable: true, + value: stack, + writable: true, + }); + + return stack; + }, + set: function setStack(stack) { + defineProperty(error, "stack", { + configurable: true, + value: stack, + writable: true, + }); + }, + }); + }; +} + +// ------------------------------------------------------------------- + +function BaseError(message) { + if (message !== undefined) { + defineProperty(this, "message", { + configurable: true, + value: message, + writable: true, + }); + } + + var cname = this.constructor.name; + if (cname !== undefined && cname !== this.name) { + defineProperty(this, "name", { + configurable: true, + value: cname, + writable: true, + }); + } + + captureStackTrace(this, this.constructor); +} + +BaseError.prototype = Object.create(Error.prototype, { + // See: https://github.com/JsCommunity/make-error/issues/4 + constructor: { + configurable: true, + value: BaseError, + writable: true, + }, +}); + +// ------------------------------------------------------------------- + +// Sets the name of a function if possible (depends of the JS engine). +var setFunctionName = (function() { + function setFunctionName(fn, name) { + return defineProperty(fn, "name", { + configurable: true, + value: name, + }); + } + try { + var f = function() {}; + setFunctionName(f, "foo"); + if (f.name === "foo") { + return setFunctionName; + } + } catch (_) {} +})(); + +// ------------------------------------------------------------------- + +function makeError(constructor, super_) { + if (super_ == null || super_ === Error) { + super_ = BaseError; + } else if (typeof super_ !== "function") { + throw new TypeError("super_ should be a function"); + } + + var name; + if (typeof constructor === "string") { + name = constructor; + constructor = + construct !== undefined + ? function() { + return construct(super_, arguments, this.constructor); + } + : function() { + super_.apply(this, arguments); + }; + + // If the name can be set, do it once and for all. + if (setFunctionName !== undefined) { + setFunctionName(constructor, name); + name = undefined; + } + } else if (typeof constructor !== "function") { + throw new TypeError("constructor should be either a string or a function"); + } + + // Also register the super constructor also as `constructor.super_` just + // like Node's `util.inherits()`. + // + // eslint-disable-next-line dot-notation + constructor.super_ = constructor["super"] = super_; + + var properties = { + constructor: { + configurable: true, + value: constructor, + writable: true, + }, + }; + + // If the name could not be set on the constructor, set it on the + // prototype. + if (name !== undefined) { + properties.name = { + configurable: true, + value: name, + writable: true, + }; + } + constructor.prototype = Object.create(super_.prototype, properties); + + return constructor; +} +exports = module.exports = makeError; +exports.BaseError = BaseError; +}(makeError$2, makeError$2.exports)); + +var util$7 = {}; + +var yn$2 = {exports: {}}; + +const YES_MATCH_SCORE_THRESHOLD = 2; +const NO_MATCH_SCORE_THRESHOLD = 1.25; + +const yMatch = new Map([ + [5, 0.25], + [6, 0.25], + [7, 0.25], + ['t', 0.75], + ['y', 1], + ['u', 0.75], + ['g', 0.25], + ['h', 0.25], + ['j', 0.25] +]); + +const eMatch = new Map([ + [2, 0.25], + [3, 0.25], + [4, 0.25], + ['w', 0.75], + ['e', 1], + ['r', 0.75], + ['s', 0.25], + ['d', 0.25], + ['f', 0.25] +]); + +const sMatch = new Map([ + ['q', 0.25], + ['w', 0.25], + ['e', 0.25], + ['a', 0.75], + ['s', 1], + ['d', 0.75], + ['z', 0.25], + ['x', 0.25], + ['c', 0.25] +]); + +const nMatch = new Map([ + ['h', 0.25], + ['j', 0.25], + ['k', 0.25], + ['b', 0.75], + ['n', 1], + ['m', 0.75] +]); + +const oMatch = new Map([ + [9, 0.25], + [0, 0.25], + ['i', 0.75], + ['o', 1], + ['p', 0.75], + ['k', 0.25], + ['l', 0.25] +]); + +function getYesMatchScore(value) { + const [y, e, s] = value; + let score = 0; + + if (yMatch.has(y)) { + score += yMatch.get(y); + } + + if (eMatch.has(e)) { + score += eMatch.get(e); + } + + if (sMatch.has(s)) { + score += sMatch.get(s); + } + + return score; +} + +function getNoMatchScore(value) { + const [n, o] = value; + let score = 0; + + if (nMatch.has(n)) { + score += nMatch.get(n); + } + + if (oMatch.has(o)) { + score += oMatch.get(o); + } + + return score; +} + +var lenient$1 = (input, options) => { + if (getYesMatchScore(input) >= YES_MATCH_SCORE_THRESHOLD) { + return true; + } + + if (getNoMatchScore(input) >= NO_MATCH_SCORE_THRESHOLD) { + return false; + } + + return options.default; +}; + +const lenient = lenient$1; + +const yn$1 = (input, options) => { + input = String(input).trim(); + + options = Object.assign({ + lenient: false, + default: null + }, options); + + if (options.default !== null && typeof options.default !== 'boolean') { + throw new TypeError(`Expected the \`default\` option to be of type \`boolean\`, got \`${typeof options.default}\``); + } + + if (/^(?:y|yes|true|1)$/i.test(input)) { + return true; + } + + if (/^(?:n|no|false|0)$/i.test(input)) { + return false; + } + + if (options.lenient === true) { + return lenient(input, options); + } + + return options.default; +}; + +yn$2.exports = yn$1; +// TODO: Remove this for the next major release +yn$2.exports.default = yn$1; + +const nativeModule = require$$0__default$5; +const path$j = path__default; +const fs$k = fs__default; + +function createRequire (filename) { + // Fallback to process.cwd() if no filename passed + if (!filename) { + filename = process.cwd(); + } + + // If filename is dir, createRequire goes with parent directory, so we need fakepath + if (isDir(filename)) { + filename = path$j.join(filename, 'index.js'); + } + + // Added in Node v12.2.0 + if (nativeModule.createRequire) { + return nativeModule.createRequire(filename) + } + + // Added in Node v10.12.0 and deprecated since Node v12.2.0 + if (nativeModule.createRequireFromPath) { + return nativeModule.createRequireFromPath(filename) + } + + // Polyfill + return _createRequire(filename) +} + +// Polyfill +function _createRequire (filename) { + const mod = new nativeModule.Module(filename, null); + mod.filename = filename; + mod.paths = nativeModule.Module._nodeModulePaths(path$j.dirname(filename)); + mod._compile('module.exports = require;', filename); + return mod.exports +} + +function isDir (path) { + try { + const stat = fs$k.lstatSync(path); + return stat.isDirectory() + } catch (e) { + // lstatSync throws an error if path doesn't exist + return false + } +} + +var createRequire_1 = createRequire; + +var _a; +Object.defineProperty(util$7, "__esModule", { value: true }); +util$7.trace = util$7.cachedLookup = util$7.hasOwnProperty = util$7.normalizeSlashes = util$7.parse = util$7.split = util$7.assign = util$7.yn = util$7.createRequire = void 0; +const module_1 = require$$0__default$5; +const ynModule = yn$2.exports; +/** @internal */ +util$7.createRequire = (_a = module_1.createRequire !== null && module_1.createRequire !== void 0 ? module_1.createRequire : module_1.createRequireFromPath) !== null && _a !== void 0 ? _a : createRequire_1; +/** + * Wrapper around yn module that returns `undefined` instead of `null`. + * This is implemented by yn v4, but we're staying on v3 to avoid v4's node 10 requirement. + * @internal + */ +function yn(value) { + var _a; + return (_a = ynModule(value)) !== null && _a !== void 0 ? _a : undefined; +} +util$7.yn = yn; +/** + * Like `Object.assign`, but ignores `undefined` properties. + * + * @internal + */ +function assign(initialValue, ...sources) { + for (const source of sources) { + for (const key of Object.keys(source)) { + const value = source[key]; + if (value !== undefined) + initialValue[key] = value; + } + } + return initialValue; +} +util$7.assign = assign; +/** + * Split a string array of values. + * @internal + */ +function split(value) { + return typeof value === 'string' ? value.split(/ *, */g) : undefined; +} +util$7.split = split; +/** + * Parse a string as JSON. + * @internal + */ +function parse$e(value) { + return typeof value === 'string' ? JSON.parse(value) : undefined; +} +util$7.parse = parse$e; +const directorySeparator$1 = '/'; +const backslashRegExp = /\\/g; +/** + * Replace backslashes with forward slashes. + * @internal + */ +function normalizeSlashes$1(value) { + return value.replace(backslashRegExp, directorySeparator$1); +} +util$7.normalizeSlashes = normalizeSlashes$1; +/** + * Safe `hasOwnProperty` + * @internal + */ +function hasOwnProperty$2(object, property) { + return Object.prototype.hasOwnProperty.call(object, property); +} +util$7.hasOwnProperty = hasOwnProperty$2; +/** + * Cached fs operation wrapper. + */ +function cachedLookup(fn) { + const cache = new Map(); + return (arg) => { + if (!cache.has(arg)) { + const v = fn(arg); + cache.set(arg, v); + return v; + } + return cache.get(arg); + }; +} +util$7.cachedLookup = cachedLookup; +/** + * We do not support ts's `trace` option yet. In the meantime, rather than omit + * `trace` options in hosts, I am using this placeholder. + */ +function trace(s) { } +util$7.trace = trace; + +var configuration = {}; + +var tsInternals = {}; + +Object.defineProperty(tsInternals, "__esModule", { value: true }); +tsInternals.getPatternFromSpec = tsInternals.createTsInternals = void 0; +const path_1$2 = path__default; +const util_1$2 = util$7; +/** @internal */ +tsInternals.createTsInternals = util_1$2.cachedLookup(createTsInternalsUncached); +/** + * Given a reference to the TS compiler, return some TS internal functions that we + * could not or did not want to grab off the `ts` object. + * These have been copy-pasted from TS's source and tweaked as necessary. + * + * NOTE: This factory returns *only* functions which need a reference to the TS + * compiler. Other functions do not need a reference to the TS compiler so are + * exported directly from this file. + */ +function createTsInternalsUncached(_ts) { + const ts = _ts; + /** + * Copied from: + * https://github.com/microsoft/TypeScript/blob/v4.3.2/src/compiler/commandLineParser.ts#L2821-L2846 + */ + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { + extendedConfig = util_1$2.normalizeSlashes(extendedConfig); + if (isRootedDiskPath(extendedConfig) || + startsWith(extendedConfig, './') || + startsWith(extendedConfig, '../')) { + let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && + !endsWith(extendedConfigPath, ts.Extension.Json)) { + extendedConfigPath = `${extendedConfigPath}.json`; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); + return undefined; + } + } + return extendedConfigPath; + } + // If the path isn't a rooted or relative path, resolve like a module + const resolved = ts.nodeModuleNameResolver(extendedConfig, combinePaths(basePath, 'tsconfig.json'), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, + /*cache*/ undefined, + /*projectRefs*/ undefined, + /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); + return undefined; + } + return { getExtendsConfigPath }; +} +// These functions have alternative implementation to avoid copying too much from TS +function isRootedDiskPath(path) { + return path_1$2.isAbsolute(path); +} +function combinePaths(path, ...paths) { + return util_1$2.normalizeSlashes(path_1$2.resolve(path, ...paths.filter((path) => path))); +} +function getNormalizedAbsolutePath(fileName, currentDirectory) { + return util_1$2.normalizeSlashes(currentDirectory != null + ? path_1$2.resolve(currentDirectory, fileName) + : path_1$2.resolve(fileName)); +} +function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; +} +function endsWith(str, suffix) { + const expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; +} +// Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. +// It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future +// proof. +const reservedCharacterPattern = /[^\w\s\/]/g; +/** + * @internal + * See also: getRegularExpressionForWildcard, which seems to do almost the same thing + */ +function getPatternFromSpec(spec, basePath) { + const pattern = spec && getSubPatternFromSpec(spec, basePath, excludeMatcher); + return pattern && `^(${pattern})${'($|/)'}`; +} +tsInternals.getPatternFromSpec = getPatternFromSpec; +function getSubPatternFromSpec(spec, basePath, { singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter, }) { + let subpattern = ''; + let hasWrittenComponent = false; + const components = getNormalizedPathComponents(spec, basePath); + const lastComponent = last(components); + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push('**', '*'); + } + let optionalCount = 0; + for (let component of components) { + if (component === '**') { + subpattern += doubleAsteriskRegexFragment; + } + else { + if (hasWrittenComponent) { + subpattern += directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ')?'; + optionalCount--; + } + return subpattern; +} +const excludeMatcher = { + singleAsteriskRegexFragment: '[^/]*', + doubleAsteriskRegexFragment: '(/.+?)?', + replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment), +}; +function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); +} +function getPathComponents(path, currentDirectory = '') { + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); +} +function reducePathComponents(components) { + if (!some(components)) + return []; + const reduced = [components[0]]; + for (let i = 1; i < components.length; i++) { + const component = components[i]; + if (!component) + continue; + if (component === '.') + continue; + if (component === '..') { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== '..') { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; +} +function getRootLength(path) { + const rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; +} +function getEncodedRootLength(path) { + if (!path) + return 0; + const ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + const p1 = path.indexOf(ch0 === 47 /* slash */ ? directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + const ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + const schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + const authorityStart = schemeEnd + urlSchemeSeparator.length; + const authorityEnd = path.indexOf(directorySeparator, authorityStart); + if (authorityEnd !== -1) { + // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + const scheme = path.slice(0, schemeEnd); + const authority = path.slice(authorityStart, authorityEnd); + if (scheme === 'file' && + (authority === '' || authority === 'localhost') && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; +} +function hasTrailingDirectorySeparator(path) { + return (path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1))); +} +function isAnyDirectorySeparator(charCode) { + return (charCode === 47 /* slash */ || charCode === 92 /* backslash */); +} +function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; +} +const directorySeparator = '/'; +const altDirectorySeparator = '\\'; +const urlSchemeSeparator = '://'; +function isVolumeCharacter(charCode) { + return ((charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */)); +} +function getFileUrlVolumeSeparatorEnd(url, start) { + const ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && + url.charCodeAt(start + 1) === 51 /* _3 */) { + const ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; +} +function some(array, predicate) { + if (array) { + if (predicate) { + for (const v of array) { + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; +} +function pathComponents(path, rootLength) { + const root = path.substring(0, rootLength); + const rest = path.substring(rootLength).split(directorySeparator); + if (rest.length && !lastOrUndefined(rest)) + rest.pop(); + return [root, ...rest]; +} +function lastOrUndefined(array) { + return array.length === 0 ? undefined : array[array.length - 1]; +} +function last(array) { + // Debug.assert(array.length !== 0); + return array[array.length - 1]; +} +function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === '*' + ? singleAsteriskRegexFragment + : match === '?' + ? '[^/]' + : '\\' + match; +} +/** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ +function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); +} + +var tsconfigs = {}; + +var $schema$3 = "https://json.schemastore.org/tsconfig"; +var display$3 = "Node 16"; +var compilerOptions$3 = { + lib: [ + "es2021" + ], + module: "commonjs", + target: "es2021", + strict: true, + esModuleInterop: true, + skipLibCheck: true, + forceConsistentCasingInFileNames: true +}; +var require$$0$3 = { + $schema: $schema$3, + display: display$3, + compilerOptions: compilerOptions$3 +}; + +var $schema$2 = "https://json.schemastore.org/tsconfig"; +var display$2 = "Node 14"; +var compilerOptions$2 = { + lib: [ + "es2020" + ], + module: "commonjs", + target: "es2020", + strict: true, + esModuleInterop: true, + skipLibCheck: true, + forceConsistentCasingInFileNames: true +}; +var require$$1 = { + $schema: $schema$2, + display: display$2, + compilerOptions: compilerOptions$2 +}; + +var $schema$1 = "https://json.schemastore.org/tsconfig"; +var display$1 = "Node 12"; +var compilerOptions$1 = { + lib: [ + "es2019", + "es2020.promise", + "es2020.bigint", + "es2020.string" + ], + module: "commonjs", + target: "es2019", + strict: true, + esModuleInterop: true, + skipLibCheck: true, + forceConsistentCasingInFileNames: true +}; +var require$$2 = { + $schema: $schema$1, + display: display$1, + compilerOptions: compilerOptions$1 +}; + +var $schema = "https://json.schemastore.org/tsconfig"; +var display = "Node 10"; +var compilerOptions = { + lib: [ + "es2018" + ], + module: "commonjs", + target: "es2018", + strict: true, + esModuleInterop: true, + skipLibCheck: true, + forceConsistentCasingInFileNames: true +}; +var require$$3 = { + $schema: $schema, + display: display, + compilerOptions: compilerOptions +}; + +Object.defineProperty(tsconfigs, "__esModule", { value: true }); +tsconfigs.getDefaultTsconfigJsonForNodeVersion = void 0; +const nodeMajor = parseInt(process.versions.node.split('.')[0], 10); +/** + * return parsed JSON of the bundled @tsconfig/bases config appropriate for the + * running version of nodejs + * @internal + */ +function getDefaultTsconfigJsonForNodeVersion(ts) { + const tsInternal = ts; + if (nodeMajor >= 16) { + const config = require$$0$3; + if (configCompatible(config)) + return config; + } + if (nodeMajor >= 14) { + const config = require$$1; + if (configCompatible(config)) + return config; + } + if (nodeMajor >= 12) { + const config = require$$2; + if (configCompatible(config)) + return config; + } + return require$$3; + // Verify that tsconfig target and lib options are compatible with TypeScript compiler + function configCompatible(config) { + return (typeof ts.ScriptTarget[config.compilerOptions.target.toUpperCase()] === 'number' && + tsInternal.libs && + config.compilerOptions.lib.every((lib) => tsInternal.libs.includes(lib))); + } +} +tsconfigs.getDefaultTsconfigJsonForNodeVersion = getDefaultTsconfigJsonForNodeVersion; + +var __rest = (commonjsGlobal && commonjsGlobal.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +Object.defineProperty(configuration, "__esModule", { value: true }); +configuration.readConfig = void 0; +const path_1$1 = path__default; +const index_1 = dist$1; +const ts_internals_1$1 = tsInternals; +const tsconfigs_1 = tsconfigs; +const util_1$1 = util$7; +/** + * TypeScript compiler option values required by `ts-node` which cannot be overridden. + */ +const TS_NODE_COMPILER_OPTIONS = { + sourceMap: true, + inlineSourceMap: false, + inlineSources: true, + declaration: false, + noEmit: false, + outDir: '.ts-node', +}; +/* + * Do post-processing on config options to support `ts-node`. + */ +function fixConfig(ts, config) { + // Delete options that *should not* be passed through. + delete config.options.out; + delete config.options.outFile; + delete config.options.composite; + delete config.options.declarationDir; + delete config.options.declarationMap; + delete config.options.emitDeclarationOnly; + // Target ES5 output by default (instead of ES3). + if (config.options.target === undefined) { + config.options.target = ts.ScriptTarget.ES5; + } + // Target CommonJS modules by default (instead of magically switching to ES6 when the target is ES6). + if (config.options.module === undefined) { + config.options.module = ts.ModuleKind.CommonJS; + } + return config; +} +/** + * Load TypeScript configuration. Returns the parsed TypeScript config and + * any `ts-node` options specified in the config file. + * + * Even when a tsconfig.json is not loaded, this function still handles merging + * compilerOptions from various sources: API, environment variables, etc. + * + * @internal + */ +function readConfig(cwd, ts, rawApiOptions) { + var _a, _b, _c; + // Ordered [a, b, c] where config a extends b extends c + const configChain = []; + let config = { compilerOptions: {} }; + let basePath = cwd; + let configFilePath = undefined; + const projectSearchDir = path_1$1.resolve(cwd, (_a = rawApiOptions.projectSearchDir) !== null && _a !== void 0 ? _a : cwd); + const { fileExists = ts.sys.fileExists, readFile = ts.sys.readFile, skipProject = index_1.DEFAULTS.skipProject, project = index_1.DEFAULTS.project, } = rawApiOptions; + // Read project configuration when available. + if (!skipProject) { + configFilePath = project + ? path_1$1.resolve(cwd, project) + : ts.findConfigFile(projectSearchDir, fileExists); + if (configFilePath) { + let pathToNextConfigInChain = configFilePath; + const tsInternals = ts_internals_1$1.createTsInternals(ts); + const errors = []; + // Follow chain of "extends" + while (true) { + const result = ts.readConfigFile(pathToNextConfigInChain, readFile); + // Return diagnostics. + if (result.error) { + return { + configFilePath, + config: { errors: [result.error], fileNames: [], options: {} }, + tsNodeOptionsFromTsconfig: {}, + optionBasePaths: {}, + }; + } + const c = result.config; + const bp = path_1$1.dirname(pathToNextConfigInChain); + configChain.push({ + config: c, + basePath: bp, + configPath: pathToNextConfigInChain, + }); + if (c.extends == null) + break; + const resolvedExtendedConfigPath = tsInternals.getExtendsConfigPath(c.extends, { + fileExists, + readDirectory: ts.sys.readDirectory, + readFile, + useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames, + trace: util_1$1.trace, + }, bp, errors, ts.createCompilerDiagnostic); + if (errors.length) { + return { + configFilePath, + config: { errors, fileNames: [], options: {} }, + tsNodeOptionsFromTsconfig: {}, + optionBasePaths: {}, + }; + } + if (resolvedExtendedConfigPath == null) + break; + pathToNextConfigInChain = resolvedExtendedConfigPath; + } + ({ config, basePath } = configChain[0]); + } + } + // Merge and fix ts-node options that come from tsconfig.json(s) + const tsNodeOptionsFromTsconfig = {}; + const optionBasePaths = {}; + for (let i = configChain.length - 1; i >= 0; i--) { + const { config, basePath, configPath } = configChain[i]; + const options = filterRecognizedTsConfigTsNodeOptions(config['ts-node']) + .recognized; + // Some options are relative to the config file, so must be converted to absolute paths here + if (options.require) { + // Modules are found relative to the tsconfig file, not the `dir` option + const tsconfigRelativeRequire = util_1$1.createRequire(configPath); + options.require = options.require.map((path) => tsconfigRelativeRequire.resolve(path)); + } + if (options.scopeDir) { + options.scopeDir = path_1$1.resolve(basePath, options.scopeDir); + } + // Downstream code uses the basePath; we do not do that here. + if (options.moduleTypes) { + optionBasePaths.moduleTypes = basePath; + } + util_1$1.assign(tsNodeOptionsFromTsconfig, options); + } + // Remove resolution of "files". + const files = (_c = (_b = rawApiOptions.files) !== null && _b !== void 0 ? _b : tsNodeOptionsFromTsconfig.files) !== null && _c !== void 0 ? _c : index_1.DEFAULTS.files; + if (!files) { + config.files = []; + config.include = []; + } + // Only if a config file is *not* loaded, load an implicit configuration from @tsconfig/bases + const skipDefaultCompilerOptions = configFilePath != null; + const defaultCompilerOptionsForNodeVersion = skipDefaultCompilerOptions + ? undefined + : Object.assign(Object.assign({}, tsconfigs_1.getDefaultTsconfigJsonForNodeVersion(ts).compilerOptions), { types: ['node'] }); + // Merge compilerOptions from all sources + config.compilerOptions = Object.assign({}, + // automatically-applied options from @tsconfig/bases + defaultCompilerOptionsForNodeVersion, + // tsconfig.json "compilerOptions" + config.compilerOptions, + // from env var + index_1.DEFAULTS.compilerOptions, + // tsconfig.json "ts-node": "compilerOptions" + tsNodeOptionsFromTsconfig.compilerOptions, + // passed programmatically + rawApiOptions.compilerOptions, + // overrides required by ts-node, cannot be changed + TS_NODE_COMPILER_OPTIONS); + const fixedConfig = fixConfig(ts, ts.parseJsonConfigFileContent(config, { + fileExists, + readFile, + readDirectory: ts.sys.readDirectory, + useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames, + }, basePath, undefined, configFilePath)); + return { + configFilePath, + config: fixedConfig, + tsNodeOptionsFromTsconfig, + optionBasePaths, + }; +} +configuration.readConfig = readConfig; +/** + * Given the raw "ts-node" sub-object from a tsconfig, return an object with only the properties + * recognized by "ts-node" + */ +function filterRecognizedTsConfigTsNodeOptions(jsonObject) { + if (jsonObject == null) + return { recognized: {}, unrecognized: {} }; + const _a = jsonObject, { compiler, compilerHost, compilerOptions, emit, files, ignore, ignoreDiagnostics, logError, preferTsExts, pretty, require, skipIgnore, transpileOnly, typeCheck, transpiler, scope, scopeDir, moduleTypes, experimentalReplAwait } = _a, unrecognized = __rest(_a, ["compiler", "compilerHost", "compilerOptions", "emit", "files", "ignore", "ignoreDiagnostics", "logError", "preferTsExts", "pretty", "require", "skipIgnore", "transpileOnly", "typeCheck", "transpiler", "scope", "scopeDir", "moduleTypes", "experimentalReplAwait"]); + const filteredTsConfigOptions = { + compiler, + compilerHost, + compilerOptions, + emit, + experimentalReplAwait, + files, + ignore, + ignoreDiagnostics, + logError, + preferTsExts, + pretty, + require, + skipIgnore, + transpileOnly, + typeCheck, + transpiler, + scope, + scopeDir, + moduleTypes, + }; + return { recognized: filteredTsConfigOptions, unrecognized }; +} + +var moduleTypeClassifier = {}; + +Object.defineProperty(moduleTypeClassifier, "__esModule", { value: true }); +moduleTypeClassifier.createModuleTypeClassifier = void 0; + +const ts_internals_1 = tsInternals; +const util_1 = util$7; +/** + * @internal + * May receive non-normalized options -- basePath and patterns -- and will normalize them + * internally. + * However, calls to `classifyModule` must pass pre-normalized paths! + */ +function createModuleTypeClassifier(options) { + const { patterns, basePath: _basePath } = options; + const basePath = _basePath !== undefined + ? util_1.normalizeSlashes(_basePath).replace(/\/$/, '') + : undefined; + const patternTypePairs = Object.entries(patterns !== null && patterns !== void 0 ? patterns : []).map(([_pattern, type]) => { + const pattern = util_1.normalizeSlashes(_pattern); + return { pattern: parsePattern(basePath, pattern), type }; + }); + const classifications = { + package: { + moduleType: 'package', + }, + cjs: { + moduleType: 'cjs', + }, + esm: { + moduleType: 'esm', + }, + }; + const auto = classifications.package; + // Passed path must be normalized! + function classifyModuleNonCached(path) { + const matched = matchPatterns$1(patternTypePairs, (_) => _.pattern, path); + if (matched) + return classifications[matched.type]; + return auto; + } + const classifyModule = util_1.cachedLookup(classifyModuleNonCached); + function classifyModuleAuto(path) { + return auto; + } + return { + classifyModule: patternTypePairs.length + ? classifyModule + : classifyModuleAuto, + }; +} +moduleTypeClassifier.createModuleTypeClassifier = createModuleTypeClassifier; +function parsePattern(basePath, patternString) { + const pattern = ts_internals_1.getPatternFromSpec(patternString, basePath); + return pattern !== undefined ? new RegExp(pattern) : /(?:)/; +} +function matchPatterns$1(objects, getPattern, candidate) { + for (let i = objects.length - 1; i >= 0; i--) { + const object = objects[i]; + const pattern = getPattern(object); + if (pattern === null || pattern === void 0 ? void 0 : pattern.test(candidate)) { + return object; + } + } +} + +var resolverFunctions = {}; + +Object.defineProperty(resolverFunctions, "__esModule", { value: true }); +resolverFunctions.createResolverFunctions = void 0; +const path_1 = path__default; +/** + * @internal + * In a factory because these are shared across both CompilerHost and LanguageService codepaths + */ +function createResolverFunctions(kwargs) { + const { serviceHost, ts, config, cwd, getCanonicalFileName, configFilePath, } = kwargs; + const moduleResolutionCache = ts.createModuleResolutionCache(cwd, getCanonicalFileName, config.options); + const knownInternalFilenames = new Set(); + /** "Buckets" (module directories) whose contents should be marked "internal" */ + const internalBuckets = new Set(); + // Get bucket for a source filename. Bucket is the containing `./node_modules/*/` directory + // For '/project/node_modules/foo/node_modules/bar/lib/index.js' bucket is '/project/node_modules/foo/node_modules/bar/' + // For '/project/node_modules/foo/node_modules/@scope/bar/lib/index.js' bucket is '/project/node_modules/foo/node_modules/@scope/bar/' + const moduleBucketRe = /.*\/node_modules\/(?:@[^\/]+\/)?[^\/]+\//; + function getModuleBucket(filename) { + const find = moduleBucketRe.exec(filename); + if (find) + return find[0]; + return ''; + } + // Mark that this file and all siblings in its bucket should be "internal" + function markBucketOfFilenameInternal(filename) { + internalBuckets.add(getModuleBucket(filename)); + } + function isFileInInternalBucket(filename) { + return internalBuckets.has(getModuleBucket(filename)); + } + function isFileKnownToBeInternal(filename) { + return knownInternalFilenames.has(filename); + } + /** + * If we need to emit JS for a file, force TS to consider it non-external + */ + const fixupResolvedModule = (resolvedModule) => { + const { resolvedFileName } = resolvedModule; + if (resolvedFileName === undefined) + return; + // .ts is always switched to internal + // .js is switched on-demand + if (resolvedModule.isExternalLibraryImport && + ((resolvedFileName.endsWith('.ts') && + !resolvedFileName.endsWith('.d.ts')) || + isFileKnownToBeInternal(resolvedFileName) || + isFileInInternalBucket(resolvedFileName))) { + resolvedModule.isExternalLibraryImport = false; + } + if (!resolvedModule.isExternalLibraryImport) { + knownInternalFilenames.add(resolvedFileName); + } + }; + /* + * NOTE: + * Older ts versions do not pass `redirectedReference` nor `options`. + * We must pass `redirectedReference` to newer ts versions, but cannot rely on `options`, hence the weird argument name + */ + const resolveModuleNames = (moduleNames, containingFile, reusedNames, redirectedReference, optionsOnlyWithNewerTsVersions) => { + return moduleNames.map((moduleName) => { + const { resolvedModule } = ts.resolveModuleName(moduleName, containingFile, config.options, serviceHost, moduleResolutionCache, redirectedReference); + if (resolvedModule) { + fixupResolvedModule(resolvedModule); + } + return resolvedModule; + }); + }; + // language service never calls this, but TS docs recommend that we implement it + const getResolvedModuleWithFailedLookupLocationsFromCache = (moduleName, containingFile) => { + const ret = ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache); + if (ret && ret.resolvedModule) { + fixupResolvedModule(ret.resolvedModule); + } + return ret; + }; + const resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile, redirectedReference, options) => { + // Note: seems to be called with empty typeDirectiveNames array for all files. + return typeDirectiveNames.map((typeDirectiveName) => { + let { resolvedTypeReferenceDirective } = ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, config.options, serviceHost, redirectedReference); + if (typeDirectiveName === 'node' && !resolvedTypeReferenceDirective) { + // Resolve @types/node relative to project first, then __dirname (copy logic from elsewhere / refactor into reusable function) + let typesNodePackageJsonPath; + try { + typesNodePackageJsonPath = require.resolve('@types/node/package.json', { + paths: [configFilePath !== null && configFilePath !== void 0 ? configFilePath : cwd, __dirname], + }); + } + catch (_a) { } // gracefully do nothing when @types/node is not installed for any reason + if (typesNodePackageJsonPath) { + const typeRoots = [path_1.resolve(typesNodePackageJsonPath, '../..')]; + ({ + resolvedTypeReferenceDirective, + } = ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, Object.assign(Object.assign({}, config.options), { typeRoots }), serviceHost, redirectedReference)); + } + } + if (resolvedTypeReferenceDirective) { + fixupResolvedModule(resolvedTypeReferenceDirective); + } + return resolvedTypeReferenceDirective; + }); + }; + return { + resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache, + resolveTypeReferenceDirectives, + isFileKnownToBeInternal, + markBucketOfFilenameInternal, + }; +} +resolverFunctions.createResolverFunctions = createResolverFunctions; + +var repl = {}; + +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) { + var tokens = value.split(/(\s+|[()[\]{}'"]|\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) { + 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 _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); +} + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } +} + +function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); +} + +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); +} + +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: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + 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; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + 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) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + 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 createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + 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]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; +} +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$1(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; +} + +var index_es6 = { + __proto__: null, + Diff: Diff, + diffChars: diffChars, + diffWords: diffWords, + diffWordsWithSpace: diffWordsWithSpace, + diffLines: diffLines, + diffTrimmedLines: diffTrimmedLines, + diffSentences: diffSentences, + diffCss: diffCss, + diffJson: diffJson, + diffArrays: diffArrays, + structuredPatch: structuredPatch, + createTwoFilesPatch: createTwoFilesPatch, + createPatch: createPatch, + applyPatch: applyPatch, + applyPatches: applyPatches, + parsePatch: parsePatch, + merge: merge$1, + convertChangesToDMP: convertChangesToDMP, + convertChangesToXML: convertChangesToXML, + canonicalize: canonicalize +}; + +var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(index_es6); + +var nodePrimordials = { + ArrayFrom: Array.from, + ArrayIsArray: Array.isArray, + ArrayPrototypeJoin: (obj, separator) => Array.prototype.join.call(obj, separator), + ArrayPrototypeShift: (obj) => Array.prototype.shift.call(obj), + ArrayPrototypeForEach: (arr, ...rest) => Array.prototype.forEach.apply(arr, rest), + ArrayPrototypeIncludes: (arr, ...rest) => Array.prototype.includes.apply(arr, rest), + ArrayPrototypeJoin: (arr, ...rest) => Array.prototype.join.apply(arr, rest), + ArrayPrototypePop: (arr, ...rest) => Array.prototype.pop.apply(arr, rest), + ArrayPrototypePush: (arr, ...rest) => Array.prototype.push.apply(arr, rest), + FunctionPrototype: Function.prototype, + JSONParse: JSON.parse, + JSONStringify: JSON.stringify, + ObjectFreeze: Object.freeze, + ObjectKeys: Object.keys, + ObjectGetOwnPropertyNames: Object.getOwnPropertyNames, + ObjectDefineProperty: Object.defineProperty, + ObjectPrototypeHasOwnProperty: (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop), + RegExpPrototypeTest: (obj, string) => RegExp.prototype.test.call(obj, string), + RegExpPrototypeSymbolReplace: (obj, ...rest) => RegExp.prototype[Symbol.replace].apply(obj, rest), + SafeMap: Map, + SafeSet: Set, + StringPrototypeEndsWith: (str, ...rest) => String.prototype.endsWith.apply(str, rest), + StringPrototypeIncludes: (str, ...rest) => String.prototype.includes.apply(str, rest), + StringPrototypeLastIndexOf: (str, ...rest) => String.prototype.lastIndexOf.apply(str, rest), + StringPrototypeIndexOf: (str, ...rest) => String.prototype.indexOf.apply(str, rest), + StringPrototypeRepeat: (str, ...rest) => String.prototype.repeat.apply(str, rest), + StringPrototypeReplace: (str, ...rest) => String.prototype.replace.apply(str, rest), + StringPrototypeSlice: (str, ...rest) => String.prototype.slice.apply(str, rest), + StringPrototypeSplit: (str, ...rest) => String.prototype.split.apply(str, rest), + StringPrototypeStartsWith: (str, ...rest) => String.prototype.startsWith.apply(str, rest), + StringPrototypeSubstr: (str, ...rest) => String.prototype.substr.apply(str, rest), + SyntaxError: SyntaxError +}; + +var acorn$1 = {exports: {}}; + +(function (module, exports) { +(function (global, factory) { + factory(exports) ; +}(commonjsGlobal, (function (exports) { + // Reserved word lists for various dialects of the language + + var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" + }; + + // And the keywords + + var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; + + var keywords = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" + }; + + var keywordRelationalOperator = /^in(stanceof)?$/; + + // ## Character categories + + // Big ugly regular expressions that match characters in the + // whitespace, identifier, and identifier-start categories. These + // are only applied when a character is found to actually have a + // code point above 128. + // Generated by `bin/generate-identifier-regex.js`. + var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + + var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + + nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + + // These are a run-length and offset encoded representation of the + // >0xffff code points that are a valid part of identifiers. The + // offset starts at 0x10000, and each pair of numbers represents an + // offset to the next range, and then a size of the range. They were + // generated by bin/generate-identifier-regex.js + + // eslint-disable-next-line comma-spacing + var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938]; + + // eslint-disable-next-line comma-spacing + var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239]; + + // This has a complexity linear to the value of the code. The + // assumption is that looking up astral identifier characters is + // rare. + function isInAstralSet(code, set) { + var pos = 0x10000; + for (var i = 0; i < set.length; i += 2) { + pos += set[i]; + if (pos > code) { return false } + pos += set[i + 1]; + if (pos >= code) { return true } + } + } + + // Test whether a given character code starts an identifier. + + function isIdentifierStart(code, astral) { + if (code < 65) { return code === 36 } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) + } + + // Test whether a given character is part of an identifier. + + function isIdentifierChar(code, astral) { + if (code < 48) { return code === 36 } + if (code < 58) { return true } + if (code < 65) { return false } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) + } + + // ## Token types + + // The assignment of fine-grained, information-carrying type objects + // allows the tokenizer to store the information it has about a + // token in a way that is very cheap for the parser to look up. + + // All token type variables start with an underscore, to make them + // easy to recognize. + + // The `beforeExpr` property is used to disambiguate between regular + // expressions and divisions. It is set on all token types that can + // be followed by an expression (thus, a slash after them would be a + // regular expression). + // + // The `startsExpr` property is used to check if the token ends a + // `yield` expression. It is set on all token types that either can + // directly start an expression (like a quotation mark) or can + // continue an expression (like the body of a string). + // + // `isLoop` marks a keyword as starting a loop, which is important + // to know when parsing a label, in order to allow or disallow + // continue jumps to that label. + + var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; + }; + + function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) + } + var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; + + // Map keyword names to token types. + + var keywords$1 = {}; + + // Succinct definitions of keyword token types + function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name; + return keywords$1[name] = new TokenType(name, options) + } + + var types = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + coalesce: binop("??", 1), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) + }; + + // Matches a whole line break (where CRLF is considered a single + // line break). Used to count lines. + + var lineBreak = /\r\n?|\n|\u2028|\u2029/; + var lineBreakG = new RegExp(lineBreak.source, "g"); + + function isNewLine(code, ecma2019String) { + return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) + } + + var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + + var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + + var ref = Object.prototype; + var hasOwnProperty = ref.hasOwnProperty; + var toString = ref.toString; + + // Checks if an object has a property. + + function has(obj, propName) { + return hasOwnProperty.call(obj, propName) + } + + var isArray = Array.isArray || (function (obj) { return ( + toString.call(obj) === "[object Array]" + ); }); + + function wordsRegexp(words) { + return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") + } + + // These are used when `options.locations` is on, for the + // `startLoc` and `endLoc` properties. + + var Position = function Position(line, col) { + this.line = line; + this.column = col; + }; + + Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) + }; + + var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } + }; + + // The `getLineInfo` function is mostly useful when the + // `locations` option is off (for performance reasons) and you + // want to find the line/column position for a given character + // offset. `input` should be the code string that the offset refers + // into. + + function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + lineBreakG.lastIndex = cur; + var match = lineBreakG.exec(input); + if (match && match.index < offset) { + ++line; + cur = match.index + match[0].length; + } else { + return new Position(line, offset - cur) + } + } + } + + // A second argument must be given to configure the parser process. + // These options are recognized (only `ecmaVersion` is required): + + var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the + // latest version the library supports). This influences support + // for strict mode, the set of reserved words, and support for + // new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called + // when a semicolon is automatically inserted. It will be passed + // the position of the comma as an offset, and if `locations` is + // enabled, it is given the location as a `{line, column}` object + // as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file + // is allowed and treated as a line comment. + allowHashBang: false, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false + }; + + // Interpret and default an options object + + var warnedAboutEcmaVersion = false; + + function getOptions(opts) { + var options = {}; + + for (var opt in defaultOptions) + { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } + + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } + + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } + + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function (token) { return tokens.push(token); }; + } + if (isArray(options.onComment)) + { options.onComment = pushComment(options, options.onComment); } + + return options + } + + function pushComment(options, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text, + start: start, + end: end + }; + if (options.locations) + { comment.loc = new SourceLocation(this, startLoc, endLoc); } + if (options.ranges) + { comment.range = [start, end]; } + array.push(comment); + } + } + + // Each scope gets a bitset that may contain these flags + var + SCOPE_TOP = 1, + SCOPE_FUNCTION = 2, + SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128; + + function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) + } + + // Used in checkLVal* and declareName to determine the type of a binding + var + BIND_NONE = 0, // Not a binding + BIND_VAR = 1, // Var-style binding + BIND_LEXICAL = 2, // Let- or const-style binding + BIND_FUNCTION = 3, // Function declaration + BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding + BIND_OUTSIDE = 5; // Special case for function names as bound inside the function + + var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { reserved += " await"; } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false; + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + + // Properties of the current token: + // Its type + this.type = types.eof; + // For tokens that include more information than their type, the value + this.value = null; + // Its start and end offset + this.start = this.end = this.pos; + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition(); + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext(); + this.exprAllowed = true; + + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + // Labels in scope. + this.labels = []; + // Thus-far undefined exports. + this.undefinedExports = Object.create(null); + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } + + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + + // For RegExp validation + this.regexpState = null; + + // The stack of private names. + // Each element has two properties: 'declared' and 'used'. + // When it exited from the outermost class definition, all used private names must be declared. + this.privateNameStack = []; + }; + + var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } }; + + Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node) + }; + + prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; + prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; + prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; + prototypeAccessors.canAwait.get = function () { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var scope = this.scopeStack[i]; + if (scope.inClassFieldInit) { return false } + if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } + } + return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction + }; + prototypeAccessors.allowSuper.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod + }; + prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; + prototypeAccessors.inNonArrowFunction.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & SCOPE_FUNCTION) > 0 || inClassFieldInit + }; + + Parser.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; + + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls + }; + + Parser.parse = function parse (input, options) { + return new this(options, input).parse() + }; + + Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() + }; + + Parser.tokenizer = function tokenizer (input, options) { + return new this(options, input) + }; + + Object.defineProperties( Parser.prototype, prototypeAccessors ); + + var pp = Parser.prototype; + + // ## Parser utilities + + var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; + pp.strictDirective = function(start) { + for (;;) { + // Try to find string literal. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { return false } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || + (lineBreak.test(spaceAfter[0]) && + !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) + } + start += match[0].length; + + // Skip semicolon, if any. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") + { start++; } + } + }; + + // Predicate that tests whether the next token is of the given + // type, and if yes, consumes it as a side effect. + + pp.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false + } + }; + + // Tests whether parsed token is a contextual keyword. + + pp.isContextual = function(name) { + return this.type === types.name && this.value === name && !this.containsEsc + }; + + // Consumes contextual keyword if possible. + + pp.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true + }; + + // Asserts that following token is given contextual keyword. + + pp.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } + }; + + // Test whether a semicolon can be inserted at the current position. + + pp.canInsertSemicolon = function() { + return this.type === types.eof || + this.type === types.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + pp.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true + } + }; + + // Consume a semicolon, or, failing that, see if we are allowed to + // pretend that there is a semicolon at this position. + + pp.semicolon = function() { + if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } + }; + + pp.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) + { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } + if (!notNext) + { this.next(); } + return true + } + }; + + // Expect a token of a given type. If found, consume it, otherwise, + // raise an unexpected token error. + + pp.expect = function(type) { + this.eat(type) || this.unexpected(); + }; + + // Raise an unexpected token error. + + pp.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); + }; + + function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; + } + + pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { return } + if (refDestructuringErrors.trailingComma > -1) + { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } + }; + + pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { return false } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } + if (shorthandAssign >= 0) + { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } + if (doubleProto >= 0) + { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } + }; + + pp.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } + if (this.awaitPos) + { this.raise(this.awaitPos, "Await expression cannot be a default value"); } + }; + + pp.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") + { return this.isSimpleAssignTarget(expr.expression) } + return expr.type === "Identifier" || expr.type === "MemberExpression" + }; + + var pp$1 = Parser.prototype; + + // ### Statement parsing + + // Parse a program. Initializes the parser, reads any number of + // statements, and wraps them in a Program node. Optionally takes a + // `program` argument. If present, the statements will be appended + // to its body instead of creating a new node. + + pp$1.parseTopLevel = function(node) { + var exports = Object.create(null); + if (!node.body) { node.body = []; } + while (this.type !== types.eof) { + var stmt = this.parseStatement(null, true, exports); + node.body.push(stmt); + } + if (this.inModule) + { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) + { + var name = list[i]; + + this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); + } } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType; + return this.finishNode(node, "Program") + }; + + var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + + pp$1.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + // For ambiguous cases, determine if a LexicalDeclaration (or only a + // Statement) is allowed here. If context is not empty then only a Statement + // is allowed. However, `let [` is an explicit negative lookahead for + // ExpressionStatement, so special-case it first. + if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral + if (context) { return false } + + if (nextCh === 123) { return true } // '{' + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } + if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { return true } + } + return false + }; + + // check 'async [no LineTerminator here] function' + // - 'async /*foo*/ function' is OK. + // - 'async /*\n*/ function' is invalid. + pp$1.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || + !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) + }; + + // Parse a single statement. + // + // If expecting a statement and finding a slash operator, parse a + // regular expression literal. This is to handle cases like + // `if (foo) /blah/.exec(foo)`, where looking at the previous token + // does not help. + + pp$1.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + + if (this.isLet(context)) { + starttype = types._var; + kind = "let"; + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case types._debugger: return this.parseDebuggerStatement(node) + case types._do: return this.parseDoStatement(node) + case types._for: return this.parseForStatement(node) + case types._function: + // Function as sole body of either an if statement or a labeled statement + // works, but not when it is part of a labeled statement that is the sole + // body of an if statement. + if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } + return this.parseFunctionStatement(node, false, !context) + case types._class: + if (context) { this.unexpected(); } + return this.parseClass(node, true) + case types._if: return this.parseIfStatement(node) + case types._return: return this.parseReturnStatement(node) + case types._switch: return this.parseSwitchStatement(node) + case types._throw: return this.parseThrowStatement(node) + case types._try: return this.parseTryStatement(node) + case types._const: case types._var: + kind = kind || this.value; + if (context && kind !== "var") { this.unexpected(); } + return this.parseVarStatement(node, kind) + case types._while: return this.parseWhileStatement(node) + case types._with: return this.parseWithStatement(node) + case types.braceL: return this.parseBlock(true, node) + case types.semi: return this.parseEmptyStatement(node) + case types._export: + case types._import: + if (this.options.ecmaVersion > 10 && starttype === types._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) // '(' or '.' + { return this.parseExpressionStatement(node, this.parseExpression()) } + } + + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } + if (!this.inModule) + { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } + } + return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { this.unexpected(); } + this.next(); + return this.parseFunctionStatement(node, true, !context) + } + + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) + { return this.parseLabeledStatement(node, maybeName, expr, context) } + else { return this.parseExpressionStatement(node, expr) } + } + }; + + pp$1.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } + else if (this.type !== types.name) { this.unexpected(); } + else { + node.label = this.parseIdent(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } + if (node.label && isBreak) { break } + } + } + if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") + }; + + pp$1.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") + }; + + pp$1.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) + { this.eat(types.semi); } + else + { this.semicolon(); } + return this.finishNode(node, "DoWhileStatement") + }; + + // Disambiguating between a `for` and a `for`/`in` or `for`/`of` + // loop is non-trivial. Basically, we have to parse the init `var` + // statement or expression, disallowing the `in` operator (see + // the second parameter to `parseExpression`), and then check + // whether the next token is `in` or `of`. When there is no init + // part (semicolon immediately after the opening parenthesis), it + // is a regular `for` loop. + + pp$1.parseForStatement = function(node) { + this.next(); + var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types.parenL); + if (this.type === types.semi) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, null) + } + var isLet = this.isLet(); + if (this.type === types._var || this.type === types._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + return this.parseForIn(node, init$1) + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init$1) + } + var refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); + if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) + }; + + pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) + }; + + pp$1.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement") + }; + + pp$1.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") + }; + + pp$1.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur; + for (var sawDefault = false; this.type !== types.braceR;) { + if (this.type === types._case || this.type === types._default) { + var isCase = this.type === types._case; + if (cur) { this.finishNode(cur, "SwitchCase"); } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } + sawDefault = true; + cur.test = null; + } + this.expect(types.colon); + } else { + if (!cur) { this.unexpected(); } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { this.finishNode(cur, "SwitchCase"); } + this.next(); // Closing brace + this.labels.pop(); + return this.finishNode(node, "SwitchStatement") + }; + + pp$1.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + { this.raise(this.lastTokEnd, "Illegal newline after throw"); } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement") + }; + + // Reused empty array added for node fields that are always empty. + + var empty = []; + + pp$1.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types.parenL)) { + clause.param = this.parseBindingAtom(); + var simple = clause.param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types.parenR); + } else { + if (this.options.ecmaVersion < 10) { this.unexpected(); } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) + { this.raise(node.start, "Missing catch or finally clause"); } + return this.finishNode(node, "TryStatement") + }; + + pp$1.parseVarStatement = function(node, kind) { + this.next(); + this.parseVar(node, false, kind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") + }; + + pp$1.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement") + }; + + pp$1.parseWithStatement = function(node) { + if (this.strict) { this.raise(this.start, "'with' in strict mode"); } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement") + }; + + pp$1.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") + }; + + pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) + { + var label = list[i$1]; + + if (label.name === maybeName) + { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } } + var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this.labels[i]; + if (label$1.statementStart === node.start) { + // Update information about previous labels on this node + label$1.statementStart = this.start; + label$1.kind = kind; + } else { break } + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement") + }; + + pp$1.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") + }; + + // Parse a semicolon-enclosed block of statements, handling `"use + // strict"` declarations when `allowStrict` is true (used for + // function bodies). + + pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); + + node.body = []; + this.expect(types.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (this.type !== types.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + if (exitStrict) { this.strict = false; } + this.next(); + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") + }; + + // Parse a regular `for` loop. The disambiguation code in + // `parseStatement` will already have parsed the init statement or + // expression. + + pp$1.parseFor = function(node, init) { + node.init = init; + this.expect(types.semi); + node.test = this.type === types.semi ? null : this.parseExpression(); + this.expect(types.semi); + node.update = this.type === types.parenR ? null : this.parseExpression(); + this.expect(types.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement") + }; + + // Parse a `for`/`in` and `for`/`of` loop, which are almost + // same from parser's perspective. + + pp$1.parseForIn = function(node, init) { + var isForIn = this.type === types._in; + this.next(); + + if ( + init.type === "VariableDeclaration" && + init.declarations[0].init != null && + ( + !isForIn || + this.options.ecmaVersion < 8 || + this.strict || + init.kind !== "var" || + init.declarations[0].id.type !== "Identifier" + ) + ) { + this.raise( + init.start, + ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") + ); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") + }; + + // Parse a list of variable declarations. + + pp$1.parseVar = function(node, isFor, kind) { + node.declarations = []; + node.kind = kind; + for (;;) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { + this.unexpected(); + } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types.comma)) { break } + } + return node + }; + + pp$1.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); + }; + + var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + + // Parse a function declaration or literal (depending on the + // `statement & FUNC_STATEMENT`). + + // Remove `allowExpressionBody` for 7.0.0, as it is only called with false + pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) + { this.unexpected(); } + node.generator = this.eat(types.star); + } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) + // If it is a regular function declaration in sloppy mode, then it is + // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding + // mode depends on properties of the current scope (see + // treatFunctionsAsVar). + { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } + } + + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + + if (!(statement & FUNC_STATEMENT)) + { node.id = this.type === types.name ? this.parseIdent() : null; } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") + }; + + pp$1.parseFunctionParams = function(node) { + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + }; + + // Parse a class declaration or literal (depending on the + // `isStatement` parameter). + + pp$1.parseClass = function(node, isStatement) { + this.next(); + + // ecma-262 14.6 Class Definitions + // A class definition is always strict mode code. + var oldStrict = this.strict; + this.strict = true; + + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types.braceL); + while (this.type !== types.braceR) { + var element = this.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); } + hadConstructor = true; + } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") + }; + + pp$1.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types.semi)) { return null } + + var ecmaVersion = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + + // Parse modifiers + node.static = false; + if (this.eatContextual("static")) { + if (this.isClassElementNameStart() || this.type === types.star) { + node.static = true; + } else { + keyName = "static"; + } + } + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + + // Parse element name + if (keyName) { + // 'async', 'get', 'set', or 'static' were not a keyword contextually. + // The last token is any of those. Make it the element name. + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + + // Parse element value + if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. + if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + + return node + }; + + pp$1.isClassElementNameStart = function() { + return ( + this.type === types.name || + this.type === types.privateId || + this.type === types.num || + this.type === types.string || + this.type === types.bracketL || + this.type.keyword + ) + }; + + pp$1.parseClassElementName = function(element) { + if (this.type === types.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } + }; + + pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + // Check key and flags + var key = method.key; + if (method.kind === "constructor") { + if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } + if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + + // Parse value + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + + // Check value + if (method.kind === "get" && value.params.length !== 0) + { this.raiseRecoverable(value.start, "getter should have no params"); } + if (method.kind === "set" && value.params.length !== 1) + { this.raiseRecoverable(value.start, "setter should have exactly one param"); } + if (method.kind === "set" && value.params[0].type === "RestElement") + { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } + + return this.finishNode(method, "MethodDefinition") + }; + + pp$1.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + + if (this.eat(types.eq)) { + // To raise SyntaxError if 'arguments' exists in the initializer. + var scope = this.currentThisScope(); + var inClassFieldInit = scope.inClassFieldInit; + scope.inClassFieldInit = true; + field.value = this.parseMaybeAssign(); + scope.inClassFieldInit = inClassFieldInit; + } else { + field.value = null; + } + this.semicolon(); + + return this.finishNode(field, "PropertyDefinition") + }; + + pp$1.parseClassId = function(node, isStatement) { + if (this.type === types.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLValSimple(node.id, BIND_LEXICAL, false); } + } else { + if (isStatement === true) + { this.unexpected(); } + node.id = null; + } + }; + + pp$1.parseClassSuper = function(node) { + node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; + }; + + pp$1.enterClassBody = function() { + var element = {declared: Object.create(null), used: []}; + this.privateNameStack.push(element); + return element.declared + }; + + pp$1.exitClassBody = function() { + var ref = this.privateNameStack.pop(); + var declared = ref.declared; + var used = ref.used; + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i = 0; i < used.length; ++i) { + var id = used[i]; + if (!has(declared, id.name)) { + if (parent) { + parent.used.push(id); + } else { + this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); + } + } + } + }; + + function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; + } + + // `class { get #a(){}; static set #a(_){} }` is also conflict. + if ( + curr === "iget" && next === "iset" || + curr === "iset" && next === "iget" || + curr === "sget" && next === "sset" || + curr === "sset" && next === "sget" + ) { + privateNameMap[name] = "true"; + return false + } else if (!curr) { + privateNameMap[name] = next; + return false + } else { + return true + } + } + + function checkKeyName(node, name) { + var computed = node.computed; + var key = node.key; + return !computed && ( + key.type === "Identifier" && key.name === name || + key.type === "Literal" && key.value === name + ) + } + + // Parses module export declaration. + + pp$1.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types.star)) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseIdent(true); + this.checkExport(exports, node.exported.name, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration") + } + if (this.eat(types._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart); + var isAsync; + if (this.type === types._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { this.next(); } + node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); + } else if (this.type === types._class) { + var cNode = this.startNode(); + node.declaration = this.parseClass(cNode, "nullableID"); + } else { + node.declaration = this.parseMaybeAssign(); + this.semicolon(); + } + return this.finishNode(node, "ExportDefaultDeclaration") + } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseStatement(null); + if (node.declaration.type === "VariableDeclaration") + { this.checkVariableExport(exports, node.declaration.declarations); } + else + { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } + node.specifiers = []; + node.source = null; + } else { // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; + + this.checkUnreserved(spec.local); + // check if export is defined + this.checkLocalExport(spec.local); + } + + node.source = null; + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration") + }; + + pp$1.checkExport = function(exports, name, pos) { + if (!exports) { return } + if (has(exports, name)) + { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } + exports[name] = true; + }; + + pp$1.checkPatternExport = function(exports, pat) { + var type = pat.type; + if (type === "Identifier") + { this.checkExport(exports, pat.name, pat.start); } + else if (type === "ObjectPattern") + { for (var i = 0, list = pat.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this.checkPatternExport(exports, prop); + } } + else if (type === "ArrayPattern") + { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + + if (elt) { this.checkPatternExport(exports, elt); } + } } + else if (type === "Property") + { this.checkPatternExport(exports, pat.value); } + else if (type === "AssignmentPattern") + { this.checkPatternExport(exports, pat.left); } + else if (type === "RestElement") + { this.checkPatternExport(exports, pat.argument); } + else if (type === "ParenthesizedExpression") + { this.checkPatternExport(exports, pat.expression); } + }; + + pp$1.checkVariableExport = function(exports, decls) { + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; + + this.checkPatternExport(exports, decl.id); + } + }; + + pp$1.shouldParseExportStatement = function() { + return this.type.keyword === "var" || + this.type.keyword === "const" || + this.type.keyword === "class" || + this.type.keyword === "function" || + this.isLet() || + this.isAsyncFunction() + }; + + // Parses a comma-separated list of module exports. + + pp$1.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + // export { x, y as z } [from '...'] + this.expect(types.braceL); + while (!this.eat(types.braceR)) { + if (!first) { + this.expect(types.comma); + if (this.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var node = this.startNode(); + node.local = this.parseIdent(true); + node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local; + this.checkExport(exports, node.exported.name, node.exported.start); + nodes.push(this.finishNode(node, "ExportSpecifier")); + } + return nodes + }; + + // Parses import declaration. + + pp$1.parseImport = function(node) { + this.next(); + // import '...' + if (this.type === types.string) { + node.specifiers = empty; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration") + }; + + // Parses a comma-separated list of module imports. + + pp$1.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types.name) { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); + if (!this.eat(types.comma)) { return nodes } + } + if (this.type === types.star) { + var node$1 = this.startNode(); + this.next(); + this.expectContextual("as"); + node$1.local = this.parseIdent(); + this.checkLValSimple(node$1.local, BIND_LEXICAL); + nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); + return nodes + } + this.expect(types.braceL); + while (!this.eat(types.braceR)) { + if (!first) { + this.expect(types.comma); + if (this.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var node$2 = this.startNode(); + node$2.imported = this.parseIdent(true); + if (this.eatContextual("as")) { + node$2.local = this.parseIdent(); + } else { + this.checkUnreserved(node$2.imported); + node$2.local = node$2.imported; + } + this.checkLValSimple(node$2.local, BIND_LEXICAL); + nodes.push(this.finishNode(node$2, "ImportSpecifier")); + } + return nodes + }; + + // Set `ExpressionStatement#directive` property for directive prologues. + pp$1.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } + }; + pp$1.isDirectiveCandidate = function(statement) { + return ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + typeof statement.expression.value === "string" && + // Reject parenthesized strings. + (this.input[statement.start] === "\"" || this.input[statement.start] === "'") + ) + }; + + var pp$2 = Parser.prototype; + + // Convert existing expression atom to assignable pattern + // if possible. + + pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } + break + + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break + + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.toAssignable(prop, isBinding); + // Early error: + // AssignmentRestProperty[Yield, Await] : + // `...` DestructuringAssignmentTarget[Yield, Await] + // + // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. + if ( + prop.type === "RestElement" && + (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") + ) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break + + case "Property": + // AssignmentProperty has type === "Property" + if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } + this.toAssignable(node.value, isBinding); + break + + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break + + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") + { this.raise(node.argument.start, "Rest elements cannot have a default value"); } + break + + case "AssignmentExpression": + if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break + + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (!isBinding) { break } + + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + return node + }; + + // Convert list of expression atoms to binding list. + + pp$2.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { this.toAssignable(elt, isBinding); } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + { this.unexpected(last.argument.start); } + } + return exprList + }; + + // Parses spread element. + + pp$2.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") + }; + + pp$2.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types.name) + { this.unexpected(); } + + node.argument = this.parseBindingAtom(); + + return this.finishNode(node, "RestElement") + }; + + // Parses lvalue (assignable) atom. + + pp$2.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types.bracketR, true, true); + return this.finishNode(node, "ArrayPattern") + + case types.braceL: + return this.parseObj(true) + } + } + return this.parseIdent() + }; + + pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { first = false; } + else { this.expect(types.comma); } + if (allowEmpty && this.type === types.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close)) { + break + } else if (this.type === types.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } + this.expect(close); + break + } else { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + elts.push(elem); + } + } + return elts + }; + + pp$2.parseBindingListItem = function(param) { + return param + }; + + // Parses assignment pattern around given atom if possible. + + pp$2.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern") + }; + + // The following three functions all verify that a node is an lvalue — + // something that can be bound, or assigned to. In order to do so, they perform + // a variety of checks: + // + // - Check that none of the bound/assigned-to identifiers are reserved words. + // - Record name declarations for bindings in the appropriate scope. + // - Check duplicate argument names, if checkClashes is set. + // + // If a complex binding pattern is encountered (e.g., object and array + // destructuring), the entire pattern is recursively checked. + // + // There are three versions of checkLVal*() appropriate for different + // circumstances: + // + // - checkLValSimple() shall be used if the syntactic construct supports + // nothing other than identifiers and member expressions. Parenthesized + // expressions are also correctly handled. This is generally appropriate for + // constructs for which the spec says + // + // > It is a Syntax Error if AssignmentTargetType of [the production] is not + // > simple. + // + // It is also appropriate for checking if an identifier is valid and not + // defined elsewhere, like import declarations or function/class identifiers. + // + // Examples where this is used include: + // a += …; + // import a from '…'; + // where a is the node to be checked. + // + // - checkLValPattern() shall be used if the syntactic construct supports + // anything checkLValSimple() supports, as well as object and array + // destructuring patterns. This is generally appropriate for constructs for + // which the spec says + // + // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor + // > an ArrayLiteral and AssignmentTargetType of [the production] is not + // > simple. + // + // Examples where this is used include: + // (a = …); + // const a = …; + // try { … } catch (a) { … } + // where a is the node to be checked. + // + // - checkLValInnerPattern() shall be used if the syntactic construct supports + // anything checkLValPattern() supports, as well as default assignment + // patterns, rest elements, and other constructs that may appear within an + // object or array destructuring pattern. + // + // As a special case, function parameters also use checkLValInnerPattern(), + // as they also support defaults and rest constructs. + // + // These functions deliberately support both assignment and binding constructs, + // as the logic for both is exceedingly similar. If the node is the target of + // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it + // should be set to the appropriate BIND_* constant, like BIND_VAR or + // BIND_LEXICAL. + // + // If the function is called with a non-BIND_NONE bindingType, then + // additionally a checkClashes object may be specified to allow checking for + // duplicate argument names. checkClashes is ignored if the provided construct + // is an assignment (i.e., bindingType is BIND_NONE). + + pp$2.checkLValSimple = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + var isBind = bindingType !== BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (checkClashes) { + if (has(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + } + break + + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ParenthesizedExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } + return this.checkLValSimple(expr.expression, bindingType, checkClashes) + + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } + }; + + pp$2.checkLValPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break + + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + + if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } + } + break + + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } + }; + + pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "Property": + // AssignmentProperty has type === "Property" + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break + + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break + + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break + + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } + }; + + // A recursive descent parser operates by defining functions for all + + var pp$3 = Parser.prototype; + + // Check if property name clashes with already added. + // Object/class getters and setters are not allowed to clash — + // either with each other or with an init property — and in + // strict mode, init properties are also not allowed to be repeated. + + pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") + { return } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + { return } + var key = prop.key; + var name; + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) + { refDestructuringErrors.doubleProto = key.start; } + // Backwards-compat kludge. Can be removed in version 6.0 + } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } + } + propHash.proto = true; + } + return + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) + { this.raiseRecoverable(key.start, "Redefinition of property"); } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; + }; + + // ### Expression parsing + + // These nest, from the most general expression type at the top to + // 'atomic', nondivisible expression types at the bottom. Most of + // the functions will simply let the function(s) below them parse, + // and, *if* the syntactic construct they handle is present, wrap + // the AST node that the inner parser gave them in another node. + + // Parse a full expression. The optional arguments are used to + // forbid the `in` operator (in for loops initalization expressions) + // and provide reference for storing '=' operator inside shorthand + // property assignment in contexts where both object expression + // and object pattern might appear (so it's possible to raise + // delayed syntax error at correct position). + + pp$3.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr + }; + + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + pp$3.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(forInit) } + // The tokenizer will assume an expression is allowed after + // `yield`, but this isn't that kind of yield + else { this.exprAllowed = false; } + } + + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } + + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types.parenL || this.type === types.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types.eq) + { left = this.toAssignable(left, false, refDestructuringErrors); } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) + { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly + if (this.type === types.eq) + { this.checkLValPattern(left); } + else + { this.checkLValSimple(left); } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + return left + }; + + // Parse a ternary conditional (`?:`) operator. + + pp$3.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + if (this.eat(types.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression") + } + return expr + }; + + // Start the precedence parser. + + pp$3.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) + }; + + // Parse binary operators with the operator precedence parsing + // algorithm. `left` is the left-hand side of the operator. + // `minPrec` provides context that allows the function to stop and + // defer further parser to one of its callers when it encounters an + // operator that has a lower precedence than the set it is parsing. + + pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types._in)) { + if (prec > minPrec) { + var logical = this.type === types.logicalOR || this.type === types.logicalAND; + var coalesce = this.type === types.coalesce; + if (coalesce) { + // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. + // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. + prec = types.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) + } + } + return left + }; + + pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") + }; + + // Parse unary operators, both prefix and postfix. + + pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLValSimple(node.argument); } + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) + { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else { + expr = this.parseExprSubscripts(refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + + if (!incDec && this.eat(types.starstar)) { + if (sawUnary) + { this.unexpected(this.lastTokStart); } + else + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } + } else { + return expr + } + }; + + function isPrivateFieldAccess(node) { + return ( + node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || + node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) + ) + } + + // Parse call, dot, and `[]`-subscript expressions. + + pp$3.parseExprSubscripts = function(refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") + { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } + } + return result + }; + + pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && + this.potentialArrowAt === base.start; + var optionalChained = false; + + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained); + + if (element.optional) { optionalChained = true; } + if (element === base || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); + } + return element + } + + base = element; + } + }; + + pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types.questionDot); + if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } + + var computed = this.eat(types.bracketL); + if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(types.bracketR); + } else if (this.type === types.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) + { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true) + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this.parseTemplate({isTagged: true}); + base = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base + }; + + // Parse an atomic expression — either a single token that is an + // expression, an expression started by a keyword like `function` or + // `new`, or an expression wrapped in punctuation like `()`, `[]`, + // or `{}`. + + pp$3.parseExprAtom = function(refDestructuringErrors) { + // If a division operator appears in an expression position, the + // tokenizer got confused, and we force it to read a regexp instead. + if (this.type === types.slash) { this.readRegexp(); } + + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types._super: + if (!this.allowSuper) + { this.raise(this.start, "'super' keyword outside a method"); } + node = this.startNode(); + this.next(); + if (this.type === types.parenL && !this.allowDirectSuper) + { this.raise(node.start, "super() call outside constructor of a subclass"); } + // The `super` keyword can appear at below: + // SuperProperty: + // super [ Expression ] + // super . IdentifierName + // SuperCall: + // super ( Arguments ) + if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) + { this.unexpected(); } + return this.finishNode(node, "Super") + + case types._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") + + case types.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) + { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc && + (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) + } + } + return id + + case types.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node + + case types.num: case types.string: + return this.parseLiteral(this.value) + + case types._null: case types._true: case types._false: + node = this.startNode(); + node.value = this.type === types._null ? null : this.type === types._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal") + + case types.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) + { refDestructuringErrors.parenthesizedAssign = start; } + if (refDestructuringErrors.parenthesizedBind < 0) + { refDestructuringErrors.parenthesizedBind = start; } + } + return expr + + case types.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") + + case types.braceL: + return this.parseObj(false, refDestructuringErrors) + + case types._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) + + case types._class: + return this.parseClass(this.startNode(), false) + + case types._new: + return this.parseNew() + + case types.backQuote: + return this.parseTemplate() + + case types._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport() + } else { + return this.unexpected() + } + + default: + this.unexpected(); + } + }; + + pp$3.parseExprImport = function() { + var node = this.startNode(); + + // Consume `import` as an identifier for `import.meta`. + // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } + var meta = this.parseIdent(true); + + switch (this.type) { + case types.parenL: + return this.parseDynamicImport(node) + case types.dot: + node.meta = meta; + return this.parseImportMeta(node) + default: + this.unexpected(); + } + }; + + pp$3.parseDynamicImport = function(node) { + this.next(); // skip `(` + + // Parse node.source. + node.source = this.parseMaybeAssign(); + + // Verify ending. + if (!this.eat(types.parenR)) { + var errorPos = this.start; + if (this.eat(types.comma) && this.eat(types.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + + return this.finishNode(node, "ImportExpression") + }; + + pp$3.parseImportMeta = function(node) { + this.next(); // skip `.` + + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + + if (node.property.name !== "meta") + { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) + { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } + + return this.finishNode(node, "MetaProperty") + }; + + pp$3.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } + this.next(); + return this.finishNode(node, "Literal") + }; + + pp$3.parseParenExpression = function() { + this.expect(types.parenL); + var val = this.parseExpression(); + this.expect(types.parenR); + return val + }; + + pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + // Do not save awaitIdentPos to allow checking awaits nested in parameters + while (this.type !== types.parenR) { + first ? first = false : this.expect(types.comma); + if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) { + lastIsComma = true; + break + } else if (this.type === types.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } + break + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.start, innerEndLoc = this.startLoc; + this.expect(types.parenR); + + if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList) + } + + if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } + if (spreadStart) { this.unexpected(spreadStart); } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val + } + }; + + pp$3.parseParenItem = function(item) { + return item + }; + + pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) + }; + + // New's precedence is slightly tricky. It must allow its argument to + // be a `[]` or dot subscript expression, but not a call — at least, + // not without wrapping it in parentheses. Thus, it uses the noCalls + // argument to parseSubscripts to prevent it from consuming the + // argument list. + + var empty$1 = []; + + pp$3.parseNew = function() { + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } + var node = this.startNode(); + var meta = this.parseIdent(true); + if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { + node.meta = meta; + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } + if (!this.inNonArrowFunction) + { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import; + node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); + if (isImport && node.callee.type === "ImportExpression") { + this.raise(startPos, "Cannot use new with import()"); + } + if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } + else { node.arguments = empty$1; } + return this.finishNode(node, "NewExpression") + }; + + // Parse template expression. + + pp$3.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; + + var elem = this.startNode(); + if (this.type === types.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value, + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types.backQuote; + return this.finishNode(elem, "TemplateElement") + }; + + pp$3.parseTemplate = function(ref) { + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({isTagged: isTagged}); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); } + this.expect(types.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types.braceR); + node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); + } + this.next(); + return this.finishNode(node, "TemplateLiteral") + }; + + pp$3.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && + (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && + !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + // Parse an object literal or binding pattern. + + pp$3.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types.braceR)) { + if (!first) { + this.expect(types.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") + }; + + pp$3.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types.comma) { + this.raise(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement") + } + // To disallow parenthesized identifier via `this.toAssignable()`. + if (this.type === types.parenL && refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0) { + refDestructuringErrors.parenthesizedAssign = this.start; + } + if (refDestructuringErrors.parenthesizedBind < 0) { + refDestructuringErrors.parenthesizedBind = this.start; + } + } + // Parse argument. + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + // To disallow trailing comma via `this.toAssignable()`. + if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + // Finish + return this.finishNode(prop, "SpreadElement") + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) + { isGenerator = this.eat(types.star); } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); + this.parsePropertyName(prop, refDestructuringErrors); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property") + }; + + pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types.colon) + { this.unexpected(); } + + if (this.eat(types.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { + if (isPattern) { this.unexpected(); } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && + this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) { + if (isGenerator || isAsync) { this.unexpected(); } + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") + { this.raiseRecoverable(start, "getter should have no params"); } + else + { this.raiseRecoverable(start, "setter should have exactly one param"); } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } + } + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { this.unexpected(); } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = startPos; } + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.shorthand = true; + } else { this.unexpected(); } + }; + + pp$3.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types.bracketR); + return prop.key + } else { + prop.computed = false; + } + } + return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") + }; + + // Initialize empty function node. + + pp$3.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } + if (this.options.ecmaVersion >= 8) { node.async = false; } + }; + + // Parse object or class method. + + pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.initFunction(node); + if (this.options.ecmaVersion >= 6) + { node.generator = isGenerator; } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") + }; + + // Parse arrow function expression with given parameters. + + pp$3.parseArrowExpression = function(node, params, isAsync) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") + }; + + // Parse function body and check parameters. + + pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { + var isExpression = isArrowFunction && this.type !== types.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (useStrict && nonSimple) + { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } + } + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { this.strict = true; } + + // Add the params to varDeclaredNames to ensure that an error is thrown + // if a let/const declaration in the function clashes with one of the params. + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } + node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); + }; + + pp$3.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; + + if (param.type !== "Identifier") { return false + } } + return true + }; + + // Checks function params for various disallowed patterns such as using "eval" + // or "arguments" and duplicate parameters. + + pp$3.checkParams = function(node, allowDuplicates) { + var nameHash = Object.create(null); + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } + }; + + // Parses a comma-separated list of expressions, and returns them as + // an array. `close` is the token type that ends the list, and + // `allowEmpty` can be turned on to allow subsequent commas with + // nothing in between them to be parsed as `null` (which is needed + // for array literals). + + pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this.expect(types.comma); + if (allowTrailingComma && this.afterTrailingComma(close)) { break } + } else { first = false; } + + var elt = (void 0); + if (allowEmpty && this.type === types.comma) + { elt = null; } + else if (this.type === types.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0) + { refDestructuringErrors.trailingComma = this.start; } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts + }; + + pp$3.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; + + if (this.inGenerator && name === "yield") + { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } + if (this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } + if (this.currentThisScope().inClassFieldInit && name === "arguments") + { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } + if (this.keywords.test(name)) + { this.raise(start, ("Unexpected keyword '" + name + "'")); } + if (this.options.ecmaVersion < 6 && + this.input.slice(start, end).indexOf("\\") !== -1) { return } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } + this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); + } + }; + + // Parse the next token as an identifier. If `liberal` is true (used + // when parsing properties), it will also convert keywords into + // identifiers. + + pp$3.parseIdent = function(liberal, isBinding) { + var node = this.startNode(); + if (this.type === types.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + + // To fix https://github.com/acornjs/acorn/issues/575 + // `class` and `function` keywords push new context into this.context. + // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. + // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword + if ((node.name === "class" || node.name === "function") && + (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + } else { + this.unexpected(); + } + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node + }; + + pp$3.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types.privateId) { + node.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "PrivateIdentifier"); + + // For validating existence + if (this.privateNameStack.length === 0) { + this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); + } + + return node + }; + + // Parses yield expression inside generator. + + pp$3.parseYield = function(forInit) { + if (!this.yieldPos) { this.yieldPos = this.start; } + + var node = this.startNode(); + this.next(); + if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression") + }; + + pp$3.parseAwait = function() { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + return this.finishNode(node, "AwaitExpression") + }; + + var pp$4 = Parser.prototype; + + // This function is used to raise exceptions on parse errors. It + // takes an offset integer (into the current `input`) to indicate + // the location of the error, attaches the position to the end + // of the error message, and then raises a `SyntaxError` with that + // message. + + pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; err.loc = loc; err.raisedAt = this.pos; + throw err + }; + + pp$4.raiseRecoverable = pp$4.raise; + + pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } + }; + + var pp$5 = Parser.prototype; + + var Scope = function Scope(flags) { + this.flags = flags; + // A list of var-declared names in the current lexical scope + this.var = []; + // A list of lexically-declared names in the current lexical scope + this.lexical = []; + // A list of lexically-declared FunctionDeclaration names in the current lexical scope + this.functions = []; + // A switch to disallow the identifier reference 'arguments' + this.inClassFieldInit = false; + }; + + // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + + pp$5.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); + }; + + pp$5.exitScope = function() { + this.scopeStack.pop(); + }; + + // The spec says: + // > At the top level of a function, or script, function declarations are + // > treated like var declarations rather than like lexical declarations. + pp$5.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) + }; + + pp$5.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && (scope.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) + { redeclared = scope$2.lexical.indexOf(name) > -1; } + else + { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } + scope$2.functions.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || + !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break + } + scope$3.var.push(name); + if (this.inModule && (scope$3.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + if (scope$3.flags & SCOPE_VAR) { break } + } + } + if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } + }; + + pp$5.checkLocalExport = function(id) { + // scope.functions must be empty as Module code is always strict. + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && + this.scopeStack[0].var.indexOf(id.name) === -1) { + this.undefinedExports[id.name] = id; + } + }; + + pp$5.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] + }; + + pp$5.currentVarScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { return scope } + } + }; + + // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. + pp$5.currentThisScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } + } + }; + + var Node = function Node(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) + { this.loc = new SourceLocation(parser, loc); } + if (parser.options.directSourceFile) + { this.sourceFile = parser.options.directSourceFile; } + if (parser.options.ranges) + { this.range = [pos, 0]; } + }; + + // Start an AST node, attaching a start offset. + + var pp$6 = Parser.prototype; + + pp$6.startNode = function() { + return new Node(this, this.start, this.startLoc) + }; + + pp$6.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) + }; + + // Finish an AST node, adding `type` and `end` properties. + + function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) + { node.loc.end = loc; } + if (this.options.ranges) + { node.range[1] = pos; } + return node + } + + pp$6.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) + }; + + // Finish node at given position + + pp$6.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) + }; + + pp$6.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { newNode[prop] = node[prop]; } + return newNode + }; + + // The algorithm used to determine whether a regexp can appear at a + + var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; + }; + + var types$1 = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) + }; + + var pp$7 = Parser.prototype; + + pp$7.initialContext = function() { + return [types$1.b_stat] + }; + + pp$7.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types$1.f_expr || parent === types$1.f_stat) + { return true } + if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) + { return !parent.isExpr } + + // The check for `tt.name && exprAllowed` detects whether we are + // after a `yield` or `of` construct. See the `updateContext` for + // `tt.name`. + if (prevType === types._return || prevType === types.name && this.exprAllowed) + { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } + if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) + { return true } + if (prevType === types.braceL) + { return parent === types$1.b_stat } + if (prevType === types._var || prevType === types._const || prevType === types.name) + { return false } + return !this.exprAllowed + }; + + pp$7.inGeneratorContext = function() { + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this.context[i]; + if (context.token === "function") + { return context.generator } + } + return false + }; + + pp$7.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types.dot) + { this.exprAllowed = false; } + else if (update = type.updateContext) + { update.call(this, prevType); } + else + { this.exprAllowed = type.beforeExpr; } + }; + + // Token-specific context update code + + types.parenR.updateContext = types.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return + } + var out = this.context.pop(); + if (out === types$1.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; + }; + + types.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); + this.exprAllowed = true; + }; + + types.dollarBraceL.updateContext = function() { + this.context.push(types$1.b_tmpl); + this.exprAllowed = true; + }; + + types.parenL.updateContext = function(prevType) { + var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; + this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); + this.exprAllowed = true; + }; + + types.incDec.updateContext = function() { + // tokExprAllowed stays unchanged + }; + + types._function.updateContext = types._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types._else && + !(prevType === types.semi && this.curContext() !== types$1.p_stat) && + !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && + !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) + { this.context.push(types$1.f_expr); } + else + { this.context.push(types$1.f_stat); } + this.exprAllowed = false; + }; + + types.backQuote.updateContext = function() { + if (this.curContext() === types$1.q_tmpl) + { this.context.pop(); } + else + { this.context.push(types$1.q_tmpl); } + this.exprAllowed = false; + }; + + types.star.updateContext = function(prevType) { + if (prevType === types._function) { + var index = this.context.length - 1; + if (this.context[index] === types$1.f_expr) + { this.context[index] = types$1.f_expr_gen; } + else + { this.context[index] = types$1.f_gen; } + } + this.exprAllowed = true; + }; + + types.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { + if (this.value === "of" && !this.exprAllowed || + this.value === "yield" && this.inGeneratorContext()) + { allowed = true; } + } + this.exprAllowed = allowed; + }; + + // This file contains Unicode properties extracted from the ECMAScript + // specification. The lists are extracted like so: + // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) + + // #table-binary-unicode-properties + var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; + var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; + var ecma11BinaryProperties = ecma10BinaryProperties; + var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; + var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties + }; + + // #table-unicode-general-category-values + var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; + + // #table-unicode-script-values + var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; + var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; + var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; + var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; + var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues + }; + + var data = {}; + function buildUnicodeData(ecmaVersion) { + var d = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; + + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; + } + buildUnicodeData(9); + buildUnicodeData(10); + buildUnicodeData(11); + buildUnicodeData(12); + + var pp$8 = Parser.prototype; + + var RegExpValidationState = function RegExpValidationState(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = []; + this.backReferenceNames = []; + }; + + RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; + }; + + RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); + }; + + // If u flag is given, this returns the code point at the index (it combines a surrogate pair). + // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). + RegExpValidationState.prototype.at = function at (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return c + } + var next = s.charCodeAt(i + 1); + return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c + }; + + RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || + (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { + return i + 1 + } + return i + 2 + }; + + RegExpValidationState.prototype.current = function current (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.pos, forceU) + }; + + RegExpValidationState.prototype.lookahead = function lookahead (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.nextIndex(this.pos, forceU), forceU) + }; + + RegExpValidationState.prototype.advance = function advance (forceU) { + if ( forceU === void 0 ) forceU = false; + + this.pos = this.nextIndex(this.pos, forceU); + }; + + RegExpValidationState.prototype.eat = function eat (ch, forceU) { + if ( forceU === void 0 ) forceU = false; + + if (this.current(forceU) === ch) { + this.advance(forceU); + return true + } + return false + }; + + function codePointToString(ch) { + if (ch <= 0xFFFF) { return String.fromCharCode(ch) } + ch -= 0x10000; + return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) + } + + /** + * Validate the flags part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$8.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } + } + }; + + /** + * Validate the pattern part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$8.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + + // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of + // parsing contains a |GroupName|, reparse with the goal symbol + // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* + // exception if _P_ did not conform to the grammar, if any elements of _P_ + // were not matched by the parse, or if any Early Error conditions exist. + if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { + state.switchN = true; + this.regexp_pattern(state); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern + pp$8.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames.length = 0; + state.backReferenceNames.length = 0; + + this.regexp_disjunction(state); + + if (state.pos !== state.source.length) { + // Make the same messages as V8. + if (state.eat(0x29 /* ) */)) { + state.raise("Unmatched ')'"); + } + if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; + + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction + pp$8.regexp_disjunction = function(state) { + this.regexp_alternative(state); + while (state.eat(0x7C /* | */)) { + this.regexp_alternative(state); + } + + // Make the same message as V8. + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(0x7B /* { */)) { + state.raise("Lone quantifier brackets"); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative + pp$8.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) + { } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term + pp$8.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + // Handle `QuantifiableAssertion Quantifier` alternative. + // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion + // is a QuantifiableAssertion. + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + // Make the same message as V8. + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true + } + + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion + pp$8.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } + + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } + + // Lookahead / Lookbehind + if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(0x3C /* < */); + } + if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { + this.regexp_disjunction(state); + if (!state.eat(0x29 /* ) */)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true + } + } + + state.pos = start; + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier + pp$8.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; + + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix + pp$8.regexp_eatQuantifierPrefix = function(state, noError) { + return ( + state.eat(0x2A /* * */) || + state.eat(0x2B /* + */) || + state.eat(0x3F /* ? */) || + this.regexp_eatBracedQuantifier(state, noError) + ) + }; + pp$8.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(0x7B /* { */)) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat(0x7D /* } */)) { + // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom + pp$8.regexp_eatAtom = function(state) { + return ( + this.regexp_eatPatternCharacters(state) || + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) + ) + }; + pp$8.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatAtomEscape(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$8.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(0x28 /* ( */)) { + if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + return true + } + state.raise("Unterminated group"); + } + state.pos = start; + } + return false + }; + pp$8.regexp_eatCapturingGroup = function(state) { + if (state.eat(0x28 /* ( */)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 0x3F /* ? */) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + state.numCapturingParens += 1; + return true + } + state.raise("Unterminated group"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom + pp$8.regexp_eatExtendedAtom = function(state) { + return ( + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) || + this.regexp_eatInvalidBracedQuantifier(state) || + this.regexp_eatExtendedPatternCharacter(state) + ) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier + pp$8.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter + pp$8.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + function isSyntaxCharacter(ch) { + return ( + ch === 0x24 /* $ */ || + ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || + ch === 0x2E /* . */ || + ch === 0x3F /* ? */ || + ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter + // But eat eager. + pp$8.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter + pp$8.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if ( + ch !== -1 && + ch !== 0x24 /* $ */ && + !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && + ch !== 0x2E /* . */ && + ch !== 0x3F /* ? */ && + ch !== 0x5B /* [ */ && + ch !== 0x5E /* ^ */ && + ch !== 0x7C /* | */ + ) { + state.advance(); + return true + } + return false + }; + + // GroupSpecifier :: + // [empty] + // `?` GroupName + pp$8.regexp_groupSpecifier = function(state) { + if (state.eat(0x3F /* ? */)) { + if (this.regexp_eatGroupName(state)) { + if (state.groupNames.indexOf(state.lastStringValue) !== -1) { + state.raise("Duplicate capture group name"); + } + state.groupNames.push(state.lastStringValue); + return + } + state.raise("Invalid group"); + } + }; + + // GroupName :: + // `<` RegExpIdentifierName `>` + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$8.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(0x3C /* < */)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { + return true + } + state.raise("Invalid capture group name"); + } + return false + }; + + // RegExpIdentifierName :: + // RegExpIdentifierStart + // RegExpIdentifierName RegExpIdentifierPart + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$8.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true + } + return false + }; + + // RegExpIdentifierStart :: + // UnicodeIDStart + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + pp$8.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ + } + + // RegExpIdentifierPart :: + // UnicodeIDContinue + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + // + // + pp$8.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape + pp$8.regexp_eatAtomEscape = function(state) { + if ( + this.regexp_eatBackReference(state) || + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) || + (state.switchN && this.regexp_eatKGroupName(state)) + ) { + return true + } + if (state.switchU) { + // Make the same message as V8. + if (state.current() === 0x63 /* c */) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false + }; + pp$8.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape + if (n > state.maxBackReference) { + state.maxBackReference = n; + } + return true + } + if (n <= state.numCapturingParens) { + return true + } + state.pos = start; + } + return false + }; + pp$8.regexp_eatKGroupName = function(state) { + if (state.eat(0x6B /* k */)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true + } + state.raise("Invalid named reference"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape + pp$8.regexp_eatCharacterEscape = function(state) { + return ( + this.regexp_eatControlEscape(state) || + this.regexp_eatCControlLetter(state) || + this.regexp_eatZero(state) || + this.regexp_eatHexEscapeSequence(state) || + this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || + (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || + this.regexp_eatIdentityEscape(state) + ) + }; + pp$8.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(0x63 /* c */)) { + if (this.regexp_eatControlLetter(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$8.regexp_eatZero = function(state) { + if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape + pp$8.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 0x74 /* t */) { + state.lastIntValue = 0x09; /* \t */ + state.advance(); + return true + } + if (ch === 0x6E /* n */) { + state.lastIntValue = 0x0A; /* \n */ + state.advance(); + return true + } + if (ch === 0x76 /* v */) { + state.lastIntValue = 0x0B; /* \v */ + state.advance(); + return true + } + if (ch === 0x66 /* f */) { + state.lastIntValue = 0x0C; /* \f */ + state.advance(); + return true + } + if (ch === 0x72 /* r */) { + state.lastIntValue = 0x0D; /* \r */ + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter + pp$8.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + function isControlLetter(ch) { + return ( + (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || + (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence + pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if ( forceU === void 0 ) forceU = false; + + var start = state.pos; + var switchU = forceU || state.switchU; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { + var leadSurrogateEnd = state.pos; + if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 0xDC00 && trail <= 0xDFFF) { + state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + return true + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true + } + if ( + switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + + return false + }; + function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape + pp$8.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true + } + if (state.eat(0x2F /* / */)) { + state.lastIntValue = 0x2F; /* / */ + return true + } + return false + } + + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape + pp$8.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape + pp$8.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return true + } + + if ( + state.switchU && + this.options.ecmaVersion >= 9 && + (ch === 0x50 /* P */ || ch === 0x70 /* p */) + ) { + state.lastIntValue = -1; + state.advance(); + if ( + state.eat(0x7B /* { */) && + this.regexp_eatUnicodePropertyValueExpression(state) && + state.eat(0x7D /* } */) + ) { + return true + } + state.raise("Invalid property name"); + } + + return false + }; + function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) + } + + // UnicodePropertyValueExpression :: + // UnicodePropertyName `=` UnicodePropertyValue + // LoneUnicodePropertyNameOrValue + pp$8.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + + // UnicodePropertyName `=` UnicodePropertyValue + if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return true + } + } + state.pos = start; + + // LoneUnicodePropertyNameOrValue + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); + return true + } + return false + }; + pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!has(state.unicodeProperties.nonBinary, name)) + { state.raise("Invalid property name"); } + if (!state.unicodeProperties.nonBinary[name].test(value)) + { state.raise("Invalid property value"); } + }; + pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (!state.unicodeProperties.binary.test(nameOrValue)) + { state.raise("Invalid property name"); } + }; + + // UnicodePropertyName :: + // UnicodePropertyNameCharacters + pp$8.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 0x5F /* _ */ + } + + // UnicodePropertyValue :: + // UnicodePropertyValueCharacters + pp$8.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) + } + + // LoneUnicodePropertyNameOrValue :: + // UnicodePropertyValueCharacters + pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass + pp$8.regexp_eatCharacterClass = function(state) { + if (state.eat(0x5B /* [ */)) { + state.eat(0x5E /* ^ */); + this.regexp_classRanges(state); + if (state.eat(0x5D /* ] */)) { + return true + } + // Unreachable since it threw "unterminated regular expression" error before. + state.raise("Unterminated character class"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash + pp$8.regexp_classRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash + pp$8.regexp_eatClassAtom = function(state) { + var start = state.pos; + + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatClassEscape(state)) { + return true + } + if (state.switchU) { + // Make the same message as V8. + var ch$1 = state.current(); + if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + + var ch = state.current(); + if (ch !== 0x5D /* ] */) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape + pp$8.regexp_eatClassEscape = function(state) { + var start = state.pos; + + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true + } + + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; + } + + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter + pp$8.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$8.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(0x78 /* x */)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits + pp$8.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } + return state.pos !== start + }; + function isDecimalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits + pp$8.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start + }; + function isHexDigit(ch) { + return ( + (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || + (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || + (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) + ) + } + function hexToInt(ch) { + if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { + return 10 + (ch - 0x41 /* A */) + } + if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { + return 10 + (ch - 0x61 /* a */) + } + return ch - 0x30 /* 0 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence + // Allows only 0-377(octal) i.e. 0-255(decimal). + pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit + pp$8.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 0x30; /* 0 */ + state.advance(); + return true + } + state.lastIntValue = 0; + return false + }; + function isOctalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit + // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$8.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true + }; + + // Object type used to represent tokens. Note that normally, tokens + // simply exist as properties on the parser object. This is only + // used for the onToken callback and the external tokenizer. + + var Token = function Token(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) + { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } + if (p.options.ranges) + { this.range = [p.start, p.end]; } + }; + + // ## Tokenizer + + var pp$9 = Parser.prototype; + + // Move to the next token + + pp$9.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) + { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } + if (this.options.onToken) + { this.options.onToken(new Token(this)); } + + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); + }; + + pp$9.getToken = function() { + this.next(); + return new Token(this) + }; + + // If we're in an ES6 environment, make parsers iterable + if (typeof Symbol !== "undefined") + { pp$9[Symbol.iterator] = function() { + var this$1$1 = this; + + return { + next: function () { + var token = this$1$1.getToken(); + return { + done: token.type === types.eof, + value: token + } + } + } + }; } + + // Toggle strict mode. Re-reads the next number or string to please + // pedantic tests (`"use strict"; 010;` should fail). + + pp$9.curContext = function() { + return this.context[this.context.length - 1] + }; + + // Read a single token, updating the parser object's token-related + // properties. + + pp$9.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } + + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types.eof) } + + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } + }; + + pp$9.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + { return this.readWord() } + + return this.getTokenFromCode(code) + }; + + pp$9.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 0xd7ff || code >= 0xdc00) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 + }; + + pp$9.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } + this.pos = end + 2; + if (this.options.locations) { + lineBreakG.lastIndex = start; + var match; + while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { + ++this.curLine; + this.lineStart = match.index + match[0].length; + } + } + if (this.options.onComment) + { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()); } + }; + + pp$9.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) + { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()); } + }; + + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and. + + pp$9.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: case 160: // ' ' + ++this.pos; + break + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: case 8232: case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break + case 47: // '/' + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: // '*' + this.skipBlockComment(); + break + case 47: + this.skipLineComment(2); + break + default: + break loop + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop + } + } + } + }; + + // Called at the end of every token. Sets `end`, `val`, and + // maintains `context` and `exprAllowed`, and skips the space after + // the token, so that the next one's `start` will point at the + // right position. + + pp$9.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { this.endLoc = this.curPosition(); } + var prevType = this.type; + this.type = type; + this.value = val; + + this.updateContext(prevType); + }; + + // ### Token reading + + // This is the function that is called to fetch the next token. It + // is somewhat obscure, because it works in character codes rather + // than characters, and because operator parsing has been inlined + // into it. + // + // All in the name of speed. + // + pp$9.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { return this.readNumber(true) } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' + this.pos += 3; + return this.finishToken(types.ellipsis) + } else { + ++this.pos; + return this.finishToken(types.dot) + } + }; + + pp$9.readToken_slash = function() { // '/' + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { ++this.pos; return this.readRegexp() } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.slash, 1) + }; + + pp$9.readToken_mult_modulo_exp = function(code) { // '%*' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types.star : types.modulo; + + // exponentiation operator ** and **= + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + + if (next === 61) { return this.finishOp(types.assign, size + 1) } + return this.finishOp(tokentype, size) + }; + + pp$9.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { return this.finishOp(types.assign, 3) } + } + return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) + } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) + }; + + pp$9.readToken_caret = function() { // '^' + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.bitwiseXOR, 1) + }; + + pp$9.readToken_plus_min = function(code) { // '+-' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && + (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types.incDec, 2) + } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.plusMin, 1) + }; + + pp$9.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } + return this.finishOp(types.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `/g; +const scriptModuleRE$1 = /(]*type\s*=\s*(?:"module"|'module')[^>]*>)(.*?)<\/script>/gims; +function htmlInlineScriptProxyPlugin() { + return { + name: 'vite:html', + resolveId(id) { + if (htmlProxyRE.test(id)) { + return id; + } + }, + load(id) { + const proxyMatch = id.match(htmlProxyRE); + if (proxyMatch) { + const index = Number(proxyMatch[1]); + const file = cleanUrl(id); + const html = fs__default.readFileSync(file, 'utf-8').replace(htmlCommentRE, ''); + let match; + scriptModuleRE$1.lastIndex = 0; + for (let i = 0; i <= index; i++) { + match = scriptModuleRE$1.exec(html); + } + if (match) { + return match[2]; + } + else { + throw new Error(`No matching html proxy module found from ${id}`); + } + } + } + }; +} +// this extends the config in @vue/compiler-sfc with +const assetAttrsConfig = { + link: ['href'], + video: ['src', 'poster'], + source: ['src', 'srcset'], + img: ['src', 'srcset'], + image: ['xlink:href', 'href'], + use: ['xlink:href', 'href'] +}; +async function traverseHtml(html, filePath, visitor) { + // lazy load compiler + const { parse, transform } = await Promise.resolve().then(function () { return require('./dep-b541373d.js'); }).then(function (n) { return n.compilerDom_cjs; }); + // @vue/compiler-core doesn't like lowercase doctypes + html = html.replace(/ url.startsWith('#') || + isExternalUrl(url) || + isDataUrl(url) || + checkPublicFile(url, config); + return { + name: 'vite:build-html', + async transform(html, id) { + if (id.endsWith('.html')) { + const publicPath = `/${slash$3(path__default.relative(config.root, id))}`; + // pre-transform + html = await applyHtmlTransforms(html, preHooks, { + path: publicPath, + filename: id + }); + let js = ''; + const s = new MagicString(html); + const assetUrls = []; + let inlineModuleIndex = -1; + await traverseHtml(html, id, (node) => { + if (node.type !== 1 /* ELEMENT */) { + return; + } + let shouldRemove = false; + // script tags + if (node.tag === 'script') { + const { src, isModule } = getScriptInfo(node); + const url = src && src.value && src.value.content; + if (url && checkPublicFile(url, config)) { + // referencing public dir url, prefix with base + s.overwrite(src.value.loc.start.offset, src.value.loc.end.offset, `"${config.base + url.slice(1)}"`); + } + if (isModule) { + inlineModuleIndex++; + if (url && !isExcludedUrl(url)) { + // + js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`; + shouldRemove = true; + } + } + } + // For asset references in index.html, also generate an import + // statement for each - this will be handled by the asset plugin + const assetAttrs = assetAttrsConfig[node.tag]; + if (assetAttrs) { + for (const p of node.props) { + if (p.type === 6 /* ATTRIBUTE */ && + p.value && + assetAttrs.includes(p.name)) { + const url = p.value.content; + if (!isExcludedUrl(url)) { + if (node.tag === 'link' && isCSSRequest(url)) { + // CSS references, convert to import + js += `\nimport ${JSON.stringify(url)}`; + shouldRemove = true; + } + else { + assetUrls.push(p); + } + } + else if (checkPublicFile(url, config)) { + s.overwrite(p.value.loc.start.offset, p.value.loc.end.offset, `"${config.base + url.slice(1)}"`); + } + } + } + } + if (shouldRemove) { + // remove the script tag from the html. we are going to inject new + // ones in the end. + s.remove(node.loc.start.offset, node.loc.end.offset); + } + }); + // for each encountered asset url, rewrite original html so that it + // references the post-build location. + for (const attr of assetUrls) { + const value = attr.value; + try { + const url = attr.name === 'srcset' + ? await processSrcSet(value.content, ({ url }) => urlToBuiltUrl(url, id, config, this)) + : await urlToBuiltUrl(value.content, id, config, this); + s.overwrite(value.loc.start.offset, value.loc.end.offset, `"${url}"`); + } + catch (e) { + // #1885 preload may be pointing to urls that do not exist + // locally on disk + if (e.code !== 'ENOENT') { + throw e; + } + } + } + processedHtml.set(id, s.toString()); + // inject module preload polyfill + if (config.build.polyfillModulePreload) { + js = `import "${modulePreloadPolyfillId}";\n${js}`; + } + return js; + } + }, + async generateBundle(_, bundle) { + const analyzedChunk = new Map(); + const getPreloadLinksForChunk = (chunk, seen = new Set()) => { + const tags = []; + chunk.imports.forEach((file) => { + const importee = bundle[file]; + if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk' && !seen.has(file)) { + seen.add(file); + tags.push({ + tag: 'link', + attrs: { + rel: 'modulepreload', + href: toPublicPath(file, config) + } + }); + tags.push(...getPreloadLinksForChunk(importee, seen)); + } + }); + return tags; + }; + const getCssTagsForChunk = (chunk, seen = new Set()) => { + const tags = []; + if (!analyzedChunk.has(chunk)) { + analyzedChunk.set(chunk, 1); + chunk.imports.forEach((file) => { + const importee = bundle[file]; + if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk') { + tags.push(...getCssTagsForChunk(importee, seen)); + } + }); + } + const cssFiles = chunkToEmittedCssFileMap.get(chunk); + if (cssFiles) { + cssFiles.forEach((file) => { + if (!seen.has(file)) { + seen.add(file); + tags.push({ + tag: 'link', + attrs: { + rel: 'stylesheet', + href: toPublicPath(file, config) + } + }); + } + }); + } + return tags; + }; + for (const [id, html] of processedHtml) { + // resolve asset url references + let result = html.replace(assetUrlRE, (_, fileHash, postfix = '') => { + return config.base + getAssetFilename(fileHash, config) + postfix; + }); + // find corresponding entry chunk + const chunk = Object.values(bundle).find((chunk) => chunk.type === 'chunk' && + chunk.isEntry && + chunk.facadeModuleId === id); + // inject chunk asset links + if (chunk) { + const assetTags = [ + // js entry chunk for this page + { + tag: 'script', + attrs: { + type: 'module', + crossorigin: true, + src: toPublicPath(chunk.fileName, config) + } + }, + // preload for imports + ...getPreloadLinksForChunk(chunk), + ...getCssTagsForChunk(chunk) + ]; + result = injectToHead(result, assetTags); + } + // inject css link when cssCodeSplit is false + if (!config.build.cssCodeSplit) { + const cssChunk = Object.values(bundle).find((chunk) => chunk.type === 'asset' && chunk.name === 'style.css'); + if (cssChunk) { + result = injectToHead(result, [ + { + tag: 'link', + attrs: { + rel: 'stylesheet', + href: toPublicPath(cssChunk.fileName, config) + } + } + ]); + } + } + const shortEmitName = path__default.posix.relative(config.root, id); + result = await applyHtmlTransforms(result, postHooks, { + path: '/' + shortEmitName, + filename: id, + bundle, + chunk + }); + this.emitFile({ + type: 'asset', + fileName: shortEmitName, + source: result + }); + } + } + }; +} +function resolveHtmlTransforms(plugins) { + const preHooks = []; + const postHooks = []; + for (const plugin of plugins) { + const hook = plugin.transformIndexHtml; + if (hook) { + if (typeof hook === 'function') { + postHooks.push(hook); + } + else if (hook.enforce === 'pre') { + preHooks.push(hook.transform); + } + else { + postHooks.push(hook.transform); + } + } + } + return [preHooks, postHooks]; +} +async function applyHtmlTransforms(html, hooks, ctx) { + const headTags = []; + const headPrependTags = []; + const bodyTags = []; + const bodyPrependTags = []; + for (const hook of hooks) { + const res = await hook(html, ctx); + if (!res) { + continue; + } + if (typeof res === 'string') { + html = res; + } + else { + let tags; + if (Array.isArray(res)) { + tags = res; + } + else { + html = res.html || html; + tags = res.tags; + } + for (const tag of tags) { + if (tag.injectTo === 'body') { + bodyTags.push(tag); + } + else if (tag.injectTo === 'body-prepend') { + bodyPrependTags.push(tag); + } + else if (tag.injectTo === 'head') { + headTags.push(tag); + } + else { + headPrependTags.push(tag); + } + } + } + } + // inject tags + if (headPrependTags.length) { + html = injectToHead(html, headPrependTags, true); + } + if (headTags.length) { + html = injectToHead(html, headTags); + } + if (bodyPrependTags.length) { + html = injectToBody(html, bodyPrependTags, true); + } + if (bodyTags.length) { + html = injectToBody(html, bodyTags); + } + return html; +} +function toPublicPath(filename, config) { + return isExternalUrl(filename) ? filename : config.base + filename; +} +const headInjectRE = /<\/head>/; +const headPrependInjectRE = [//, //i]; +function injectToHead(html, tags, prepend = false) { + const tagsHtml = serializeTags(tags); + if (prepend) { + // inject after head or doctype + for (const re of headPrependInjectRE) { + if (re.test(html)) { + return html.replace(re, `$&\n${tagsHtml}`); + } + } + } + else { + // inject before head close + if (headInjectRE.test(html)) { + return html.replace(headInjectRE, `${tagsHtml}\n $&`); + } + } + // if no tag is present, just prepend + return tagsHtml + `\n` + html; +} +const bodyInjectRE = /<\/body>/; +const bodyPrependInjectRE = /]*>/; +function injectToBody(html, tags, prepend = false) { + if (prepend) { + // inject after body open + const tagsHtml = `\n` + serializeTags(tags); + if (bodyPrependInjectRE.test(html)) { + return html.replace(bodyPrependInjectRE, `$&\n${tagsHtml}`); + } + // if no body, prepend + return tagsHtml + `\n` + html; + } + else { + // inject before body close + const tagsHtml = `\n` + serializeTags(tags); + if (bodyInjectRE.test(html)) { + return html.replace(bodyInjectRE, `${tagsHtml}\n$&`); + } + // if no body, append + return html + `\n` + tagsHtml; + } +} +const unaryTags = new Set(['link', 'meta', 'base']); +function serializeTag({ tag, attrs, children }) { + if (unaryTags.has(tag)) { + return `<${tag}${serializeAttrs(attrs)}>`; + } + else { + return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children)}`; + } +} +function serializeTags(tags) { + if (typeof tags === 'string') { + return tags; + } + else if (tags) { + return ` ${tags.map(serializeTag).join('\n ')}`; + } + return ''; +} +function serializeAttrs(attrs) { + let res = ''; + for (const key in attrs) { + if (typeof attrs[key] === 'boolean') { + res += attrs[key] ? ` ${key}` : ``; + } + else { + res += ` ${key}=${JSON.stringify(attrs[key])}`; + } + } + return res; +} + +var stripBom = string => { + if (typeof string !== 'string') { + throw new TypeError(`Expected a string, got ${typeof string}`); + } + + // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string + // conversion translates it to FEFF (UTF-16 BOM) + if (string.charCodeAt(0) === 0xFEFF) { + return string.slice(1); + } + + return string; +}; + +const singleComment = Symbol('singleComment'); +const multiComment = Symbol('multiComment'); +const stripWithoutWhitespace = () => ''; +const stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, ' '); + +const isEscaped = (jsonString, quotePosition) => { + let index = quotePosition - 1; + let backslashCount = 0; + + while (jsonString[index] === '\\') { + index -= 1; + backslashCount += 1; + } + + return Boolean(backslashCount % 2); +}; + +var stripJsonComments = (jsonString, options = {}) => { + if (typeof jsonString !== 'string') { + throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``); + } + + const strip = options.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; + + let insideString = false; + let insideComment = false; + let offset = 0; + let result = ''; + + for (let i = 0; i < jsonString.length; i++) { + const currentCharacter = jsonString[i]; + const nextCharacter = jsonString[i + 1]; + + if (!insideComment && currentCharacter === '"') { + const escaped = isEscaped(jsonString, i); + if (!escaped) { + insideString = !insideString; + } + } + + if (insideString) { + continue; + } + + if (!insideComment && currentCharacter + nextCharacter === '//') { + result += jsonString.slice(offset, i); + offset = i; + insideComment = singleComment; + i++; + } else if (insideComment === singleComment && currentCharacter + nextCharacter === '\r\n') { + i++; + insideComment = false; + result += strip(jsonString, offset, i); + offset = i; + continue; + } else if (insideComment === singleComment && currentCharacter === '\n') { + insideComment = false; + result += strip(jsonString, offset, i); + offset = i; + } else if (!insideComment && currentCharacter + nextCharacter === '/*') { + result += jsonString.slice(offset, i); + offset = i; + insideComment = multiComment; + i++; + continue; + } else if (insideComment === multiComment && currentCharacter + nextCharacter === '*/') { + i++; + insideComment = false; + result += strip(jsonString, offset, i + 1); + offset = i + 1; + continue; + } + } + + return result + (insideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset)); +}; + +const debug$c = createDebugger('vite:esbuild'); +async function transformWithEsbuild(code, filename, options, inMap) { + var _a, _b, _c; + // if the id ends with a valid ext, use it (e.g. vue blocks) + // otherwise, cleanup the query before checking the ext + const ext = path__default.extname(/\.\w+$/.test(filename) ? filename : cleanUrl(filename)); + let loader = ext.slice(1); + if (loader === 'cjs' || loader === 'mjs') { + loader = 'js'; + } + // these fields would affect the compilation result + // https://esbuild.github.io/content-types/#tsconfig-json + const meaningfulFields = [ + 'jsxFactory', + 'jsxFragmentFactory', + 'useDefineForClassFields', + 'importsNotUsedAsValues' + ]; + const compilerOptionsForFile = {}; + if (loader === 'ts' || loader === 'tsx') { + const loadedTsconfig = await loadTsconfigJsonForFile(filename); + const loadedCompilerOptions = (_a = loadedTsconfig.compilerOptions) !== null && _a !== void 0 ? _a : {}; + for (const field of meaningfulFields) { + if (field in loadedCompilerOptions) { + // @ts-ignore TypeScript can't tell they are of the same type + compilerOptionsForFile[field] = loadedCompilerOptions[field]; + } + } + // align with TypeScript 4.3 + // https://github.com/microsoft/TypeScript/pull/42663 + if (((_b = loadedCompilerOptions.target) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'esnext') { + compilerOptionsForFile.useDefineForClassFields = + (_c = loadedCompilerOptions.useDefineForClassFields) !== null && _c !== void 0 ? _c : true; + } + } + const resolvedOptions = { + loader: loader, + sourcemap: true, + // ensure source file name contains full query + sourcefile: filename, + tsconfigRaw: { compilerOptions: compilerOptionsForFile }, + ...options + }; + delete resolvedOptions.include; + delete resolvedOptions.exclude; + delete resolvedOptions.jsxInject; + try { + const result = await esbuild.transform(code, resolvedOptions); + if (inMap) { + const nextMap = JSON.parse(result.map); + nextMap.sourcesContent = []; + return { + ...result, + map: combineSourcemaps(filename, [ + nextMap, + inMap + ]) + }; + } + else { + return { + ...result, + map: JSON.parse(result.map) + }; + } + } + catch (e) { + debug$c(`esbuild error with options used: `, resolvedOptions); + // patch error information + if (e.errors) { + e.frame = ''; + e.errors.forEach((m) => { + e.frame += `\n` + prettifyMessage(m, code); + }); + e.loc = e.errors[0].location; + } + throw e; + } +} +function esbuildPlugin(options = {}) { + const filter = createFilter$1(options.include || /\.(tsx?|jsx)$/, options.exclude || /\.js$/); + return { + name: 'vite:esbuild', + async transform(code, id) { + if (filter(id) || filter(cleanUrl(id))) { + const result = await transformWithEsbuild(code, id, options); + if (result.warnings.length) { + result.warnings.forEach((m) => { + this.warn(prettifyMessage(m, code)); + }); + } + if (options.jsxInject && /\.(?:j|t)sx\b/.test(id)) { + result.code = options.jsxInject + ';' + result.code; + } + return { + code: result.code, + map: result.map + }; + } + } + }; +} +const buildEsbuildPlugin = (config) => { + return { + name: 'vite:esbuild-transpile', + async renderChunk(code, chunk, opts) { + // @ts-ignore injected by @vitejs/plugin-legacy + if (opts.__vite_skip_esbuild__) { + return null; + } + const target = config.build.target; + const minify = config.build.minify === 'esbuild'; + if ((!target || target === 'esnext') && !minify) { + return null; + } + return transformWithEsbuild(code, chunk.fileName, { + target: target || undefined, + minify + }); + } + }; +}; +function prettifyMessage(m, code) { + let res = source.yellow(m.text); + if (m.location) { + const lines = code.split(/\r?\n/g); + const line = Number(m.location.line); + const column = Number(m.location.column); + const offset = lines + .slice(0, line - 1) + .map((l) => l.length) + .reduce((total, l) => total + l + 1, 0) + column; + res += `\n` + generateCodeFrame(code, offset, offset + 1); + } + return res + `\n`; +} +// modified from +/** + * Copyright (c) 2015 TypeStrong + * + * 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. + */ +async function findTSConfig(dir) { + const configFile = path__default.resolve(dir, 'tsconfig.json'); + const stats = await stat$4(configFile); + if (isFile(stats)) { + return configFile; + } + const parentDir = path__default.dirname(dir); + if (dir === parentDir) { + return; + } + return findTSConfig(parentDir); +} +/** + * Check if a file exists. + */ +function stat$4(filename) { + return new Promise((resolve, reject) => { + fs__default.stat(filename, (err, stats) => { + return err ? resolve() : resolve(stats); + }); + }); +} +/** + * Check filesystem stat is a directory. + */ +function isFile(stats) { + return stats ? stats.isFile() || stats.isFIFO() : false; +} +// from +// by @dominikg +/** + * replace dangling commas from pseudo-json string with single space + * + * limitations: + * - pseudo-json must not contain comments, use strip-json-comments before + * - only a single dangling comma before } or ] is removed + * stripDanglingComma('[1,2,]') === '[1,2 ] + * stripDanglingComma('[1,2,,]') === '[1,2, ] + * + * implementation heavily inspired by strip-json-comments + */ +function stripDanglingComma(jsonString) { + /** + * Check if char at qoutePosition is escaped by an odd number of backslashes preceding it + */ + function isEscaped(jsonString, quotePosition) { + let index = quotePosition - 1; + let backslashCount = 0; + while (jsonString[index] === '\\') { + index -= 1; + backslashCount += 1; + } + return backslashCount % 2 === 1; + } + let insideString = false; + let offset = 0; + let result = ''; + let danglingCommaPos = null; + for (let i = 0; i < jsonString.length; i++) { + const currentCharacter = jsonString[i]; + if (currentCharacter === '"') { + const escaped = isEscaped(jsonString, i); + if (!escaped) { + insideString = !insideString; + } + } + if (insideString) { + danglingCommaPos = null; + continue; + } + if (currentCharacter === ',') { + danglingCommaPos = i; + continue; + } + if (danglingCommaPos) { + if (currentCharacter === '}' || currentCharacter === ']') { + result += jsonString.slice(offset, danglingCommaPos) + ' '; + offset = danglingCommaPos + 1; + danglingCommaPos = null; + } + else if (!currentCharacter.match(/\s/)) { + danglingCommaPos = null; + } + } + } + return result + jsonString.substring(offset); +} +async function readTSConfig(configPath) { + const content = await new Promise((resolve, reject) => { + fs__default.readFile(configPath, 'utf-8', (err, data) => { + if (err) { + reject(err); + return; + } + resolve(stripJsonComments(stripBom(data))); + }); + }); + // tsconfig.json can be empty + if (/^\s*$/.test(content)) { + return {}; + } + return JSON.parse(stripDanglingComma(content)); +} +const tsconfigCache = new Map(); +async function loadTsconfigJsonForFile(filename) { + const directory = path__default.dirname(filename); + const cached = tsconfigCache.get(directory); + if (cached) { + return cached; + } + let configPath = await findTSConfig(directory); + let tsconfig = {}; + if (configPath) { + const visited = new Set(); + visited.add(configPath); + tsconfig = await readTSConfig(configPath); + while (tsconfig.extends) { + const configRequire = require$$0$9.createRequire(configPath); + const extendsPath = configRequire.resolve(tsconfig.extends); + const extendedConfig = await readTSConfig(extendsPath); + if (visited.has(extendsPath)) { + throw new Error(`Circular dependency detected in the "extends" field of ${configPath}`); + } + visited.add(extendsPath); + tsconfig = { + extends: extendedConfig.extends, + compilerOptions: { + ...extendedConfig.compilerOptions, + ...tsconfig.compilerOptions + } + }; + configPath = extendsPath; + } + } + tsconfigCache.set(directory, tsconfig); + return tsconfig; +} + +var dist = {}; + +var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(dist, "__esModule", { value: true }); +var Worker_1 = dist.Worker = void 0; +const os_1 = __importDefault(require$$0__default$1); +const worker_threads_1 = require$$1__default; +class Worker { + constructor(fn, options = {}) { + this.code = genWorkerCode(fn); + this.max = options.max || Math.max(1, os_1.default.cpus().length - 1); + this.pool = []; + this.idlePool = []; + this.queue = []; + } + async run(...args) { + const worker = await this._getAvailableWorker(); + return new Promise((resolve, reject) => { + worker.currentResolve = resolve; + worker.currentReject = reject; + worker.postMessage(args); + }); + } + stop() { + this.pool.forEach((w) => w.unref()); + this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.'))); + this.pool = []; + this.idlePool = []; + this.queue = []; + } + async _getAvailableWorker() { + // has idle one? + if (this.idlePool.length) { + return this.idlePool.shift(); + } + // can spawn more? + if (this.pool.length < this.max) { + const worker = new worker_threads_1.Worker(this.code, { eval: true }); + worker.on('message', (res) => { + worker.currentResolve && worker.currentResolve(res); + worker.currentResolve = null; + this._assignDoneWorker(worker); + }); + worker.on('error', (err) => { + worker.currentReject && worker.currentReject(err); + worker.currentReject = null; + }); + worker.on('exit', (code) => { + const i = this.pool.indexOf(worker); + if (i > -1) + this.pool.splice(i, 1); + if (code !== 0 && worker.currentReject) { + worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`)); + worker.currentReject = null; + } + }); + this.pool.push(worker); + return worker; + } + // no one is available, we have to wait + let resolve; + let reject; + const onWorkerAvailablePromise = new Promise((r, rj) => { + resolve = r; + reject = rj; + }); + this.queue.push([resolve, reject]); + return onWorkerAvailablePromise; + } + _assignDoneWorker(worker) { + // someone's waiting already? + if (this.queue.length) { + const [resolve] = this.queue.shift(); + resolve(worker); + return; + } + // take a rest. + this.idlePool.push(worker); + } +} +Worker_1 = dist.Worker = Worker; +function genWorkerCode(fn) { + return ` +const doWork = ${fn.toString()} + +const { parentPort } = require('worker_threads') + +parentPort.on('message', async (args) => { + const res = await doWork(...args) + parentPort.postMessage(res) +}) + `; +} + +function terserPlugin(options) { + const worker = new Worker_1((basedir, code, options) => { + // when vite is linked, the worker thread won't share the same resolve + // root with vite itself, so we have to pass in the basedir and resolve + // terser first. + // eslint-disable-next-line node/no-restricted-require + const terserPath = require.resolve('vite/dist/node/terser', { + paths: [basedir] + }); + return require(terserPath).minify(code, options); + }); + return { + name: 'vite:terser', + async renderChunk(code, _chunk, outputOptions) { + const res = await worker.run(__dirname, code, { + safari10: true, + ...options, + sourceMap: !!outputOptions.sourcemap, + module: outputOptions.format.startsWith('es'), + toplevel: outputOptions.format === 'cjs' + }); + return { + code: res.code, + map: res.map + }; + }, + closeBundle() { + worker.stop(); + } + }; +} + +function manifestPlugin(config) { + const manifest = {}; + let outputCount; + return { + name: 'vite:manifest', + buildStart() { + outputCount = 0; + }, + generateBundle({ format }, bundle) { + var _a; + function getChunkName(chunk) { + if (chunk.facadeModuleId) { + let name = normalizePath$4(path__default.relative(config.root, chunk.facadeModuleId)); + if (format === 'system' && !chunk.name.includes('-legacy')) { + const ext = path__default.extname(name); + name = name.slice(0, -ext.length) + `-legacy` + ext; + } + return name; + } + else { + return `_` + path__default.basename(chunk.fileName); + } + } + function getInternalImports(imports) { + const filteredImports = []; + for (const file of imports) { + if (bundle[file] === undefined) { + continue; + } + filteredImports.push(getChunkName(bundle[file])); + } + return filteredImports; + } + function createChunk(chunk) { + const manifestChunk = { + file: chunk.fileName + }; + if (chunk.facadeModuleId) { + manifestChunk.src = getChunkName(chunk); + } + if (chunk.isEntry) { + manifestChunk.isEntry = true; + } + if (chunk.isDynamicEntry) { + manifestChunk.isDynamicEntry = true; + } + if (chunk.imports.length) { + const internalImports = getInternalImports(chunk.imports); + if (internalImports.length > 0) { + manifestChunk.imports = internalImports; + } + } + if (chunk.dynamicImports.length) { + const internalImports = getInternalImports(chunk.dynamicImports); + if (internalImports.length > 0) { + manifestChunk.dynamicImports = internalImports; + } + } + const cssFiles = chunkToEmittedCssFileMap.get(chunk); + if (cssFiles) { + manifestChunk.css = [...cssFiles]; + } + const assets = chunkToEmittedAssetsMap.get(chunk); + if (assets) + [(manifestChunk.assets = [...assets])]; + return manifestChunk; + } + for (const file in bundle) { + const chunk = bundle[file]; + if (chunk.type === 'chunk') { + manifest[getChunkName(chunk)] = createChunk(chunk); + } + } + outputCount++; + const output = (_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.output; + const outputLength = Array.isArray(output) ? output.length : 1; + if (outputCount >= outputLength) { + this.emitFile({ + fileName: `manifest.json`, + type: 'asset', + source: JSON.stringify(manifest, null, 2) + }); + } + } + }; +} + +function walk$2(ast, { enter, leave }) { + return visit(ast, null, enter, leave); +} + +let should_skip = false; +let should_remove = false; +let replacement = null; +const context = { + skip: () => should_skip = true, + remove: () => should_remove = true, + replace: (node) => replacement = node +}; + +function replace(parent, prop, index, node) { + if (parent) { + if (index !== null) { + parent[prop][index] = node; + } else { + parent[prop] = node; + } + } +} + +function remove(parent, prop, index) { + if (parent) { + if (index !== null) { + parent[prop].splice(index, 1); + } else { + delete parent[prop]; + } + } +} + +function visit( + node, + parent, + enter, + leave, + prop, + index +) { + if (node) { + if (enter) { + const _should_skip = should_skip; + const _should_remove = should_remove; + const _replacement = replacement; + should_skip = false; + should_remove = false; + replacement = null; + + enter.call(context, node, parent, prop, index); + + if (replacement) { + node = replacement; + replace(parent, prop, index, node); + } + + if (should_remove) { + remove(parent, prop, index); + } + + const skipped = should_skip; + const removed = should_remove; + + should_skip = _should_skip; + should_remove = _should_remove; + replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + for (const key in node) { + const value = (node )[key]; + + if (typeof value !== 'object') { + continue; + } + + else if (Array.isArray(value)) { + for (let j = 0, k = 0; j < value.length; j += 1, k += 1) { + if (value[j] !== null && typeof value[j].type === 'string') { + if (!visit(value[j], node, enter, leave, key, k)) { + // removed + j--; + } + } + } + } + + else if (value !== null && typeof value.type === 'string') { + visit(value, node, enter, leave, key, null); + } + } + + if (leave) { + const _replacement = replacement; + const _should_remove = should_remove; + replacement = null; + should_remove = false; + + leave.call(context, node, parent, prop, index); + + if (replacement) { + node = replacement; + replace(parent, prop, index, node); + } + + if (should_remove) { + remove(parent, prop, index); + } + + const removed = should_remove; + + replacement = _replacement; + should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; +} + +const extractors = { + ArrayPattern(names, param) { + for (const element of param.elements) { + if (element) + extractors[element.type](names, element); + } + }, + AssignmentPattern(names, param) { + extractors[param.left.type](names, param.left); + }, + Identifier(names, param) { + names.push(param.name); + }, + MemberExpression() { }, + ObjectPattern(names, param) { + for (const prop of param.properties) { + // @ts-ignore Typescript reports that this is not a valid type + if (prop.type === 'RestElement') { + extractors.RestElement(names, prop); + } + else { + extractors[prop.value.type](names, prop.value); + } + } + }, + RestElement(names, param) { + extractors[param.argument.type](names, param.argument); + } +}; +const extractAssignedNames = function extractAssignedNames(param) { + const names = []; + extractors[param.type](names, param); + return names; +}; + +const blockDeclarations = { + const: true, + let: true +}; +class Scope$1 { + constructor(options = {}) { + this.parent = options.parent; + this.isBlockScope = !!options.block; + this.declarations = Object.create(null); + if (options.params) { + options.params.forEach((param) => { + extractAssignedNames(param).forEach((name) => { + this.declarations[name] = true; + }); + }); + } + } + addDeclaration(node, isBlockDeclaration, isVar) { + if (!isBlockDeclaration && this.isBlockScope) { + // it's a `var` or function node, and this + // is a block scope, so we need to go up + this.parent.addDeclaration(node, isBlockDeclaration, isVar); + } + else if (node.id) { + extractAssignedNames(node.id).forEach((name) => { + this.declarations[name] = true; + }); + } + } + contains(name) { + return this.declarations[name] || (this.parent ? this.parent.contains(name) : false); + } +} +const attachScopes = function attachScopes(ast, propertyName = 'scope') { + let scope = new Scope$1(); + walk$2(ast, { + enter(n, parent) { + const node = n; + // function foo () {...} + // class Foo {...} + if (/(Function|Class)Declaration/.test(node.type)) { + scope.addDeclaration(node, false, false); + } + // var foo = 1 + if (node.type === 'VariableDeclaration') { + const { kind } = node; + const isBlockDeclaration = blockDeclarations[kind]; + // don't add const/let declarations in the body of a for loop #113 + const parentType = parent ? parent.type : ''; + if (!(isBlockDeclaration && /ForOfStatement/.test(parentType))) { + node.declarations.forEach((declaration) => { + scope.addDeclaration(declaration, isBlockDeclaration, true); + }); + } + } + let newScope; + // create new function scope + if (/Function/.test(node.type)) { + const func = node; + newScope = new Scope$1({ + parent: scope, + block: false, + params: func.params + }); + // named function expressions - the name is considered + // part of the function's scope + if (func.type === 'FunctionExpression' && func.id) { + newScope.addDeclaration(func, false, false); + } + } + // create new block scope + if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) { + newScope = new Scope$1({ + parent: scope, + block: true + }); + } + // catch clause has its own block scope + if (node.type === 'CatchClause') { + newScope = new Scope$1({ + parent: scope, + params: node.param ? [node.param] : [], + block: true + }); + } + if (newScope) { + Object.defineProperty(node, propertyName, { + value: newScope, + configurable: true + }); + scope = newScope; + } + }, + leave(n) { + const node = n; + if (node[propertyName]) + scope = scope.parent; + } + }); + return scope; +}; + +// Helper since Typescript can't detect readonly arrays with Array.isArray +function isArray$2(arg) { + return Array.isArray(arg); +} +function ensureArray(thing) { + if (isArray$2(thing)) + return thing; + if (thing == null) + return []; + return [thing]; +} + +function getMatcherString(id, resolutionBase) { + if (resolutionBase === false) { + return id; + } + // resolve('') is valid and will default to process.cwd() + const basePath = path$w.resolve(resolutionBase || '') + .split(path$w.sep) + .join('/') + // escape all possible (posix + win) path characters that might interfere with regex + .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); + // Note that we use posix.join because: + // 1. the basePath has been normalized to use / + // 2. the incoming glob (id) matcher, also uses / + // otherwise Node will force backslash (\) on windows + return path$w.posix.join(basePath, id); +} +const createFilter = function createFilter(include, exclude, options) { + const resolutionBase = options && options.resolve; + const getMatcher = (id) => id instanceof RegExp + ? id + : { + test: (what) => { + // this refactor is a tad overly verbose but makes for easy debugging + const pattern = getMatcherString(id, resolutionBase); + const fn = picomatch$3(pattern, { dot: true }); + const result = fn(what); + return result; + } + }; + const includeMatchers = ensureArray(include).map(getMatcher); + const excludeMatchers = ensureArray(exclude).map(getMatcher); + return function result(id) { + if (typeof id !== 'string') + return false; + if (/\0/.test(id)) + return false; + const pathId = id.split(path$w.sep).join('/'); + for (let i = 0; i < excludeMatchers.length; ++i) { + const matcher = excludeMatchers[i]; + if (matcher.test(pathId)) + return false; + } + for (let i = 0; i < includeMatchers.length; ++i) { + const matcher = includeMatchers[i]; + if (matcher.test(pathId)) + return true; + } + return !includeMatchers.length; + }; +}; + +const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'; +const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'; +const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' ')); +forbiddenIdentifiers.add(''); +const makeLegalIdentifier = function makeLegalIdentifier(str) { + let identifier = str + .replace(/-(\w)/g, (_, letter) => letter.toUpperCase()) + .replace(/[^$_a-zA-Z0-9]/g, '_'); + if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) { + identifier = `_${identifier}`; + } + return identifier || '_'; +}; + +var path$h = path__default; + +var commondir = function (basedir, relfiles) { + if (relfiles) { + var files = relfiles.map(function (r) { + return path$h.resolve(basedir, r); + }); + } + else { + var files = basedir; + } + + var res = files.slice(1).reduce(function (ps, file) { + if (!file.match(/^([A-Za-z]:)?\/|\\/)) { + throw new Error('relative path without a basedir'); + } + + var xs = file.split(/\/+|\\+/); + for ( + var i = 0; + ps[i] === xs[i] && i < Math.min(ps.length, xs.length); + i++ + ); + return ps.slice(0, i); + }, files[0].split(/\/+|\\+/)); + + // Windows correctly handles paths with forward-slashes + return res.length > 1 ? res.join('/') : '/' +}; + +var old$1 = {}; + +// 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 pathModule = path__default; +var isWindows$3 = process.platform === 'win32'; +var fs$i = fs__default; + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } + + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } +} + +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} + +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows$3) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} + +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows$3) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} + +old$1.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows$3 && !knownHard[base]) { + fs$i.lstatSync(base); + knownHard[base] = true; + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } + + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs$i.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } + + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows$3) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs$i.statSync(base); + linkTarget = fs$i.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows$3) seenLinks[id] = linkTarget; + } + + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } + + if (cache) cache[original] = p; + + return p; +}; + + +old$1.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows$3 && !knownHard[base]) { + fs$i.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } + + return fs$i.lstat(base, gotStat); + } + + function gotStat(err, stat) { + if (err) return cb(err); + + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows$3) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs$i.stat(base, function(err) { + if (err) return cb(err); + + fs$i.readlink(base, function(err, target) { + if (!isWindows$3) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + + function gotTarget(err, target, base) { + if (err) return cb(err); + + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; + +var fs_realpath = realpath$2; +realpath$2.realpath = realpath$2; +realpath$2.sync = realpathSync; +realpath$2.realpathSync = realpathSync; +realpath$2.monkeypatch = monkeypatch; +realpath$2.unmonkeypatch = unmonkeypatch; + +var fs$h = fs__default; +var origRealpath = fs$h.realpath; +var origRealpathSync = fs$h.realpathSync; + +var version$1 = process.version; +var ok = /^v[0-5]\./.test(version$1); +var old = old$1; + +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} + +function realpath$2 (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } + + if (typeof cache === 'function') { + cb = cache; + cache = null; + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb); + } else { + cb(er, result); + } + }); +} + +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } + + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } + } +} + +function monkeypatch () { + fs$h.realpath = realpath$2; + fs$h.realpathSync = realpathSync; +} + +function unmonkeypatch () { + fs$h.realpath = origRealpath; + fs$h.realpathSync = origRealpathSync; +} + +var concatMap$1 = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray$1(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray$1 = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +var balancedMatch = balanced$1; +function balanced$1(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced$1.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} + +var concatMap = concatMap$1; +var balanced = balancedMatch; + +var braceExpansion = 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$1(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$1(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + 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$1(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$1(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand$1(m.post, false) + : ['']; + 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. + + // 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$1(m.post, false) + : ['']; + + 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 = concatMap(n, function(el) { return expand$1(el, 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; +} + +var minimatch_1 = minimatch$3; +minimatch$3.Minimatch = Minimatch$1; + +var path$g = { sep: '/' }; +try { + path$g = path__default; +} catch (er) {} + +var GLOBSTAR$1 = minimatch$3.GLOBSTAR = Minimatch$1.GLOBSTAR = {}; +var expand = braceExpansion; + +var 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() +var qmark = '[^/]'; + +// * => any number of characters +var 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})($|\\\/)).)*?'; + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!'); + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true; + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/; + +minimatch$3.filter = filter; +function filter (pattern, options) { + options = options || {}; + return function (p, i, list) { + return minimatch$3(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]; + }); + return t +} + +minimatch$3.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch$3 + + var orig = minimatch$3; + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + }; + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + }; + + return m +}; + +Minimatch$1.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch$1 + return minimatch$3.defaults(def).Minimatch +}; + +function minimatch$3 (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 === '' + + return new Minimatch$1(pattern, options).match(p) +} + +function Minimatch$1 (pattern, options) { + if (!(this instanceof Minimatch$1)) { + return new Minimatch$1(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {}; + pattern = pattern.trim(); + + // windows support: need to use /, not \ + if (path$g.sep !== '/') { + pattern = pattern.split(path$g.sep).join('/'); + } + + this.options = options; + this.set = []; + this.pattern = pattern; + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; + + // make the set of regexps etc. + this.make(); +} + +Minimatch$1.prototype.debug = function () {}; + +Minimatch$1.prototype.make = make; +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern; + var 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 + var set = this.globSet = this.braceExpand(); + + if (options.debug) this.debug = console.error; + + 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(function (s) { + return s.split(slashSplit) + }); + + this.debug(this.pattern, set); + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this); + + this.debug(this.pattern, set); + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }); + + this.debug(this.pattern, set); + + this.set = set; +} + +Minimatch$1.prototype.parseNegate = parseNegate; +function parseNegate () { + var pattern = this.pattern; + var negate = false; + var options = this.options; + var negateOffset = 0; + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate; + negateOffset++; + } + + 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$3.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +}; + +Minimatch$1.prototype.braceExpand = braceExpand; + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch$1) { + options = this.options; + } else { + options = {}; + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern; + + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// 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$1.prototype.parse = parse$c; +var SUBPARSE = {}; +function parse$c (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } + + var options = this.options; + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR$1 + 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; + } + } + + 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); + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c; + escaping = false; + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + 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 + } + + // 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 (!stateChar) { + re += '\\('; + continue + } + + 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 + } + + 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 + } + + 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 + } + + 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 + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // 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. + var cs = pattern.substring(classStart + 1, i); + try { + } catch (er) { + // not a valid class! + var 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(); + + if (escaping) { + // no need + escaping = false; + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\'; + } + + re += c; + + } // 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 = '\\'; + } + + // 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; + } + + // 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; + } + + // 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(/\)[+*?]?/, ''); + } + nlAfter = cleanAfter; + + var dollar = ''; + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$'; + } + 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; + } + + // 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) + } + + 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('$.') + } + + regExp._glob = pattern; + regExp._src = re; + + return regExp +} + +minimatch$3.makeRe = function (pattern, options) { + return new Minimatch$1(pattern, options || {}).makeRe() +}; + +Minimatch$1.prototype.makeRe = makeRe; +function 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. + var set = this.set; + + if (!set.length) { + 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$1) ? 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$3.match = function (list, pattern, options) { + options = options || {}; + var mm = new Minimatch$1(pattern, options); + list = list.filter(function (f) { + return mm.match(f) + }); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list +}; + +Minimatch$1.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$g.sep !== '/') { + f = f.split(path$g.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. + + var set = this.set; + this.debug(this.pattern, 'set', set); + + // 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 + } + + 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 + } + } + + // 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$1.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$1) { + 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 + 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') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase(); + } else { + 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 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 + } + + // 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, '\\$&') +} + +var inherits$1 = {exports: {}}; + +var inherits_browser = {exports: {}}; + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.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 + inherits_browser.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; + } + }; +} + +try { + var util$6 = require$$0__default$3; + /* istanbul ignore next */ + if (typeof util$6.inherits !== 'function') throw ''; + inherits$1.exports = util$6.inherits; +} catch (e) { + /* istanbul ignore next */ + inherits$1.exports = inherits_browser.exports; +} + +var pathIsAbsolute = {exports: {}}; + +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); +} + +pathIsAbsolute.exports = process.platform === 'win32' ? win32 : posix; +pathIsAbsolute.exports.posix = posix; +pathIsAbsolute.exports.win32 = win32; + +var common$6 = {}; + +common$6.setopts = setopts$2; +common$6.ownProp = ownProp$2; +common$6.makeAbs = makeAbs; +common$6.finish = finish; +common$6.mark = mark; +common$6.isIgnored = isIgnored$2; +common$6.childrenIgnored = childrenIgnored$2; + +function ownProp$2 (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var path$f = path__default; +var minimatch$2 = minimatch_1; +var isAbsolute$2 = pathIsAbsolute.exports; +var Minimatch = minimatch$2.Minimatch; + +function alphasort (a, b) { + return a.localeCompare(b, 'en') +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || []; + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore]; + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap); + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null; + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, ''); + gmatcher = new Minimatch(gpattern, { dot: true }); + } + + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts$2 (self, pattern, options) { + if (!options) + options = {}; + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern; + } + + self.silent = !!options.silent; + self.pattern = pattern; + self.strict = options.strict !== false; + self.realpath = !!options.realpath; + self.realpathCache = options.realpathCache || Object.create(null); + self.follow = !!options.follow; + self.dot = !!options.dot; + self.mark = !!options.mark; + self.nodir = !!options.nodir; + if (self.nodir) + self.mark = true; + self.sync = !!options.sync; + self.nounique = !!options.nounique; + self.nonull = !!options.nonull; + self.nosort = !!options.nosort; + self.nocase = !!options.nocase; + self.stat = !!options.stat; + self.noprocess = !!options.noprocess; + self.absolute = !!options.absolute; + + self.maxLength = options.maxLength || Infinity; + self.cache = options.cache || Object.create(null); + self.statCache = options.statCache || Object.create(null); + self.symlinks = options.symlinks || Object.create(null); + + setupIgnores(self, options); + + self.changedCwd = false; + var cwd = process.cwd(); + if (!ownProp$2(options, "cwd")) + self.cwd = cwd; + else { + self.cwd = path$f.resolve(options.cwd); + self.changedCwd = self.cwd !== cwd; + } + + self.root = options.root || path$f.resolve(self.cwd, "/"); + self.root = path$f.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$2(self.cwd) ? self.cwd : makeAbs(self, self.cwd); + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); + self.nomount = !!options.nomount; + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true; + options.nocomment = true; + + self.minimatch = new Minimatch(pattern, options); + self.options = self.minimatch.options; +} + +function finish (self) { + var nou = self.nounique; + var all = nou ? [] : Object.create(null); + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i]; + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i]; + if (nou) + all.push(literal); + else + all[literal] = true; + } + } else { + // had matches + var m = Object.keys(matches); + if (nou) + all.push.apply(all, m); + else + m.forEach(function (m) { + all[m] = true; + }); + } + } + + if (!nou) + all = Object.keys(all); + + if (!self.nosort) + all = all.sort(alphasort); + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]); + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)); + var c = self.cache[e] || self.cache[makeAbs(self, e)]; + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c); + return notDir + }); + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored$2(self, m) + }); + + self.found = all; +} + +function mark (self, p) { + var abs = makeAbs(self, p); + var c = self.cache[abs]; + var m = p; + if (c) { + var isDir = c === 'DIR' || Array.isArray(c); + var slash = p.slice(-1) === '/'; + + if (isDir && !slash) + m += '/'; + else if (!isDir && slash) + m = m.slice(0, -1); + + if (m !== p) { + var mabs = makeAbs(self, m); + self.statCache[mabs] = self.statCache[abs]; + self.cache[mabs] = self.cache[abs]; + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f; + if (f.charAt(0) === '/') { + abs = path$f.join(self.root, f); + } else if (isAbsolute$2(f) || f === '') { + abs = f; + } else if (self.changedCwd) { + abs = path$f.resolve(self.cwd, f); + } else { + abs = path$f.resolve(f); + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/'); + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored$2 (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored$2 (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +var sync$3 = globSync$1; +globSync$1.GlobSync = GlobSync$1; + +var fs$g = fs__default; +var rp$1 = fs_realpath; +var minimatch$1 = minimatch_1; +var path$e = path__default; +var assert$3 = require$$6__default; +var isAbsolute$1 = pathIsAbsolute.exports; +var common$5 = common$6; +var setopts$1 = common$5.setopts; +var ownProp$1 = common$5.ownProp; +var childrenIgnored$1 = common$5.childrenIgnored; +var isIgnored$1 = common$5.isIgnored; + +function globSync$1 (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync$1(pattern, options).found +} + +function GlobSync$1 (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync$1)) + return new GlobSync$1(pattern, options) + + setopts$1(this, pattern, options); + + if (this.noprocess) + return this + + var n = this.minimatch.set.length; + this.matches = new Array(n); + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false); + } + this._finish(); +} + +GlobSync$1.prototype._finish = function () { + assert$3(this instanceof GlobSync$1); + if (this.realpath) { + var self = this; + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null); + for (var p in matchset) { + try { + p = self._makeAbs(p); + var real = rp$1.realpathSync(p, self.realpathCache); + set[real] = true; + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true; + else + throw er + } + } + }); + } + common$5.finish(this); +}; + + +GlobSync$1.prototype._process = function (pattern, index, inGlobStar) { + assert$3(this instanceof GlobSync$1); + + // Get the first [n] parts of pattern that are all strings. + var n = 0; + while (typeof pattern[n] === 'string') { + n ++; + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix; + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index); + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null; + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/'); + break + } + + var remain = pattern.slice(n); + + // get the list of entries. + var read; + if (prefix === null) + read = '.'; + else if (isAbsolute$1(prefix) || isAbsolute$1(pattern.join('/'))) { + if (!prefix || !isAbsolute$1(prefix)) + prefix = '/' + prefix; + read = prefix; + } else + read = prefix; + + var abs = this._makeAbs(read); + + //if ignored, skip processing + if (childrenIgnored$1(this, read)) + return + + var isGlobStar = remain[0] === minimatch$1.GLOBSTAR; + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar); +}; + + +GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar); + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0]; + var negate = !!this.minimatch.negate; + var rawGlob = pn._glob; + var dotOk = this.dot || rawGlob.charAt(0) === '.'; + + var matchedEntries = []; + for (var i = 0; i < entries.length; i++) { + var e = entries[i]; + if (e.charAt(0) !== '.' || dotOk) { + var m; + if (negate && !prefix) { + m = !e.match(pn); + } else { + m = e.match(pn); + } + if (m) + matchedEntries.push(e); + } + } + + var len = matchedEntries.length; + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path$e.join(this.root, e); + } + this._emitMatch(index, e); + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift(); + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + var newPattern; + if (prefix) + newPattern = [prefix, e]; + else + newPattern = [e]; + this._process(newPattern.concat(remain), index, inGlobStar); + } +}; + + +GlobSync$1.prototype._emitMatch = function (index, e) { + if (isIgnored$1(this, e)) + return + + var abs = this._makeAbs(e); + + if (this.mark) + e = this._mark(e); + + if (this.absolute) { + e = abs; + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs]; + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true; + + if (this.stat) + this._stat(e); +}; + + +GlobSync$1.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries; + var lstat; + try { + lstat = fs$g.lstatSync(abs); + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink(); + this.symlinks[abs] = isSym; + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE'; + else + entries = this._readdir(abs, false); + + return entries +}; + +GlobSync$1.prototype._readdir = function (abs, inGlobStar) { + + if (inGlobStar && !ownProp$1(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp$1(this.cache, abs)) { + var c = this.cache[abs]; + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, fs$g.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er); + return null + } +}; + +GlobSync$1.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i]; + if (abs === '/') + e = abs + e; + else + e = abs + '/' + e; + this.cache[e] = true; + } + } + + this.cache[abs] = entries; + + // mark and cache dir-ness + return entries +}; + +GlobSync$1.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f); + this.cache[abs] = 'FILE'; + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd); + error.path = this.cwd; + error.code = er.code; + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false; + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false; + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er); + break + } +}; + +GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar); + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1); + var gspref = prefix ? [ prefix ] : []; + var noGlobStar = gspref.concat(remainWithoutGlobStar); + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false); + + var len = entries.length; + var isSym = this.symlinks[abs]; + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i]; + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar); + this._process(instead, index, true); + + var below = gspref.concat(entries[i], remain); + this._process(below, index, true); + } +}; + +GlobSync$1.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix); + + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute$1(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix); + if (prefix.charAt(0) === '/') { + prefix = path$e.join(this.root, prefix); + } else { + prefix = path$e.resolve(this.root, prefix); + if (trail) + prefix += '/'; + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/'); + + // Mark this as a match + this._emitMatch(index, prefix); +}; + +// Returns either 'DIR', 'FILE', or false +GlobSync$1.prototype._stat = function (f) { + var abs = this._makeAbs(f); + var needDir = f.slice(-1) === '/'; + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp$1(this.cache, abs)) { + var c = this.cache[abs]; + + if (Array.isArray(c)) + c = 'DIR'; + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var stat = this.statCache[abs]; + if (!stat) { + var lstat; + try { + lstat = fs$g.lstatSync(abs); + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false; + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = fs$g.statSync(abs); + } catch (er) { + stat = lstat; + } + } else { + stat = lstat; + } + } + + this.statCache[abs] = stat; + + var c = true; + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE'; + + this.cache[abs] = this.cache[abs] || c; + + if (needDir && c === 'FILE') + return false + + return c +}; + +GlobSync$1.prototype._mark = function (p) { + return common$5.mark(this, p) +}; + +GlobSync$1.prototype._makeAbs = function (f) { + return common$5.makeAbs(this, f) +}; + +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +var wrappy_1 = wrappy$2; +function wrappy$2 (fn, cb) { + if (fn && cb) return wrappy$2(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k]; + }); + + return wrapper + + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb = args[args.length-1]; + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k]; + }); + } + return ret + } +} + +var once$3 = {exports: {}}; + +var wrappy$1 = wrappy_1; +once$3.exports = wrappy$1(once$2); +once$3.exports.strict = wrappy$1(onceStrict); + +once$2.proto = once$2(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once$2(this) + }, + configurable: true + }); + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }); +}); + +function once$2 (fn) { + var f = function () { + if (f.called) return f.value + f.called = true; + return f.value = fn.apply(this, arguments) + }; + f.called = false; + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true; + return f.value = fn.apply(this, arguments) + }; + var name = fn.name || 'Function wrapped with `once`'; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f +} + +var wrappy = wrappy_1; +var reqs = Object.create(null); +var once$1 = once$3.exports; + +var inflight_1 = wrappy(inflight$1); + +function inflight$1 (key, cb) { + if (reqs[key]) { + reqs[key].push(cb); + return null + } else { + reqs[key] = [cb]; + return makeres(key) + } +} + +function makeres (key) { + return once$1(function RES () { + var cbs = reqs[key]; + var len = cbs.length; + var args = slice(arguments); + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args); + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len); + process.nextTick(function () { + RES.apply(null, args); + }); + } else { + delete reqs[key]; + } + } + }) +} + +function slice (args) { + var length = args.length; + var array = []; + + for (var i = 0; i < length; i++) array[i] = args[i]; + return array +} + +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +var glob_1 = glob; + +var fs$f = fs__default; +var rp = fs_realpath; +var minimatch = minimatch_1; +var inherits = inherits$1.exports; +var EE$1 = require$$0__default$6.EventEmitter; +var path$d = path__default; +var assert$2 = require$$6__default; +var isAbsolute = pathIsAbsolute.exports; +var globSync = sync$3; +var common$4 = common$6; +var setopts = common$4.setopts; +var ownProp = common$4.ownProp; +var inflight = inflight_1; +var childrenIgnored = common$4.childrenIgnored; +var isIgnored = common$4.isIgnored; + +var once = once$3.exports; + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {}; + if (!options) options = {}; + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = globSync; +var GlobSync = glob.GlobSync = globSync.GlobSync; + +// old api surface +glob.glob = glob; + +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin +} + +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_); + options.noprocess = true; + + var g = new Glob(pattern, options); + var set = g.minimatch.set; + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +}; + +glob.Glob = Glob; +inherits(Glob, EE$1); +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options; + options = null; + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options); + this._didRealPath = false; + + // process each pattern in the minimatch set + var n = this.minimatch.set.length; + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n); + + if (typeof cb === 'function') { + cb = once(cb); + this.on('error', cb); + this.on('end', function (matches) { + cb(null, matches); + }); + } + + var self = this; + this._processing = 0; + + this._emitQueue = []; + this._processQueue = []; + this.paused = false; + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true; + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done); + } + sync = false; + + function done () { + --self._processing; + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish(); + }); + } else { + self._finish(); + } + } + } +} + +Glob.prototype._finish = function () { + assert$2(this instanceof Glob); + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common$4.finish(this); + this.emit('end', this.found); +}; + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true; + + var n = this.matches.length; + if (n === 0) + return this._finish() + + var self = this; + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next); + + function next () { + if (--n === 0) + self._finish(); + } +}; + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index]; + if (!matchset) + return cb() + + var found = Object.keys(matchset); + var self = this; + var n = found.length; + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null); + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p); + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true; + else if (er.syscall === 'stat') + set[p] = true; + else + self.emit('error', er); // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set; + cb(); + } + }); + }); +}; + +Glob.prototype._mark = function (p) { + return common$4.mark(this, p) +}; + +Glob.prototype._makeAbs = function (f) { + return common$4.makeAbs(this, f) +}; + +Glob.prototype.abort = function () { + this.aborted = true; + this.emit('abort'); +}; + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true; + this.emit('pause'); + } +}; + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume'); + this.paused = false; + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0); + this._emitQueue.length = 0; + for (var i = 0; i < eq.length; i ++) { + var e = eq[i]; + this._emitMatch(e[0], e[1]); + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0); + this._processQueue.length = 0; + for (var i = 0; i < pq.length; i ++) { + var p = pq[i]; + this._processing--; + this._process(p[0], p[1], p[2], p[3]); + } + } + } +}; + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert$2(this instanceof Glob); + assert$2(typeof cb === 'function'); + + if (this.aborted) + return + + this._processing++; + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]); + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0; + while (typeof pattern[n] === 'string') { + n ++; + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix; + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb); + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null; + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/'); + break + } + + var remain = pattern.slice(n); + + // get the list of entries. + var read; + if (prefix === null) + read = '.'; + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix; + read = prefix; + } else + read = prefix; + + var abs = this._makeAbs(read); + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR; + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); +}; + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this; + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }); +}; + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0]; + var negate = !!this.minimatch.negate; + var rawGlob = pn._glob; + var dotOk = this.dot || rawGlob.charAt(0) === '.'; + + var matchedEntries = []; + for (var i = 0; i < entries.length; i++) { + var e = entries[i]; + if (e.charAt(0) !== '.' || dotOk) { + var m; + if (negate && !prefix) { + m = !e.match(pn); + } else { + m = e.match(pn); + } + if (m) + matchedEntries.push(e); + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length; + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path$d.join(this.root, e); + } + this._emitMatch(index, e); + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift(); + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + this._process([e].concat(remain), index, inGlobStar, cb); + } + cb(); +}; + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]); + return + } + + var abs = isAbsolute(e) ? e : this._makeAbs(e); + + if (this.mark) + e = this._mark(e); + + if (this.absolute) + e = abs; + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs]; + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true; + + var st = this.statCache[abs]; + if (st) + this.emit('stat', e, st); + + this.emit('match', e); +}; + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs; + var self = this; + var lstatcb = inflight(lstatkey, lstatcb_); + + if (lstatcb) + fs$f.lstat(abs, lstatcb); + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink(); + self.symlinks[abs] = isSym; + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE'; + cb(); + } else + self._readdir(abs, false, cb); + } +}; + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb); + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs]; + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + fs$f.readdir(abs, readdirCb(this, abs, cb)); +}; + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb); + else + self._readdirEntries(abs, entries, cb); + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i]; + if (abs === '/') + e = abs + e; + else + e = abs + '/' + e; + this.cache[e] = true; + } + } + + this.cache[abs] = entries; + return cb(null, entries) +}; + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f); + this.cache[abs] = 'FILE'; + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd); + error.path = this.cwd; + error.code = er.code; + this.emit('error', error); + this.abort(); + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false; + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false; + if (this.strict) { + this.emit('error', er); + // If the error is handled, then we abort + // if not, we threw out of here + this.abort(); + } + if (!this.silent) + console.error('glob error', er); + break + } + + return cb() +}; + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this; + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); + }); +}; + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1); + var gspref = prefix ? [ prefix ] : []; + var noGlobStar = gspref.concat(remainWithoutGlobStar); + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb); + + var isSym = this.symlinks[abs]; + var len = entries.length; + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i]; + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar); + this._process(instead, index, true, cb); + + var below = gspref.concat(entries[i], remain); + this._process(below, index, true, cb); + } + + cb(); +}; + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this; + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb); + }); +}; +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix); + if (prefix.charAt(0) === '/') { + prefix = path$d.join(this.root, prefix); + } else { + prefix = path$d.resolve(this.root, prefix); + if (trail) + prefix += '/'; + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/'); + + // Mark this as a match + this._emitMatch(index, prefix); + cb(); +}; + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f); + var needDir = f.slice(-1) === '/'; + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs]; + + if (Array.isArray(c)) + c = 'DIR'; + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var stat = this.statCache[abs]; + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE'; + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this; + var statcb = inflight('stat\0' + abs, lstatcb_); + if (statcb) + fs$f.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$f.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb); + else + self._stat2(f, abs, er, stat, cb); + }) + } else { + self._stat2(f, abs, er, lstat, cb); + } + } +}; + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false; + return cb() + } + + var needDir = f.slice(-1) === '/'; + this.statCache[abs] = stat; + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true; + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE'; + this.cache[abs] = this.cache[abs] || c; + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) +}; + +// @ts-check +/** @typedef { import('estree').BaseNode} BaseNode */ + +/** @typedef {{ + skip: () => void; + remove: () => void; + replace: (node: BaseNode) => void; +}} WalkerContext */ + +class WalkerBase { + constructor() { + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {BaseNode | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + } + + /** + * + * @param {any} parent + * @param {string} prop + * @param {number} index + * @param {BaseNode} node + */ + replace(parent, prop, index, node) { + if (parent) { + if (index !== null) { + parent[prop][index] = node; + } else { + parent[prop] = node; + } + } + } + + /** + * + * @param {any} parent + * @param {string} prop + * @param {number} index + */ + remove(parent, prop, index) { + if (parent) { + if (index !== null) { + parent[prop].splice(index, 1); + } else { + delete parent[prop]; + } + } + } +} + +// @ts-check + +/** @typedef { import('estree').BaseNode} BaseNode */ +/** @typedef { import('./walker.js').WalkerContext} WalkerContext */ + +/** @typedef {( + * this: WalkerContext, + * node: BaseNode, + * parent: BaseNode, + * key: string, + * index: number + * ) => void} SyncHandler */ + +class SyncWalker extends WalkerBase { + /** + * + * @param {SyncHandler} enter + * @param {SyncHandler} leave + */ + constructor(enter, leave) { + super(); + + /** @type {SyncHandler} */ + this.enter = enter; + + /** @type {SyncHandler} */ + this.leave = leave; + } + + /** + * + * @param {BaseNode} node + * @param {BaseNode} parent + * @param {string} [prop] + * @param {number} [index] + * @returns {BaseNode} + */ + visit(node, parent, prop, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + + this.enter.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const skipped = this.should_skip; + const removed = this.should_remove; + + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + for (const key in node) { + const value = node[key]; + + if (typeof value !== "object") { + continue; + } else if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + if (value[i] !== null && typeof value[i].type === 'string') { + if (!this.visit(value[i], node, key, i)) { + // removed + i--; + } + } + } + } else if (value !== null && typeof value.type === "string") { + this.visit(value, node, key, null); + } + } + + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + + this.leave.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const removed = this.should_remove; + + this.replacement = _replacement; + this.should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; + } +} + +// @ts-check + +/** @typedef { import('estree').BaseNode} BaseNode */ +/** @typedef { import('./sync.js').SyncHandler} SyncHandler */ +/** @typedef { import('./async.js').AsyncHandler} AsyncHandler */ + +/** + * + * @param {BaseNode} ast + * @param {{ + * enter?: SyncHandler + * leave?: SyncHandler + * }} walker + * @returns {BaseNode} + */ +function walk$1(ast, { enter, leave }) { + const instance = new SyncWalker(enter, leave); + return instance.visit(ast, null); +} + +function isReference(node, parent) { + if (node.type === 'MemberExpression') { + return !node.computed && isReference(node.object, node); + } + if (node.type === 'Identifier') { + if (!parent) + return true; + switch (parent.type) { + // disregard `bar` in `foo.bar` + case 'MemberExpression': return parent.computed || node === parent.object; + // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}` + case 'MethodDefinition': return parent.computed; + // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}` + case 'FieldDefinition': return parent.computed || node === parent.value; + // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }` + case 'Property': return parent.computed || node === parent.value; + // disregard the `bar` in `export { foo as bar }` or + // the foo in `import { foo as bar }` + case 'ExportSpecifier': + case 'ImportSpecifier': return node === parent.local; + // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}` + case 'LabeledStatement': + case 'BreakStatement': + case 'ContinueStatement': return false; + default: return true; + } + } + return false; +} + +var peerDependencies = { + rollup: "^2.38.3" +}; + +function tryParse(parse, code, id) { + try { + return parse(code, { allowReturnOutsideFunction: true }); + } catch (err) { + err.message += ` in ${id}`; + throw err; + } +} + +const firstpassGlobal = /\b(?:require|module|exports|global)\b/; + +const firstpassNoGlobal = /\b(?:require|module|exports)\b/; + +function hasCjsKeywords(code, ignoreGlobal) { + const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal; + return firstpass.test(code); +} + +/* eslint-disable no-underscore-dangle */ + +function analyzeTopLevelStatements(parse, code, id) { + const ast = tryParse(parse, code, id); + + let isEsModule = false; + let hasDefaultExport = false; + let hasNamedExports = false; + + for (const node of ast.body) { + switch (node.type) { + case 'ExportDefaultDeclaration': + isEsModule = true; + hasDefaultExport = true; + break; + case 'ExportNamedDeclaration': + isEsModule = true; + if (node.declaration) { + hasNamedExports = true; + } else { + for (const specifier of node.specifiers) { + if (specifier.exported.name === 'default') { + hasDefaultExport = true; + } else { + hasNamedExports = true; + } + } + } + break; + case 'ExportAllDeclaration': + isEsModule = true; + if (node.exported && node.exported.name === 'default') { + hasDefaultExport = true; + } else { + hasNamedExports = true; + } + break; + case 'ImportDeclaration': + isEsModule = true; + break; + } + } + + return { isEsModule, hasDefaultExport, hasNamedExports, ast }; +} + +const isWrappedId = (id, suffix) => id.endsWith(suffix); +const wrapId = (id, suffix) => `\0${id}${suffix}`; +const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length); + +const PROXY_SUFFIX = '?commonjs-proxy'; +const REQUIRE_SUFFIX = '?commonjs-require'; +const EXTERNAL_SUFFIX = '?commonjs-external'; +const EXPORTS_SUFFIX = '?commonjs-exports'; +const MODULE_SUFFIX = '?commonjs-module'; + +const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register'; +const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:'; +const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages'; + +const HELPERS_ID = '\0commonjsHelpers.js'; + +// `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers. +// Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled. +// This will no longer be necessary once Rollup switches to ES6 output, likely +// in Rollup 3 + +const HELPERS = ` +export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +export function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +export function getDefaultExportFromNamespaceIfPresent (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; +} + +export function getDefaultExportFromNamespaceIfNotNamed (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; +} + +export 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; +} +`; + +const FAILED_REQUIRE_ERROR = `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.');`; + +const HELPER_NON_DYNAMIC = ` +export function commonjsRequire (path) { + ${FAILED_REQUIRE_ERROR} +} +`; + +const getDynamicHelpers = (ignoreDynamicRequires) => ` +export function createModule(modulePath) { + return { + path: modulePath, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, base == null ? modulePath : base); + } + }; +} + +export function commonjsRegister (path, loader) { + DYNAMIC_REQUIRE_LOADERS[path] = loader; +} + +export function commonjsRegisterOrShort (path, to) { + const resolvedPath = commonjsResolveImpl(path, null, true); + if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) { + DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath]; + } else { + DYNAMIC_REQUIRE_SHORTS[path] = to; + } +} + +const DYNAMIC_REQUIRE_LOADERS = Object.create(null); +const DYNAMIC_REQUIRE_CACHE = Object.create(null); +const DYNAMIC_REQUIRE_SHORTS = Object.create(null); +const DEFAULT_PARENT_MODULE = { + id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: [] +}; +const CHECKED_EXTENSIONS = ['', '.js', '.json']; + +function normalize (path) { + path = path.replace(/\\\\/g, '/'); + const parts = path.split('/'); + const slashed = parts[0] === ''; + for (let i = 1; i < parts.length; i++) { + if (parts[i] === '.' || parts[i] === '') { + parts.splice(i--, 1); + } + } + for (let i = 1; i < parts.length; i++) { + if (parts[i] !== '..') continue; + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { + parts.splice(--i, 2); + i--; + } + } + path = parts.join('/'); + if (slashed && path[0] !== '/') + path = '/' + path; + else if (path.length === 0) + path = '.'; + return path; +} + +function join () { + if (arguments.length === 0) + return '.'; + let joined; + for (let i = 0; i < arguments.length; ++i) { + let arg = arguments[i]; + if (arg.length > 0) { + if (joined === undefined) + joined = arg; + else + joined += '/' + arg; + } + } + if (joined === undefined) + return '.'; + + return joined; +} + +function isPossibleNodeModulesPath (modulePath) { + let c0 = modulePath[0]; + if (c0 === '/' || c0 === '\\\\') return false; + let c1 = modulePath[1], c2 = modulePath[2]; + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) + return false; + return true; +} + +function dirname (path) { + if (path.length === 0) + return '.'; + + let i = path.length - 1; + while (i > 0) { + const c = path.charCodeAt(i); + if ((c === 47 || c === 92) && i !== path.length - 1) + break; + i--; + } + + if (i > 0) + return path.substr(0, i); + + if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92) + return path.charAt(0); + + return '.'; +} + +export function commonjsResolveImpl (path, originalModuleDir, testCache) { + const shouldTryNodeModules = isPossibleNodeModulesPath(path); + path = normalize(path); + let relPath; + if (path[0] === '/') { + originalModuleDir = '/'; + } + while (true) { + if (!shouldTryNodeModules) { + relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path; + } else if (originalModuleDir) { + relPath = normalize(originalModuleDir + '/node_modules/' + path); + } else { + relPath = normalize(join('node_modules', path)); + } + + if (relPath.endsWith('/..')) { + break; // Travelled too far up, avoid infinite loop + } + + for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) { + const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex]; + if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) { + return resolvedPath; + } + if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) { + return resolvedPath; + } + if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) { + return resolvedPath; + } + } + if (!shouldTryNodeModules) break; + const nextDir = normalize(originalModuleDir + '/..'); + if (nextDir === originalModuleDir) break; + originalModuleDir = nextDir; + } + return null; +} + +export function commonjsResolve (path, originalModuleDir) { + const resolvedPath = commonjsResolveImpl(path, originalModuleDir); + if (resolvedPath !== null) { + return resolvedPath; + } + return require.resolve(path); +} + +export function commonjsRequire (path, originalModuleDir) { + let resolvedPath = commonjsResolveImpl(path, originalModuleDir, true); + if (resolvedPath !== null) { + let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath]; + if (cachedModule) return cachedModule.exports; + let shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath]; + if (shortTo) { + cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo]; + if (cachedModule) + return cachedModule.exports; + resolvedPath = commonjsResolveImpl(shortTo, null, true); + } + const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath]; + if (loader) { + DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = { + id: resolvedPath, + filename: resolvedPath, + path: dirname(resolvedPath), + exports: {}, + parent: DEFAULT_PARENT_MODULE, + loaded: false, + children: [], + paths: [], + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base); + } + }; + try { + loader.call(commonjsGlobal, cachedModule, cachedModule.exports); + } catch (error) { + delete DYNAMIC_REQUIRE_CACHE[resolvedPath]; + throw error; + } + cachedModule.loaded = true; + return cachedModule.exports; + }; + } + ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR} +} + +commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE; +commonjsRequire.resolve = commonjsResolve; +`; + +function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) { + return `${HELPERS}${ + isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC + }`; +} + +/* eslint-disable import/prefer-default-export */ + +function deconflict(scopes, globals, identifier) { + let i = 1; + let deconflicted = makeLegalIdentifier(identifier); + const hasConflicts = () => + scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted); + + while (hasConflicts()) { + deconflicted = makeLegalIdentifier(`${identifier}_${i}`); + i += 1; + } + + for (const scope of scopes) { + scope.declarations[deconflicted] = true; + } + + return deconflicted; +} + +function getName(id) { + const name = makeLegalIdentifier(path$w.basename(id, path$w.extname(id))); + if (name !== 'index') { + return name; + } + return makeLegalIdentifier(path$w.basename(path$w.dirname(id))); +} + +function normalizePathSlashes(path) { + return path.replace(/\\/g, '/'); +} + +const VIRTUAL_PATH_BASE = '/$$rollup_base$$'; +const getVirtualPathForDynamicRequirePath = (path, commonDir) => { + const normalizedPath = normalizePathSlashes(path); + return normalizedPath.startsWith(commonDir) + ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length) + : normalizedPath; +}; + +function getPackageEntryPoint(dirPath) { + let entryPoint = 'index.js'; + + try { + if (fs$v.existsSync(path$w.join(dirPath, 'package.json'))) { + entryPoint = + JSON.parse(fs$v.readFileSync(path$w.join(dirPath, 'package.json'), { encoding: 'utf8' })).main || + entryPoint; + } + } catch (ignored) { + // ignored + } + + return entryPoint; +} + +function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) { + let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`; + for (const dir of dynamicRequireModuleDirPaths) { + const entryPoint = getPackageEntryPoint(dir); + + code += `\ncommonjsRegisterOrShort(${JSON.stringify( + getVirtualPathForDynamicRequirePath(dir, commonDir) + )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(path$w.join(dir, entryPoint), commonDir))});`; + } + return code; +} + +function getDynamicPackagesEntryIntro( + dynamicRequireModuleDirPaths, + dynamicRequireModuleSet +) { + let dynamicImports = Array.from( + dynamicRequireModuleSet, + (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});` + ).join('\n'); + + if (dynamicRequireModuleDirPaths.length) { + dynamicImports += `require(${JSON.stringify( + wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX) + )});`; + } + + return dynamicImports; +} + +function isDynamicModuleImport(id, dynamicRequireModuleSet) { + const normalizedPath = normalizePathSlashes(id); + return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json'); +} + +function isDirectory(path) { + try { + if (fs$v.statSync(path).isDirectory()) return true; + } catch (ignored) { + // Nothing to do here + } + return false; +} + +function getDynamicRequirePaths(patterns) { + const dynamicRequireModuleSet = new Set(); + for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) { + const isNegated = pattern.startsWith('!'); + const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet); + for (const path of glob_1.sync(isNegated ? pattern.substr(1) : pattern)) { + modifySet(normalizePathSlashes(path$w.resolve(path))); + if (isDirectory(path)) { + modifySet(normalizePathSlashes(path$w.resolve(path$w.join(path, getPackageEntryPoint(path))))); + } + } + } + const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) => + isDirectory(path) + ); + return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths }; +} + +function getCommonJSMetaPromise(commonJSMetaPromises, id) { + let commonJSMetaPromise = commonJSMetaPromises.get(id); + if (commonJSMetaPromise) return commonJSMetaPromise.promise; + + const promise = new Promise((resolve) => { + commonJSMetaPromise = { + resolve, + promise: null + }; + commonJSMetaPromises.set(id, commonJSMetaPromise); + }); + commonJSMetaPromise.promise = promise; + + return promise; +} + +function setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) { + const commonJSMetaPromise = commonJSMetaPromises.get(id); + if (commonJSMetaPromise) { + if (commonJSMetaPromise.resolve) { + commonJSMetaPromise.resolve(commonjsMeta); + commonJSMetaPromise.resolve = null; + } + } else { + commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null }); + } +} + +// e.g. id === "commonjsHelpers?commonjsRegister" +function getSpecificHelperProxy(id) { + return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`; +} + +function getUnknownRequireProxy(id, requireReturnsDefault) { + if (requireReturnsDefault === true || id.endsWith('.json')) { + return `export {default} from ${JSON.stringify(id)};`; + } + const name = getName(id); + const exported = + requireReturnsDefault === 'auto' + ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` + : requireReturnsDefault === 'preferred' + ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` + : !requireReturnsDefault + ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` + : `export default ${name};`; + return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`; +} + +function getDynamicJsonProxy(id, commonDir) { + const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length)); + return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify( + getVirtualPathForDynamicRequirePath(normalizedPath, commonDir) + )}, function (module, exports) { + module.exports = require(${JSON.stringify(normalizedPath)}); +});`; +} + +function getDynamicRequireProxy(normalizedPath, commonDir) { + return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify( + getVirtualPathForDynamicRequirePath(normalizedPath, commonDir) + )}, function (module, exports) { + ${fs$v.readFileSync(normalizedPath, { encoding: 'utf8' })} +});`; +} + +async function getStaticRequireProxy( + id, + requireReturnsDefault, + esModulesWithDefaultExport, + esModulesWithNamedExports, + commonJsMetaPromises +) { + const name = getName(id); + const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id); + if (commonjsMeta && commonjsMeta.isCommonJS) { + return `export { __moduleExports as default } from ${JSON.stringify(id)};`; + } else if (commonjsMeta === null) { + return getUnknownRequireProxy(id, requireReturnsDefault); + } else if (!requireReturnsDefault) { + return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify( + id + )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`; + } else if ( + requireReturnsDefault !== true && + (requireReturnsDefault === 'namespace' || + !esModulesWithDefaultExport.has(id) || + (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id))) + ) { + return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`; + } + return `export { default } from ${JSON.stringify(id)};`; +} + +/* eslint-disable no-param-reassign, no-undefined */ + +function getCandidatesForExtension(resolved, extension) { + return [resolved + extension, `${resolved}${path$w.sep}index${extension}`]; +} + +function getCandidates(resolved, extensions) { + return extensions.reduce( + (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), + [resolved] + ); +} + +function getResolveId(extensions) { + function resolveExtensions(importee, importer) { + // not our problem + if (importee[0] !== '.' || !importer) return undefined; + + const resolved = path$w.resolve(path$w.dirname(importer), importee); + const candidates = getCandidates(resolved, extensions); + + for (let i = 0; i < candidates.length; i += 1) { + try { + const stats = fs$v.statSync(candidates[i]); + if (stats.isFile()) return { id: candidates[i] }; + } catch (err) { + /* noop */ + } + } + + return undefined; + } + + return function resolveId(importee, rawImporter) { + if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) { + return importee; + } + + const importer = + rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX) + ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX) + : rawImporter; + + // Except for exports, proxies are only importing resolved ids, + // no need to resolve again + if (importer && isWrappedId(importer, PROXY_SUFFIX)) { + return importee; + } + + const isProxyModule = isWrappedId(importee, PROXY_SUFFIX); + const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX); + let isModuleRegistration = false; + + if (isProxyModule) { + importee = unwrapId(importee, PROXY_SUFFIX); + } else if (isRequiredModule) { + importee = unwrapId(importee, REQUIRE_SUFFIX); + + isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX); + if (isModuleRegistration) { + importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX); + } + } + + if ( + importee.startsWith(HELPERS_ID) || + importee === DYNAMIC_PACKAGES_ID || + importee.startsWith(DYNAMIC_JSON_PREFIX) + ) { + return importee; + } + + if (importee.startsWith('\0')) { + return null; + } + + return this.resolve(importee, importer, { + skipSelf: true, + custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } } + }).then((resolved) => { + if (!resolved) { + resolved = resolveExtensions(importee, importer); + } + if (resolved && isProxyModule) { + resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX); + resolved.external = false; + } else if (resolved && isModuleRegistration) { + resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX); + } else if (!resolved && (isProxyModule || isRequiredModule)) { + return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false }; + } + return resolved; + }); + }; +} + +function validateRollupVersion(rollupVersion, peerDependencyVersion) { + const [major, minor] = rollupVersion.split('.').map(Number); + const versionRegexp = /\^(\d+\.\d+)\.\d+/g; + let minMajor = Infinity; + let minMinor = Infinity; + let foundVersion; + // eslint-disable-next-line no-cond-assign + while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) { + const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number); + if (foundMajor < minMajor) { + minMajor = foundMajor; + minMinor = foundMinor; + } + } + if (major < minMajor || (major === minMajor && minor < minMinor)) { + throw new Error( + `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.` + ); + } +} + +const operators = { + '==': (x) => equals(x.left, x.right, false), + + '!=': (x) => not(operators['=='](x)), + + '===': (x) => equals(x.left, x.right, true), + + '!==': (x) => not(operators['==='](x)), + + '!': (x) => isFalsy(x.argument), + + '&&': (x) => isTruthy(x.left) && isTruthy(x.right), + + '||': (x) => isTruthy(x.left) || isTruthy(x.right) +}; + +function not(value) { + return value === null ? value : !value; +} + +function equals(a, b, strict) { + if (a.type !== b.type) return null; + // eslint-disable-next-line eqeqeq + if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value; + return null; +} + +function isTruthy(node) { + if (!node) return false; + if (node.type === 'Literal') return !!node.value; + if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression); + if (node.operator in operators) return operators[node.operator](node); + return null; +} + +function isFalsy(node) { + return not(isTruthy(node)); +} + +function getKeypath(node) { + const parts = []; + + while (node.type === 'MemberExpression') { + if (node.computed) return null; + + parts.unshift(node.property.name); + // eslint-disable-next-line no-param-reassign + node = node.object; + } + + if (node.type !== 'Identifier') return null; + + const { name } = node; + parts.unshift(name); + + return { name, keypath: parts.join('.') }; +} + +const KEY_COMPILED_ESM = '__esModule'; + +function isDefineCompiledEsm(node) { + const definedProperty = + getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports'); + if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) { + return isTruthy(definedProperty.value); + } + return false; +} + +function getDefinePropertyCallName(node, targetName) { + const { + callee: { object, property } + } = node; + if (!object || object.type !== 'Identifier' || object.name !== 'Object') return; + if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return; + if (node.arguments.length !== 3) return; + + const targetNames = targetName.split('.'); + const [target, key, value] = node.arguments; + if (targetNames.length === 1) { + if (target.type !== 'Identifier' || target.name !== targetNames[0]) { + return; + } + } + + if (targetNames.length === 2) { + if ( + target.type !== 'MemberExpression' || + target.object.name !== targetNames[0] || + target.property.name !== targetNames[1] + ) { + return; + } + } + + if (value.type !== 'ObjectExpression' || !value.properties) return; + + const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value'); + if (!valueProperty || !valueProperty.value) return; + + // eslint-disable-next-line consistent-return + return { key: key.value, value: valueProperty.value }; +} + +function isShorthandProperty(parent) { + return parent && parent.type === 'Property' && parent.shorthand; +} + +function hasDefineEsmProperty(node) { + return node.properties.some((property) => { + if ( + property.type === 'Property' && + property.key.type === 'Identifier' && + property.key.name === '__esModule' && + isTruthy(property.value) + ) { + return true; + } + return false; + }); +} + +function wrapCode(magicString, uses, moduleName, exportsName) { + const args = []; + const passedArgs = []; + if (uses.module) { + args.push('module'); + passedArgs.push(moduleName); + } + if (uses.exports) { + args.push('exports'); + passedArgs.push(exportsName); + } + magicString + .trim() + .prepend(`(function (${args.join(', ')}) {\n`) + .append(`\n}(${passedArgs.join(', ')}));`); +} + +function rewriteExportsAndGetExportsBlock( + magicString, + moduleName, + exportsName, + wrapped, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsAssignmentsByName, + topLevelAssignments, + defineCompiledEsmExpressions, + deconflictedExportNames, + code, + HELPERS_NAME, + exportMode, + detectWrappedDefault, + defaultIsModuleExports +) { + const exports = []; + const exportDeclarations = []; + + if (exportMode === 'replace') { + getExportsForReplacedModuleExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsName + ); + } else { + exports.push(`${exportsName} as __moduleExports`); + if (wrapped) { + getExportsWhenWrapping( + exportDeclarations, + exportsName, + detectWrappedDefault, + HELPERS_NAME, + defaultIsModuleExports + ); + } else { + getExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + exportsAssignmentsByName, + deconflictedExportNames, + topLevelAssignments, + moduleName, + exportsName, + defineCompiledEsmExpressions, + HELPERS_NAME, + defaultIsModuleExports + ); + } + } + if (exports.length) { + exportDeclarations.push(`export { ${exports.join(', ')} };`); + } + + return `\n\n${exportDeclarations.join('\n')}`; +} + +function getExportsForReplacedModuleExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsName +) { + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, exportsName); + } + magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var '); + exports.push(`${exportsName} as __moduleExports`); + exportDeclarations.push(`export default ${exportsName};`); +} + +function getExportsWhenWrapping( + exportDeclarations, + exportsName, + detectWrappedDefault, + HELPERS_NAME, + defaultIsModuleExports +) { + exportDeclarations.push( + `export default ${ + detectWrappedDefault && defaultIsModuleExports === 'auto' + ? `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName})` + : defaultIsModuleExports === false + ? `${exportsName}.default` + : exportsName + };` + ); +} + +function getExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + exportsAssignmentsByName, + deconflictedExportNames, + topLevelAssignments, + moduleName, + exportsName, + defineCompiledEsmExpressions, + HELPERS_NAME, + defaultIsModuleExports +) { + let deconflictedDefaultExportName; + // Collect and rewrite module.exports assignments + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, `${moduleName}.exports`); + } + + // Collect and rewrite named exports + for (const [exportName, { nodes }] of exportsAssignmentsByName) { + const deconflicted = deconflictedExportNames[exportName]; + let needsDeclaration = true; + for (const node of nodes) { + let replacement = `${deconflicted} = ${exportsName}.${exportName}`; + if (needsDeclaration && topLevelAssignments.has(node)) { + replacement = `var ${replacement}`; + needsDeclaration = false; + } + magicString.overwrite(node.start, node.left.end, replacement); + } + if (needsDeclaration) { + magicString.prepend(`var ${deconflicted};\n`); + } + + if (exportName === 'default') { + deconflictedDefaultExportName = deconflicted; + } else { + exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`); + } + } + + // Collect and rewrite exports.__esModule assignments + let isRestorableCompiledEsm = false; + for (const expression of defineCompiledEsmExpressions) { + isRestorableCompiledEsm = true; + const moduleExportsExpression = + expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object; + magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName); + } + + if (!isRestorableCompiledEsm || defaultIsModuleExports === true) { + exportDeclarations.push(`export default ${exportsName};`); + } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) { + exports.push(`${deconflictedDefaultExportName || exportsName} as default`); + } else { + exportDeclarations.push( + `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});` + ); + } +} + +function isRequireStatement(node, scope) { + if (!node) return false; + if (node.type !== 'CallExpression') return false; + + // Weird case of `require()` or `module.require()` without arguments + if (node.arguments.length === 0) return false; + + return isRequire(node.callee, scope); +} + +function isRequire(node, scope) { + return ( + (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) || + (node.type === 'MemberExpression' && isModuleRequire(node, scope)) + ); +} + +function isModuleRequire({ object, property }, scope) { + return ( + object.type === 'Identifier' && + object.name === 'module' && + property.type === 'Identifier' && + property.name === 'require' && + !scope.contains('module') + ); +} + +function isStaticRequireStatement(node, scope) { + if (!isRequireStatement(node, scope)) return false; + return !hasDynamicArguments(node); +} + +function hasDynamicArguments(node) { + return ( + node.arguments.length > 1 || + (node.arguments[0].type !== 'Literal' && + (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0)) + ); +} + +const reservedMethod = { resolve: true, cache: true, main: true }; + +function isNodeRequirePropertyAccess(parent) { + return parent && parent.property && reservedMethod[parent.property.name]; +} + +function isIgnoredRequireStatement(requiredNode, ignoreRequire) { + return ignoreRequire(requiredNode.arguments[0].value); +} + +function getRequireStringArg(node) { + return node.arguments[0].type === 'Literal' + ? node.arguments[0].value + : node.arguments[0].quasis[0].value.cooked; +} + +function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) { + if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) { + try { + const resolvedPath = normalizePathSlashes(resolve$4.sync(source, { basedir: path$w.dirname(id) })); + if (dynamicRequireModuleSet.has(resolvedPath)) { + return true; + } + } catch (ex) { + // Probably a node.js internal module + return false; + } + + return false; + } + + for (const attemptExt of ['', '.js', '.json']) { + const resolvedPath = normalizePathSlashes(path$w.resolve(path$w.dirname(id), source + attemptExt)); + if (dynamicRequireModuleSet.has(resolvedPath)) { + return true; + } + } + + return false; +} + +function getRequireHandlers() { + const requiredSources = []; + const requiredBySource = Object.create(null); + const requiredByNode = new Map(); + const requireExpressionsWithUsedReturnValue = []; + + function addRequireStatement(sourceId, node, scope, usesReturnValue) { + const required = getRequired(sourceId); + requiredByNode.set(node, { scope, required }); + if (usesReturnValue) { + required.nodesUsingRequired.push(node); + requireExpressionsWithUsedReturnValue.push(node); + } + } + + function getRequired(sourceId) { + if (!requiredBySource[sourceId]) { + requiredSources.push(sourceId); + + requiredBySource[sourceId] = { + source: sourceId, + name: null, + nodesUsingRequired: [] + }; + } + + return requiredBySource[sourceId]; + } + + function rewriteRequireExpressionsAndGetImportBlock( + magicString, + topLevelDeclarations, + topLevelRequireDeclarators, + reassignedNames, + helpersName, + dynamicRegisterSources, + moduleName, + exportsName, + id, + exportMode + ) { + setRemainingImportNamesAndRewriteRequires( + requireExpressionsWithUsedReturnValue, + requiredByNode, + magicString + ); + const imports = []; + imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`); + if (exportMode === 'module') { + imports.push( + `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify( + wrapId(id, MODULE_SUFFIX) + )}` + ); + } else if (exportMode === 'exports') { + imports.push( + `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}` + ); + } + for (const source of dynamicRegisterSources) { + imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`); + } + for (const source of requiredSources) { + if (!source.startsWith('\0')) { + imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`); + } + const { name, nodesUsingRequired } = requiredBySource[source]; + imports.push( + `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify( + source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX) + )};` + ); + } + return imports.length ? `${imports.join('\n')}\n\n` : ''; + } + + return { + addRequireStatement, + requiredSources, + rewriteRequireExpressionsAndGetImportBlock + }; +} + +function setRemainingImportNamesAndRewriteRequires( + requireExpressionsWithUsedReturnValue, + requiredByNode, + magicString +) { + let uid = 0; + for (const requireExpression of requireExpressionsWithUsedReturnValue) { + const { required } = requiredByNode.get(requireExpression); + if (!required.name) { + let potentialName; + const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName); + do { + potentialName = `require$$${uid}`; + uid += 1; + } while (required.nodesUsingRequired.some(isUsedName)); + required.name = potentialName; + } + magicString.overwrite(requireExpression.start, requireExpression.end, required.name); + } +} + +/* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */ + +const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/; + +const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/; + +function transformCommonjs( + parse, + code, + id, + isEsModule, + ignoreGlobal, + ignoreRequire, + ignoreDynamicRequires, + getIgnoreTryCatchRequireStatementMode, + sourceMap, + isDynamicRequireModulesEnabled, + dynamicRequireModuleSet, + disableWrap, + commonDir, + astCache, + defaultIsModuleExports +) { + const ast = astCache || tryParse(parse, code, id); + const magicString = new MagicString(code); + const uses = { + module: false, + exports: false, + global: false, + require: false + }; + let usesDynamicRequire = false; + const virtualDynamicRequirePath = + isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path$w.dirname(id), commonDir); + let scope = attachScopes(ast, 'scope'); + let lexicalDepth = 0; + let programDepth = 0; + let currentTryBlockEnd = null; + let shouldWrap = false; + + const globals = new Set(); + + // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯ + const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers'); + const dynamicRegisterSources = new Set(); + let hasRemovedRequire = false; + + const { + addRequireStatement, + requiredSources, + rewriteRequireExpressionsAndGetImportBlock + } = getRequireHandlers(); + + // See which names are assigned to. This is necessary to prevent + // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`, + // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh) + const reassignedNames = new Set(); + const topLevelDeclarations = []; + const topLevelRequireDeclarators = new Set(); + const skippedNodes = new Set(); + const moduleAccessScopes = new Set([scope]); + const exportsAccessScopes = new Set([scope]); + const moduleExportsAssignments = []; + let firstTopLevelModuleExportsAssignment = null; + const exportsAssignmentsByName = new Map(); + const topLevelAssignments = new Set(); + const topLevelDefineCompiledEsmExpressions = []; + + walk$1(ast, { + enter(node, parent) { + if (skippedNodes.has(node)) { + this.skip(); + return; + } + + if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) { + currentTryBlockEnd = null; + } + + programDepth += 1; + if (node.scope) ({ scope } = node); + if (functionType.test(node.type)) lexicalDepth += 1; + if (sourceMap) { + magicString.addSourcemapLocation(node.start); + magicString.addSourcemapLocation(node.end); + } + + // eslint-disable-next-line default-case + switch (node.type) { + case 'TryStatement': + if (currentTryBlockEnd === null) { + currentTryBlockEnd = node.block.end; + } + return; + case 'AssignmentExpression': + if (node.left.type === 'MemberExpression') { + const flattened = getKeypath(node.left); + if (!flattened || scope.contains(flattened.name)) return; + + const exportsPatternMatch = exportsPattern.exec(flattened.keypath); + if (!exportsPatternMatch || flattened.keypath === 'exports') return; + + const [, exportName] = exportsPatternMatch; + uses[flattened.name] = true; + + // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` – + if (flattened.keypath === 'module.exports') { + moduleExportsAssignments.push(node); + if (programDepth > 3) { + moduleAccessScopes.add(scope); + } else if (!firstTopLevelModuleExportsAssignment) { + firstTopLevelModuleExportsAssignment = node; + } + + if (defaultIsModuleExports === false) { + shouldWrap = true; + } else if (defaultIsModuleExports === 'auto') { + if (node.right.type === 'ObjectExpression') { + if (hasDefineEsmProperty(node.right)) { + shouldWrap = true; + } + } else if (defaultIsModuleExports === false) { + shouldWrap = true; + } + } + } else if (exportName === KEY_COMPILED_ESM) { + if (programDepth > 3) { + shouldWrap = true; + } else { + topLevelDefineCompiledEsmExpressions.push(node); + } + } else { + const exportsAssignments = exportsAssignmentsByName.get(exportName) || { + nodes: [], + scopes: new Set() + }; + exportsAssignments.nodes.push(node); + exportsAssignments.scopes.add(scope); + exportsAccessScopes.add(scope); + exportsAssignmentsByName.set(exportName, exportsAssignments); + if (programDepth <= 3) { + topLevelAssignments.add(node); + } + } + + skippedNodes.add(node.left); + } else { + for (const name of extractAssignedNames(node.left)) { + reassignedNames.add(name); + } + } + return; + case 'CallExpression': { + if (isDefineCompiledEsm(node)) { + if (programDepth === 3 && parent.type === 'ExpressionStatement') { + // skip special handling for [module.]exports until we know we render this + skippedNodes.add(node.arguments[0]); + topLevelDefineCompiledEsmExpressions.push(node); + } else { + shouldWrap = true; + } + return; + } + + if ( + node.callee.object && + node.callee.object.name === 'require' && + node.callee.property.name === 'resolve' && + hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet) + ) { + const requireNode = node.callee.object; + magicString.appendLeft( + node.end - 1, + `,${JSON.stringify( + path$w.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath + )}` + ); + magicString.overwrite( + requireNode.start, + requireNode.end, + `${HELPERS_NAME}.commonjsRequire`, + { + storeName: true + } + ); + return; + } + + if (!isStaticRequireStatement(node, scope)) return; + if (!isDynamicRequireModulesEnabled) { + skippedNodes.add(node.callee); + } + if (!isIgnoredRequireStatement(node, ignoreRequire)) { + skippedNodes.add(node.callee); + const usesReturnValue = parent.type !== 'ExpressionStatement'; + + let canConvertRequire = true; + let shouldRemoveRequireStatement = false; + + if (currentTryBlockEnd !== null) { + ({ + canConvertRequire, + shouldRemoveRequireStatement + } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value)); + + if (shouldRemoveRequireStatement) { + hasRemovedRequire = true; + } + } + + let sourceId = getRequireStringArg(node); + const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX); + if (isDynamicRegister) { + sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX); + if (sourceId.endsWith('.json')) { + sourceId = DYNAMIC_JSON_PREFIX + sourceId; + } + dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX)); + } else { + if ( + !sourceId.endsWith('.json') && + hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet) + ) { + if (shouldRemoveRequireStatement) { + magicString.overwrite(node.start, node.end, `undefined`); + } else if (canConvertRequire) { + magicString.overwrite( + node.start, + node.end, + `${HELPERS_NAME}.commonjsRequire(${JSON.stringify( + getVirtualPathForDynamicRequirePath(sourceId, commonDir) + )}, ${JSON.stringify( + path$w.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath + )})` + ); + usesDynamicRequire = true; + } + return; + } + + if (canConvertRequire) { + addRequireStatement(sourceId, node, scope, usesReturnValue); + } + } + + if (usesReturnValue) { + if (shouldRemoveRequireStatement) { + magicString.overwrite(node.start, node.end, `undefined`); + return; + } + + if ( + parent.type === 'VariableDeclarator' && + !scope.parent && + parent.id.type === 'Identifier' + ) { + // This will allow us to reuse this variable name as the imported variable if it is not reassigned + // and does not conflict with variables in other places where this is imported + topLevelRequireDeclarators.add(parent); + } + } else { + // This is a bare import, e.g. `require('foo');` + + if (!canConvertRequire && !shouldRemoveRequireStatement) { + return; + } + + magicString.remove(parent.start, parent.end); + } + } + return; + } + case 'ConditionalExpression': + case 'IfStatement': + // skip dead branches + if (isFalsy(node.test)) { + skippedNodes.add(node.consequent); + } else if (node.alternate && isTruthy(node.test)) { + skippedNodes.add(node.alternate); + } + return; + case 'Identifier': { + const { name } = node; + if (!(isReference(node, parent) && !scope.contains(name))) return; + switch (name) { + case 'require': + if (isNodeRequirePropertyAccess(parent)) { + if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) { + if (parent.property.name === 'cache') { + magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { + storeName: true + }); + } + } + + return; + } + + if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) { + magicString.appendLeft( + parent.end - 1, + `,${JSON.stringify( + path$w.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath + )}` + ); + } + if (!ignoreDynamicRequires) { + if (isShorthandProperty(parent)) { + magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`); + } else { + magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { + storeName: true + }); + } + } + usesDynamicRequire = true; + return; + case 'module': + case 'exports': + shouldWrap = true; + uses[name] = true; + return; + case 'global': + uses.global = true; + if (!ignoreGlobal) { + magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, { + storeName: true + }); + } + return; + case 'define': + magicString.overwrite(node.start, node.end, 'undefined', { + storeName: true + }); + return; + default: + globals.add(name); + return; + } + } + case 'MemberExpression': + if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) { + magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { + storeName: true + }); + skippedNodes.add(node.object); + skippedNodes.add(node.property); + } + return; + case 'ReturnStatement': + // if top-level return, we need to wrap it + if (lexicalDepth === 0) { + shouldWrap = true; + } + return; + case 'ThisExpression': + // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal` + if (lexicalDepth === 0) { + uses.global = true; + if (!ignoreGlobal) { + magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, { + storeName: true + }); + } + } + return; + case 'UnaryExpression': + // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151) + if (node.operator === 'typeof') { + const flattened = getKeypath(node.argument); + if (!flattened) return; + + if (scope.contains(flattened.name)) return; + + if ( + flattened.keypath === 'module.exports' || + flattened.keypath === 'module' || + flattened.keypath === 'exports' + ) { + magicString.overwrite(node.start, node.end, `'object'`, { + storeName: false + }); + } + } + return; + case 'VariableDeclaration': + if (!scope.parent) { + topLevelDeclarations.push(node); + } + } + }, + + leave(node) { + programDepth -= 1; + if (node.scope) scope = scope.parent; + if (functionType.test(node.type)) lexicalDepth -= 1; + } + }); + + const nameBase = getName(id); + const exportsName = deconflict([...exportsAccessScopes], globals, nameBase); + const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`); + const deconflictedExportNames = Object.create(null); + for (const [exportName, { scopes }] of exportsAssignmentsByName) { + deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName); + } + + // We cannot wrap ES/mixed modules + shouldWrap = + !isEsModule && + !disableWrap && + (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0)); + const detectWrappedDefault = + shouldWrap && + (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0); + + if ( + !( + requiredSources.length || + dynamicRegisterSources.size || + uses.module || + uses.exports || + uses.require || + usesDynamicRequire || + hasRemovedRequire || + topLevelDefineCompiledEsmExpressions.length > 0 + ) && + (ignoreGlobal || !uses.global) + ) { + return { meta: { commonjs: { isCommonJS: false } } }; + } + + let leadingComment = ''; + if (code.startsWith('/*')) { + const commentEnd = code.indexOf('*/', 2) + 2; + leadingComment = `${code.slice(0, commentEnd)}\n`; + magicString.remove(0, commentEnd).trim(); + } + + const exportMode = shouldWrap + ? uses.module + ? 'module' + : 'exports' + : firstTopLevelModuleExportsAssignment + ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 + ? 'replace' + : 'module' + : moduleExportsAssignments.length === 0 + ? 'exports' + : 'module'; + + const importBlock = rewriteRequireExpressionsAndGetImportBlock( + magicString, + topLevelDeclarations, + topLevelRequireDeclarators, + reassignedNames, + HELPERS_NAME, + dynamicRegisterSources, + moduleName, + exportsName, + id, + exportMode + ); + + const exportBlock = isEsModule + ? '' + : rewriteExportsAndGetExportsBlock( + magicString, + moduleName, + exportsName, + shouldWrap, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsAssignmentsByName, + topLevelAssignments, + topLevelDefineCompiledEsmExpressions, + deconflictedExportNames, + code, + HELPERS_NAME, + exportMode, + detectWrappedDefault, + defaultIsModuleExports + ); + + if (shouldWrap) { + wrapCode(magicString, uses, moduleName, exportsName); + } + + magicString + .trim() + .prepend(leadingComment + importBlock) + .append(exportBlock); + + return { + code: magicString.toString(), + map: sourceMap ? magicString.generateMap() : null, + syntheticNamedExports: isEsModule ? false : '__moduleExports', + meta: { commonjs: { isCommonJS: !isEsModule } } + }; +} + +function commonjs(options = {}) { + const extensions = options.extensions || ['.js']; + const filter = createFilter(options.include, options.exclude); + const { + ignoreGlobal, + ignoreDynamicRequires, + requireReturnsDefault: requireReturnsDefaultOption, + esmExternals + } = options; + const getRequireReturnsDefault = + typeof requireReturnsDefaultOption === 'function' + ? requireReturnsDefaultOption + : () => requireReturnsDefaultOption; + let esmExternalIds; + const isEsmExternal = + typeof esmExternals === 'function' + ? esmExternals + : Array.isArray(esmExternals) + ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id)) + : () => esmExternals; + const defaultIsModuleExports = + typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto'; + + const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths( + options.dynamicRequireTargets + ); + const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0; + const commonDir = isDynamicRequireModulesEnabled + ? commondir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd())) + : null; + + const esModulesWithDefaultExport = new Set(); + const esModulesWithNamedExports = new Set(); + const commonJsMetaPromises = new Map(); + + const ignoreRequire = + typeof options.ignore === 'function' + ? options.ignore + : Array.isArray(options.ignore) + ? (id) => options.ignore.includes(id) + : () => false; + + const getIgnoreTryCatchRequireStatementMode = (id) => { + const mode = + typeof options.ignoreTryCatch === 'function' + ? options.ignoreTryCatch(id) + : Array.isArray(options.ignoreTryCatch) + ? options.ignoreTryCatch.includes(id) + : options.ignoreTryCatch || false; + + return { + canConvertRequire: mode !== 'remove' && mode !== true, + shouldRemoveRequireStatement: mode === 'remove' + }; + }; + + const resolveId = getResolveId(extensions); + + const sourceMap = options.sourceMap !== false; + + function transformAndCheckExports(code, id) { + if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) { + // eslint-disable-next-line no-param-reassign + code = + getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code; + } + + const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements( + this.parse, + code, + id + ); + if (hasDefaultExport) { + esModulesWithDefaultExport.add(id); + } + if (hasNamedExports) { + esModulesWithNamedExports.add(id); + } + + if ( + !dynamicRequireModuleSet.has(normalizePathSlashes(id)) && + (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules)) + ) { + return { meta: { commonjs: { isCommonJS: false } } }; + } + + // avoid wrapping as this is a commonjsRegister call + const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX); + if (disableWrap) { + // eslint-disable-next-line no-param-reassign + id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX); + } + + return transformCommonjs( + this.parse, + code, + id, + isEsModule, + ignoreGlobal || isEsModule, + ignoreRequire, + ignoreDynamicRequires && !isDynamicRequireModulesEnabled, + getIgnoreTryCatchRequireStatementMode, + sourceMap, + isDynamicRequireModulesEnabled, + dynamicRequireModuleSet, + disableWrap, + commonDir, + ast, + defaultIsModuleExports + ); + } + + return { + name: 'commonjs', + + buildStart() { + validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup); + if (options.namedExports != null) { + this.warn( + 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.' + ); + } + }, + + resolveId, + + load(id) { + if (id === HELPERS_ID) { + return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires); + } + + if (id.startsWith(HELPERS_ID)) { + return getSpecificHelperProxy(id); + } + + if (isWrappedId(id, MODULE_SUFFIX)) { + const actualId = unwrapId(id, MODULE_SUFFIX); + let name = getName(actualId); + let code; + if (isDynamicRequireModulesEnabled) { + if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) { + name = `${name}_`; + } + code = + `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` + + `var ${name} = createModule(${JSON.stringify( + getVirtualPathForDynamicRequirePath(path$w.dirname(actualId), commonDir) + )});\n` + + `export {${name} as __module}`; + } else { + code = `var ${name} = {exports: {}}; export {${name} as __module}`; + } + return { + code, + syntheticNamedExports: '__module', + meta: { commonjs: { isCommonJS: false } } + }; + } + + if (isWrappedId(id, EXPORTS_SUFFIX)) { + const actualId = unwrapId(id, EXPORTS_SUFFIX); + const name = getName(actualId); + return { + code: `var ${name} = {}; export {${name} as __exports}`, + meta: { commonjs: { isCommonJS: false } } + }; + } + + if (isWrappedId(id, EXTERNAL_SUFFIX)) { + const actualId = unwrapId(id, EXTERNAL_SUFFIX); + return getUnknownRequireProxy( + actualId, + isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true + ); + } + + if (id === DYNAMIC_PACKAGES_ID) { + return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir); + } + + if (id.startsWith(DYNAMIC_JSON_PREFIX)) { + return getDynamicJsonProxy(id, commonDir); + } + + if (isDynamicModuleImport(id, dynamicRequireModuleSet)) { + return `export default require(${JSON.stringify(normalizePathSlashes(id))});`; + } + + if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) { + return getDynamicRequireProxy( + normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)), + commonDir + ); + } + + if (isWrappedId(id, PROXY_SUFFIX)) { + const actualId = unwrapId(id, PROXY_SUFFIX); + return getStaticRequireProxy( + actualId, + getRequireReturnsDefault(actualId), + esModulesWithDefaultExport, + esModulesWithNamedExports, + commonJsMetaPromises + ); + } + + return null; + }, + + transform(code, rawId) { + let id = rawId; + + if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) { + id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX); + } + + const extName = path$w.extname(id); + if ( + extName !== '.cjs' && + id !== DYNAMIC_PACKAGES_ID && + !id.startsWith(DYNAMIC_JSON_PREFIX) && + (!filter(id) || !extensions.includes(extName)) + ) { + return null; + } + + try { + return transformAndCheckExports.call(this, code, rawId); + } catch (err) { + return this.error(err, err.loc); + } + }, + + moduleParsed({ id, meta: { commonjs: commonjsMeta } }) { + if (commonjsMeta && commonjsMeta.isCommonJS != null) { + setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta); + return; + } + setCommonJSMetaPromise(commonJsMetaPromises, id, null); + } + }; +} + +var globby$1 = {exports: {}}; + +var arrayUnion$1 = (...arguments_) => { + return [...new Set([].concat(...arguments_))]; +}; + +var dirGlob$1 = {exports: {}}; + +var pathType$1 = {}; + +const {promisify: promisify$6} = require$$0__default$3; +const fs$e = fs__default; + +async function isType(fsStatType, statsMethodName, filePath) { + if (typeof filePath !== 'string') { + throw new TypeError(`Expected a string, got ${typeof filePath}`); + } + + try { + const stats = await promisify$6(fs$e[fsStatType])(filePath); + return stats[statsMethodName](); + } catch (error) { + if (error.code === 'ENOENT') { + return false; + } + + throw error; + } +} + +function isTypeSync(fsStatType, statsMethodName, filePath) { + if (typeof filePath !== 'string') { + throw new TypeError(`Expected a string, got ${typeof filePath}`); + } + + try { + return fs$e[fsStatType](filePath)[statsMethodName](); + } catch (error) { + if (error.code === 'ENOENT') { + return false; + } + + throw error; + } +} + +pathType$1.isFile = isType.bind(null, 'stat', 'isFile'); +pathType$1.isDirectory = isType.bind(null, 'stat', 'isDirectory'); +pathType$1.isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink'); +pathType$1.isFileSync = isTypeSync.bind(null, 'statSync', 'isFile'); +pathType$1.isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory'); +pathType$1.isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink'); + +const path$c = path__default; +const pathType = pathType$1; + +const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; + +const getPath = (filepath, cwd) => { + const pth = filepath[0] === '!' ? filepath.slice(1) : filepath; + return path$c.isAbsolute(pth) ? pth : path$c.join(cwd, pth); +}; + +const addExtensions = (file, extensions) => { + if (path$c.extname(file)) { + return `**/${file}`; + } + + return `**/${file}.${getExtensions(extensions)}`; +}; + +const getGlob = (directory, options) => { + if (options.files && !Array.isArray(options.files)) { + throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``); + } + + if (options.extensions && !Array.isArray(options.extensions)) { + throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``); + } + + if (options.files && options.extensions) { + return options.files.map(x => path$c.posix.join(directory, addExtensions(x, options.extensions))); + } + + if (options.files) { + return options.files.map(x => path$c.posix.join(directory, `**/${x}`)); + } + + if (options.extensions) { + return [path$c.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)]; + } + + return [path$c.posix.join(directory, '**')]; +}; + +dirGlob$1.exports = async (input, options) => { + options = { + cwd: process.cwd(), + ...options + }; + + if (typeof options.cwd !== 'string') { + throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); + } + + const globs = await Promise.all([].concat(input).map(async x => { + const isDirectory = await pathType.isDirectory(getPath(x, options.cwd)); + return isDirectory ? getGlob(x, options) : x; + })); + + return [].concat.apply([], globs); // eslint-disable-line prefer-spread +}; + +dirGlob$1.exports.sync = (input, options) => { + options = { + cwd: process.cwd(), + ...options + }; + + if (typeof options.cwd !== 'string') { + throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); + } + + const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x); + + return [].concat.apply([], globs); // eslint-disable-line prefer-spread +}; + +var gitignore$1 = {exports: {}}; + +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} + +const EMPTY = ''; +const SPACE = ' '; +const ESCAPE = '\\'; +const REGEX_TEST_BLANK_LINE = /^\s+$/; +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; +const REGEX_SPLITALL_CRLF = /\r?\n/g; +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; + +const SLASH$1 = '/'; +const KEY_IGNORE = typeof Symbol !== 'undefined' + ? Symbol.for('node-ignore') + /* istanbul ignore next */ + : 'node-ignore'; + +const define = (object, key, value) => + Object.defineProperty(object, key, {value}); + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY +); + +// See fixtures #59 +const cleanRangeBackSlash = slashes => { + const {length} = slashes; + return slashes.slice(0, length - length % 2) +}; + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ + + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? SPACE + : EMPTY + ], + + // replace (\ ) with ' ' + [ + /\\\s/g, + () => SPACE + ], + + // Escape metacharacters + // which is written down by users but means special for regular expressions. + + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\$.|*+(){^]/g, + match => `\\${match}` + ], + + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], + + // leading slash + [ + + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], + + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], + + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, + + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], + + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' + } + ], + + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, + + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer + + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], + + // intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' + + // 'abc.*/' -> go + // 'abc.*' -> skip this rule + /(^|[^\\]+)\\\*(?=.+)/g, + + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1) => `${p1}[^\\/]*` + ], + + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], + + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], + + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. + + // `\` is escaped by step 3 + /(\\)?\[([^\]/]*?)(\\*)($|\])/g, + (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` + : close === ']' + ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? `[${sanitizeRange(range)}${endEscape}]` + // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' + : '[]' + ], + + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, + + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ], + + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + + return `${prefix}(?=$|\\/$)` + } + ], +]; + +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null); + +// @param {pattern} +const makeRegex = (pattern, negative, ignorecase) => { + const r = regexCache[pattern]; + if (r) { + return r + } + + // const replacers = negative + // ? NEGATIVE_REPLACERS + // : POSITIVE_REPLACERS + + const source = REPLACERS.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ); + + return regexCache[pattern] = ignorecase + ? new RegExp(source, 'i') + : new RegExp(source) +}; + +const isString = subject => typeof subject === 'string'; + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0; + +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF); + +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin; + this.pattern = pattern; + this.negative = negative; + this.regex = regex; + } +} + +const createRule = (pattern, ignorecase) => { + const origin = pattern; + let negative = false; + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true; + pattern = pattern.substr(1); + } + + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); + + const regex = makeRegex(pattern, negative, ignorecase); + + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +}; + +const throwError = (message, Ctor) => { + throw new Ctor(message) +}; + +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d'; + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } + + return true +}; + +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path); + +checkPath.isNotRelative = isNotRelative; +checkPath.convert = p => p; + +class Ignore { + constructor ({ + ignorecase = true + } = {}) { + this._rules = []; + this._ignorecase = ignorecase; + define(this, KEY_IGNORE, true); + this._initCache(); + } + + _initCache () { + this._ignoreCache = Object.create(null); + this._testCache = Object.create(null); + } + + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return + } + + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignorecase); + this._added = true; + this._rules.push(rule); + } + } + + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false; + + makeArray( + isString(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this); + + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache(); + } + + return this + } + + // legacy + addPattern (pattern) { + return this.add(pattern) + } + + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false; + let unignored = false; + + this._rules.forEach(rule => { + const {negative} = rule; + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } + + const matched = rule.regex.test(path); + + if (matched) { + ignored = !negative; + unignored = negative; + } + }); + + return { + ignored, + unignored + } + } + + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath); + + checkPath(path, originalPath, throwError); + + return this._t(path, cache, checkUnignored, slices) + } + + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH$1); + } + + slices.pop(); + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } + + const parent = this._t( + slices.join(SLASH$1) + SLASH$1, + cache, + checkUnignored, + slices + ); + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } + + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + + createFilter () { + return path => !this.ignores(path) + } + + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } + + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} + +const factory = options => new Ignore(options); + +const returnFalse = () => false; + +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, returnFalse); + +factory.isPathValid = isPathValid; + +// Fixes typescript +factory.default = factory; + +var ignore = factory; + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/'); + + checkPath.convert = makePosix; + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path); +} + +var slash$1 = path => { + const isExtendedLengthPath = /^\\\\\?\\/.test(path); + const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex + + if (isExtendedLengthPath || hasNonAscii) { + return path; + } + + return path.replace(/\\/g, '/'); +}; + +const {promisify: promisify$5} = require$$0__default$3; +const fs$d = fs__default; +const path$b = path__default; +const fastGlob$1 = out; +const gitIgnore = ignore; +const slash = slash$1; + +const DEFAULT_IGNORE = [ + '**/node_modules/**', + '**/flow-typed/**', + '**/coverage/**', + '**/.git' +]; + +const readFileP = promisify$5(fs$d.readFile); + +const mapGitIgnorePatternTo = base => ignore => { + if (ignore.startsWith('!')) { + return '!' + path$b.posix.join(base, ignore.slice(1)); + } + + return path$b.posix.join(base, ignore); +}; + +const parseGitIgnore = (content, options) => { + const base = slash(path$b.relative(options.cwd, path$b.dirname(options.fileName))); + + return content + .split(/\r?\n/) + .filter(Boolean) + .filter(line => !line.startsWith('#')) + .map(mapGitIgnorePatternTo(base)); +}; + +const reduceIgnore = files => { + const ignores = gitIgnore(); + for (const file of files) { + ignores.add(parseGitIgnore(file.content, { + cwd: file.cwd, + fileName: file.filePath + })); + } + + return ignores; +}; + +const ensureAbsolutePathForCwd = (cwd, p) => { + cwd = slash(cwd); + if (path$b.isAbsolute(p)) { + if (slash(p).startsWith(cwd)) { + return p; + } + + throw new Error(`Path ${p} is not in cwd ${cwd}`); + } + + return path$b.join(cwd, p); +}; + +const getIsIgnoredPredecate = (ignores, cwd) => { + return p => ignores.ignores(slash(path$b.relative(cwd, ensureAbsolutePathForCwd(cwd, p.path || p)))); +}; + +const getFile = async (file, cwd) => { + const filePath = path$b.join(cwd, file); + const content = await readFileP(filePath, 'utf8'); + + return { + cwd, + filePath, + content + }; +}; + +const getFileSync = (file, cwd) => { + const filePath = path$b.join(cwd, file); + const content = fs$d.readFileSync(filePath, 'utf8'); + + return { + cwd, + filePath, + content + }; +}; + +const normalizeOptions = ({ + ignore = [], + cwd = slash(process.cwd()) +} = {}) => { + return {ignore, cwd}; +}; + +gitignore$1.exports = async options => { + options = normalizeOptions(options); + + const paths = await fastGlob$1('**/.gitignore', { + ignore: DEFAULT_IGNORE.concat(options.ignore), + cwd: options.cwd + }); + + const files = await Promise.all(paths.map(file => getFile(file, options.cwd))); + const ignores = reduceIgnore(files); + + return getIsIgnoredPredecate(ignores, options.cwd); +}; + +gitignore$1.exports.sync = options => { + options = normalizeOptions(options); + + const paths = fastGlob$1.sync('**/.gitignore', { + ignore: DEFAULT_IGNORE.concat(options.ignore), + cwd: options.cwd + }); + + const files = paths.map(file => getFileSync(file, options.cwd)); + const ignores = reduceIgnore(files); + + return getIsIgnoredPredecate(ignores, options.cwd); +}; + +const {Transform} = require$$0__default$2; + +class ObjectTransform extends Transform { + constructor() { + super({ + objectMode: true + }); + } +} + +class FilterStream$1 extends ObjectTransform { + constructor(filter) { + super(); + this._filter = filter; + } + + _transform(data, encoding, callback) { + if (this._filter(data)) { + this.push(data); + } + + callback(); + } +} + +class UniqueStream$1 extends ObjectTransform { + constructor() { + super(); + this._pushed = new Set(); + } + + _transform(data, encoding, callback) { + if (!this._pushed.has(data)) { + this.push(data); + this._pushed.add(data); + } + + callback(); + } +} + +var streamUtils = { + FilterStream: FilterStream$1, + UniqueStream: UniqueStream$1 +}; + +const fs$c = fs__default; +const arrayUnion = arrayUnion$1; +const merge2 = merge2_1; +const fastGlob = out; +const dirGlob = dirGlob$1.exports; +const gitignore = gitignore$1.exports; +const {FilterStream, UniqueStream} = streamUtils; + +const DEFAULT_FILTER = () => false; + +const isNegative = pattern => pattern[0] === '!'; + +const assertPatternsInput = patterns => { + if (!patterns.every(pattern => typeof pattern === 'string')) { + throw new TypeError('Patterns must be a string or an array of strings'); + } +}; + +const checkCwdOption = (options = {}) => { + if (!options.cwd) { + return; + } + + let stat; + try { + stat = fs$c.statSync(options.cwd); + } catch { + return; + } + + if (!stat.isDirectory()) { + throw new Error('The `cwd` option must be a path to a directory'); + } +}; + +const getPathString = p => p.stats instanceof fs$c.Stats ? p.path : p; + +const generateGlobTasks = (patterns, taskOptions) => { + patterns = arrayUnion([].concat(patterns)); + assertPatternsInput(patterns); + checkCwdOption(taskOptions); + + const globTasks = []; + + taskOptions = { + ignore: [], + expandDirectories: true, + ...taskOptions + }; + + for (const [index, pattern] of patterns.entries()) { + if (isNegative(pattern)) { + continue; + } + + const ignore = patterns + .slice(index) + .filter(pattern => isNegative(pattern)) + .map(pattern => pattern.slice(1)); + + const options = { + ...taskOptions, + ignore: taskOptions.ignore.concat(ignore) + }; + + globTasks.push({pattern, options}); + } + + return globTasks; +}; + +const globDirs = (task, fn) => { + let options = {}; + if (task.options.cwd) { + options.cwd = task.options.cwd; + } + + if (Array.isArray(task.options.expandDirectories)) { + options = { + ...options, + files: task.options.expandDirectories + }; + } else if (typeof task.options.expandDirectories === 'object') { + options = { + ...options, + ...task.options.expandDirectories + }; + } + + return fn(task.pattern, options); +}; + +const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern]; + +const getFilterSync = options => { + return options && options.gitignore ? + gitignore.sync({cwd: options.cwd, ignore: options.ignore}) : + DEFAULT_FILTER; +}; + +const globToTask = task => glob => { + const {options} = task; + if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) { + options.ignore = dirGlob.sync(options.ignore); + } + + return { + pattern: glob, + options + }; +}; + +globby$1.exports = async (patterns, options) => { + const globTasks = generateGlobTasks(patterns, options); + + const getFilter = async () => { + return options && options.gitignore ? + gitignore({cwd: options.cwd, ignore: options.ignore}) : + DEFAULT_FILTER; + }; + + const getTasks = async () => { + const tasks = await Promise.all(globTasks.map(async task => { + const globs = await getPattern(task, dirGlob); + return Promise.all(globs.map(globToTask(task))); + })); + + return arrayUnion(...tasks); + }; + + const [filter, tasks] = await Promise.all([getFilter(), getTasks()]); + const paths = await Promise.all(tasks.map(task => fastGlob(task.pattern, task.options))); + + return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_))); +}; + +globby$1.exports.sync = (patterns, options) => { + const globTasks = generateGlobTasks(patterns, options); + + const tasks = []; + for (const task of globTasks) { + const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); + tasks.push(...newTask); + } + + const filter = getFilterSync(options); + + let matches = []; + for (const task of tasks) { + matches = arrayUnion(matches, fastGlob.sync(task.pattern, task.options)); + } + + return matches.filter(path_ => !filter(path_)); +}; + +globby$1.exports.stream = (patterns, options) => { + const globTasks = generateGlobTasks(patterns, options); + + const tasks = []; + for (const task of globTasks) { + const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); + tasks.push(...newTask); + } + + const filter = getFilterSync(options); + const filterStream = new FilterStream(p => !filter(p)); + const uniqueStream = new UniqueStream(); + + return merge2(tasks.map(task => fastGlob.stream(task.pattern, task.options))) + .pipe(filterStream) + .pipe(uniqueStream); +}; + +globby$1.exports.generateGlobTasks = generateGlobTasks; + +globby$1.exports.hasMagic = (patterns, options) => [] + .concat(patterns) + .some(pattern => fastGlob.isDynamicPattern(pattern, options)); + +globby$1.exports.gitignore = gitignore; + +var globby = globby$1.exports; + +class VariableDynamicImportError extends Error {} + +/* eslint-disable-next-line no-template-curly-in-string */ +const example = 'For example: import(`./foo/${bar}.js`).'; + +function sanitizeString(str) { + if (str.includes('*')) { + throw new VariableDynamicImportError('A dynamic import cannot contain * characters.'); + } + return str; +} + +function templateLiteralToGlob(node) { + let glob = ''; + + for (let i = 0; i < node.quasis.length; i += 1) { + glob += sanitizeString(node.quasis[i].value.raw); + if (node.expressions[i]) { + glob += expressionToGlob(node.expressions[i]); + } + } + + return glob; +} + +function callExpressionToGlob(node) { + const { callee } = node; + if ( + callee.type === 'MemberExpression' && + callee.property.type === 'Identifier' && + callee.property.name === 'concat' + ) { + return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join('')}`; + } + return '*'; +} + +function binaryExpressionToGlob(node) { + if (node.operator !== '+') { + throw new VariableDynamicImportError(`${node.operator} operator is not supported.`); + } + + return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`; +} + +function expressionToGlob(node) { + switch (node.type) { + case 'TemplateLiteral': + return templateLiteralToGlob(node); + case 'CallExpression': + return callExpressionToGlob(node); + case 'BinaryExpression': + return binaryExpressionToGlob(node); + case 'Literal': { + return sanitizeString(node.value); + } + default: + return '*'; + } +} + +function dynamicImportToGlob(node, sourceString) { + let glob = expressionToGlob(node); + if (!glob.includes('*')) { + return null; + } + glob = glob.replace(/\*\*/g, '*'); + + if (glob.startsWith('*')) { + throw new VariableDynamicImportError( + `invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}` + ); + } + + if (glob.startsWith('/')) { + throw new VariableDynamicImportError( + `invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}` + ); + } + + if (!glob.startsWith('./') && !glob.startsWith('../')) { + throw new VariableDynamicImportError( + `invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}` + ); + } + + // Disallow ./*.ext + const ownDirectoryStarExtension = /^\.\/\*\.[\w]+$/; + if (ownDirectoryStarExtension.test(glob)) { + throw new VariableDynamicImportError( + `${ + `invalid import "${sourceString}". Variable imports cannot import their own directory, ` + + 'place imports in a separate directory or make the import filename more specific. ' + }${example}` + ); + } + + if (path__default.extname(glob) === '') { + throw new VariableDynamicImportError( + `invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}` + ); + } + + return glob; +} + +function dynamicImportVariables({ include, exclude, warnOnError } = {}) { + const filter = createFilter(include, exclude); + + return { + name: 'rollup-plugin-dynamic-import-variables', + + transform(code, id) { + if (!filter(id)) { + return null; + } + + const parsed = this.parse(code); + + let dynamicImportIndex = -1; + let ms; + + walk$1(parsed, { + enter: (node) => { + if (node.type !== 'ImportExpression') { + return; + } + dynamicImportIndex += 1; + + try { + // see if this is a variable dynamic import, and generate a glob expression + const glob = dynamicImportToGlob(node.source, code.substring(node.start, node.end)); + + if (!glob) { + // this was not a variable dynamic import + return; + } + + // execute the glob + const result = globby.sync(glob, { cwd: path__default.dirname(id) }); + const paths = result.map((r) => + r.startsWith('./') || r.startsWith('../') ? r : `./${r}` + ); + + // create magic string if it wasn't created already + ms = ms || new MagicString(code); + // unpack variable dynamic import into a function with import statements per file, rollup + // will turn these into chunks automatically + ms.prepend( + `function __variableDynamicImportRuntime${dynamicImportIndex}__(path) { + switch (path) { +${paths.map((p) => ` case '${p}': return import('${p}');`).join('\n')} +${` default: return new Promise(function(resolve, reject) { + (typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)( + reject.bind(null, new Error("Unknown variable dynamic import: " + path)) + ); + })\n`} } + }\n\n` + ); + // call the runtime function instead of doing a dynamic import, the import specifier will + // be evaluated at runtime and the correct import will be returned by the injected function + ms.overwrite( + node.start, + node.start + 6, + `__variableDynamicImportRuntime${dynamicImportIndex}__` + ); + } catch (error) { + if (error instanceof VariableDynamicImportError) { + // TODO: line number + if (warnOnError) { + this.warn(error); + } else { + this.error(error); + } + } else { + this.error(error); + } + } + } + }); + + if (ms && dynamicImportIndex !== -1) { + return { + code: ms.toString(), + map: ms.generateMap({ + file: id, + includeContent: true, + hires: true + }) + }; + } + return null; + } + }; +} + +const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/; +const dataUriPrefix = `/@data-uri/`; +/** + * Build only, since importing from a data URI works natively. + */ +function dataURIPlugin() { + let resolved; + return { + name: 'vite:data-uri', + buildStart() { + resolved = {}; + }, + resolveId(id) { + if (!dataUriRE.test(id)) { + return null; + } + const uri = new require$$0$a.URL(id); + if (uri.protocol !== 'data:') { + return null; + } + const match = uri.pathname.match(dataUriRE); + if (!match) { + return null; + } + const [, mime, format, data] = match; + if (mime !== 'text/javascript') { + throw new Error(`data URI with non-JavaScript mime type is not supported.`); + } + // decode data + const base64 = format && /base64/i.test(format.substring(1)); + const content = base64 + ? Buffer.from(data, 'base64').toString('utf-8') + : data; + resolved[id] = content; + return dataUriPrefix + id; + }, + load(id) { + if (id.startsWith(dataUriPrefix)) { + id = id.slice(dataUriPrefix.length); + return resolved[id] || null; + } + } + }; +} + +/** + * @param {object} exports + * @param {Set} keys + */ +function loop(exports, keys) { + if (typeof exports === 'string') { + return exports; + } + + if (exports) { + let idx, tmp; + if (Array.isArray(exports)) { + for (idx=0; idx < exports.length; idx++) { + if (tmp = loop(exports[idx], keys)) return tmp; + } + } else { + for (idx in exports) { + if (keys.has(idx)) { + return loop(exports[idx], keys); + } + } + } + } +} + +/** + * @param {string} name The package name + * @param {string} entry The target entry, eg "." + * @param {number} [condition] Unmatched condition? + */ +function bail(name, entry, condition) { + throw new Error( + condition + ? `No known conditions for "${entry}" entry in "${name}" package` + : `Missing "${entry}" export in "${name}" package` + ); +} + +/** + * @param {string} name the package name + * @param {string} entry the target path/import + */ +function toName(name, entry) { + return entry === name ? '.' + : entry[0] === '.' ? entry + : entry.replace(new RegExp('^' + name + '\/'), './'); +} + +/** + * @param {object} pkg package.json contents + * @param {string} [entry] entry name or import path + * @param {object} [options] + * @param {boolean} [options.browser] + * @param {boolean} [options.require] + * @param {string[]} [options.conditions] + */ +function resolve$1(pkg, entry='.', options={}) { + let { name, exports } = pkg; + + if (exports) { + let { browser, require, conditions=[] } = options; + + let target = toName(name, entry); + if (target[0] !== '.') target = './' + target; + + if (typeof exports === 'string') { + return target === '.' ? exports : bail(name, target); + } + + let allows = new Set(['default', ...conditions]); + allows.add(require ? 'require' : 'import'); + allows.add(browser ? 'browser' : 'node'); + + let key, tmp, isSingle=false; + + for (key in exports) { + isSingle = key[0] !== '.'; + break; + } + + if (isSingle) { + return target === '.' + ? loop(exports, allows) || bail(name, target, 1) + : bail(name, target); + } + + if (tmp = exports[target]) { + return loop(tmp, allows) || bail(name, target, 1); + } + + for (key in exports) { + tmp = key[key.length - 1]; + if (tmp === '/' && target.startsWith(key)) { + return (tmp = loop(exports[key], allows)) + ? (tmp + target.substring(key.length)) + : bail(name, target, 1); + } + if (tmp === '*' && target.startsWith(key.slice(0, -1))) { + // do not trigger if no *content* to inject + if (target.substring(key.length - 1).length > 0) { + return (tmp = loop(exports[key], allows)) + ? tmp.replace('*', target.substring(key.length - 1)) + : bail(name, target, 1); + } + } + } + + return bail(name, target); + } +} + +// special id for paths marked with browser: false +// https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module +const browserExternalId = '__vite-browser-external'; +const isDebug$5 = process.env.DEBUG; +const debug$b = createDebugger('vite:resolve-details', { + onlyWhenFocused: true +}); +function resolvePlugin(baseOptions) { + const { root, isProduction, asSrc, ssrConfig, preferRelative = false } = baseOptions; + const requireOptions = { + ...baseOptions, + isRequire: true + }; + let server; + const { target: ssrTarget, noExternal: ssrNoExternal } = ssrConfig !== null && ssrConfig !== void 0 ? ssrConfig : {}; + return { + name: 'vite:resolve', + configureServer(_server) { + server = _server; + }, + resolveId(id, importer, resolveOpts, ssr) { + if (id.startsWith(browserExternalId)) { + return id; + } + // fast path for commonjs proxy modules + if (/\?commonjs/.test(id) || id === 'commonjsHelpers.js') { + return; + } + const targetWeb = !ssr || ssrTarget === 'webworker'; + // this is passed by @rollup/plugin-commonjs + const isRequire = resolveOpts && + resolveOpts.custom && + resolveOpts.custom['node-resolve'] && + resolveOpts.custom['node-resolve'].isRequire; + const options = isRequire ? requireOptions : baseOptions; + let res; + // explicit fs paths that starts with /@fs/* + if (asSrc && id.startsWith(FS_PREFIX)) { + const fsPath = fsPathFromId(id); + res = tryFsResolve(fsPath, options); + isDebug$5 && debug$b(`[@fs] ${source.cyan(id)} -> ${source.dim(res)}`); + // always return here even if res doesn't exist since /@fs/ is explicit + // if the file doesn't exist it should be a 404 + return res || fsPath; + } + // URL + // /foo -> /fs-root/foo + if (asSrc && id.startsWith('/')) { + const fsPath = path__default.resolve(root, id.slice(1)); + if ((res = tryFsResolve(fsPath, options))) { + isDebug$5 && debug$b(`[url] ${source.cyan(id)} -> ${source.dim(res)}`); + return res; + } + } + // relative + if (id.startsWith('.') || (preferRelative && /^\w/.test(id))) { + const basedir = importer ? path__default.dirname(importer) : process.cwd(); + const fsPath = path__default.resolve(basedir, id); + // handle browser field mapping for relative imports + const normalizedFsPath = normalizePath$4(fsPath); + const pathFromBasedir = normalizedFsPath.slice(basedir.length); + if (pathFromBasedir.startsWith('/node_modules/')) { + // normalize direct imports from node_modules to bare imports, so the + // hashing logic is shared and we avoid duplicated modules #2503 + const bareImport = pathFromBasedir.slice('/node_modules/'.length); + if ((res = tryNodeResolve(bareImport, importer, options, targetWeb, server, ssr)) && + res.id.startsWith(normalizedFsPath)) { + return res; + } + } + if (targetWeb && + (res = tryResolveBrowserMapping(fsPath, importer, options, true))) { + return res; + } + if ((res = tryFsResolve(fsPath, options))) { + isDebug$5 && debug$b(`[relative] ${source.cyan(id)} -> ${source.dim(res)}`); + const pkg = importer != null && idToPkgMap.get(importer); + if (pkg) { + idToPkgMap.set(res, pkg); + return { + id: res, + moduleSideEffects: pkg.hasSideEffects(res) + }; + } + return res; + } + } + // absolute fs paths + if (path__default.isAbsolute(id) && (res = tryFsResolve(id, options))) { + isDebug$5 && debug$b(`[fs] ${source.cyan(id)} -> ${source.dim(res)}`); + return res; + } + // external + if (isExternalUrl(id)) { + return { + id, + external: true + }; + } + // data uri: pass through (this only happens during build and will be + // handled by dedicated plugin) + if (isDataUrl(id)) { + return null; + } + // bare package imports, perform node resolve + if (bareImportRE.test(id)) { + if (asSrc && + server && + !ssr && + (res = tryOptimizedResolve(id, server, importer))) { + return res; + } + if (targetWeb && + (res = tryResolveBrowserMapping(id, importer, options, false))) { + return res; + } + if ((res = tryNodeResolve(id, importer, options, targetWeb, server, ssr))) { + return res; + } + // node built-ins. + // externalize if building for SSR, otherwise redirect to empty module + if (isBuiltin(id)) { + if (ssr) { + if (ssrNoExternal === true) { + let message = `Cannot bundle Node.js built-in "${id}"`; + if (importer) { + message += ` imported from "${path__default.relative(process.cwd(), importer)}"`; + } + message += `. Consider disabling ssr.noExternal or remove the built-in dependency.`; + this.error(message); + } + return { + id, + external: true + }; + } + else { + if (!asSrc) { + debug$b(`externalized node built-in "${id}" to empty module. ` + + `(imported by: ${source.white.dim(importer)})`); + } + return isProduction + ? browserExternalId + : `${browserExternalId}:${id}`; + } + } + } + isDebug$5 && debug$b(`[fallthrough] ${source.dim(id)}`); + }, + load(id) { + if (id.startsWith(browserExternalId)) { + return isProduction + ? `export default {}` + : `export default new Proxy({}, { + get() { + throw new Error('Module "${id.slice(browserExternalId.length + 1)}" has been externalized for browser compatibility and cannot be accessed in client code.') + } +})`; + } + } + }; +} +function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true) { + let file = fsPath; + let postfix = ''; + let postfixIndex = fsPath.indexOf('?'); + if (postfixIndex < 0) { + postfixIndex = fsPath.indexOf('#'); + } + if (postfixIndex > 0) { + file = fsPath.slice(0, postfixIndex); + postfix = fsPath.slice(postfixIndex); + } + let res; + if ((res = tryResolveFile(file, postfix, options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) { + return res; + } + for (const ext of options.extensions || DEFAULT_EXTENSIONS) { + if ((res = tryResolveFile(file + ext, postfix, options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) { + return res; + } + } + if ((res = tryResolveFile(file, postfix, options, tryIndex, targetWeb, options.tryPrefix, options.skipPackageJson))) { + return res; + } +} +function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix, skipPackageJson) { + let isReadable = false; + try { + // #2051 if we don't have read permission on a directory, existsSync() still + // works and will result in massively slow subsequent checks (which are + // unnecessary in the first place) + fs__default.accessSync(file, fs__default.constants.R_OK); + isReadable = true; + } + catch (e) { } + if (isReadable) { + if (!fs__default.statSync(file).isDirectory()) { + return normalizePath$4(ensureVolumeInPath(file)) + postfix; + } + else if (tryIndex) { + if (!skipPackageJson) { + const pkgPath = file + '/package.json'; + if (fs__default.existsSync(pkgPath)) { + // path points to a node package + const pkg = loadPackageData(pkgPath); + return resolvePackageEntry(file, pkg, options, targetWeb); + } + } + const index = tryFsResolve(file + '/index', options); + if (index) + return index + postfix; + } + } + if (tryPrefix) { + const prefixed = `${path__default.dirname(file)}/${tryPrefix}${path__default.basename(file)}`; + return tryResolveFile(prefixed, postfix, options, tryIndex, targetWeb); + } +} +const idToPkgMap = new Map(); +function tryNodeResolve(id, importer, options, targetWeb, server, ssr) { + var _a, _b, _c; + const { root, dedupe, isBuild } = options; + // split id by last '>' for nested selected packages, for example: + // 'foo > bar > baz' => 'foo > bar' & 'baz' + // 'foo' => '' & 'foo' + const lastArrowIndex = id.lastIndexOf('>'); + const nestedRoot = id.substring(0, lastArrowIndex).trim(); + const nestedPath = id.substring(lastArrowIndex + 1).trim(); + // check for deep import, e.g. "my-lib/foo" + const deepMatch = nestedPath.match(deepImportRE); + const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : nestedPath; + let basedir; + if (dedupe && dedupe.includes(pkgId)) { + basedir = root; + } + else if (importer && + path__default.isAbsolute(importer) && + fs__default.existsSync(cleanUrl(importer))) { + basedir = path__default.dirname(importer); + } + else { + basedir = root; + } + // nested node module, step-by-step resolve to the basedir of the nestedPath + if (nestedRoot) { + basedir = nestedResolveFrom(nestedRoot, basedir); + } + const pkg = resolvePackageData(pkgId, basedir); + if (!pkg) { + return; + } + let resolved = deepMatch + ? resolveDeepImport(id, pkg, options, targetWeb) + : resolvePackageEntry(id, pkg, options, targetWeb); + if (!resolved) { + return; + } + // link id to pkg for browser field mapping check + idToPkgMap.set(resolved, pkg); + if (isBuild) { + // Resolve package side effects for build so that rollup can better + // perform tree-shaking + return { + id: resolved, + moduleSideEffects: pkg.hasSideEffects(resolved) + }; + } + else { + if (!resolved.includes('node_modules') || // linked + !server || // build + server._isRunningOptimizer || // optimizing + !server._optimizeDepsMetadata) { + return { id: resolved }; + } + // if we reach here, it's a valid dep import that hasn't been optimized. + const isJsType = OPTIMIZABLE_ENTRY_RE.test(resolved); + const exclude = (_a = server.config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.exclude; + if (!isJsType || + (importer === null || importer === void 0 ? void 0 : importer.includes('node_modules')) || + (exclude === null || exclude === void 0 ? void 0 : exclude.includes(pkgId)) || + (exclude === null || exclude === void 0 ? void 0 : exclude.includes(id)) || + SPECIAL_QUERY_RE.test(resolved)) { + // excluded from optimization + // Inject a version query to npm deps so that the browser + // can cache it without re-validation, but only do so for known js types. + // otherwise we may introduce duplicated modules for externalized files + // from pre-bundled deps. + const versionHash = (_b = server._optimizeDepsMetadata) === null || _b === void 0 ? void 0 : _b.browserHash; + if (versionHash && isJsType) { + resolved = injectQuery(resolved, `v=${versionHash}`); + } + } + else { + // this is a missing import. + // queue optimize-deps re-run. + (_c = server._registerMissingImport) === null || _c === void 0 ? void 0 : _c.call(server, id, resolved, ssr); + } + return { id: resolved }; + } +} +function tryOptimizedResolve(id, server, importer) { + const cacheDir = server.config.cacheDir; + const depData = server._optimizeDepsMetadata; + if (!cacheDir || !depData) + return; + const getOptimizedUrl = (optimizedData) => { + return (optimizedData.file + + `?v=${depData.browserHash}${optimizedData.needsInterop ? `&es-interop` : ``}`); + }; + // check if id has been optimized + const isOptimized = depData.optimized[id]; + if (isOptimized) { + return getOptimizedUrl(isOptimized); + } + if (!importer) + return; + // further check if id is imported by nested dependency + let resolvedSrc; + for (const [pkgPath, optimizedData] of Object.entries(depData.optimized)) { + // check for scenarios, e.g. + // pkgPath => "my-lib > foo" + // id => "foo" + // this narrows the need to do a full resolve + if (!pkgPath.endsWith(id)) + continue; + // lazily initialize resolvedSrc + if (resolvedSrc == null) { + try { + // this may throw errors if unable to resolve, e.g. aliased id + resolvedSrc = normalizePath$4(resolveFrom$3(id, path__default.dirname(importer))); + } + catch { + // this is best-effort only so swallow errors + break; + } + } + // match by src to correctly identify if id belongs to nested dependency + if (optimizedData.src === resolvedSrc) { + return getOptimizedUrl(optimizedData); + } + } +} +const packageCache = new Map(); +function resolvePackageData(id, basedir) { + const cacheKey = id + basedir; + if (packageCache.has(cacheKey)) { + return packageCache.get(cacheKey); + } + try { + const pkgPath = resolveFrom$3(`${id}/package.json`, basedir); + return loadPackageData(pkgPath, cacheKey); + } + catch (e) { + isDebug$5 && debug$b(`${source.red(`[failed loading package.json]`)} ${id}`); + } +} +function loadPackageData(pkgPath, cacheKey = pkgPath) { + const data = JSON.parse(fs__default.readFileSync(pkgPath, 'utf-8')); + const pkgDir = path__default.dirname(pkgPath); + const { sideEffects } = data; + let hasSideEffects; + if (typeof sideEffects === 'boolean') { + hasSideEffects = () => sideEffects; + } + else if (Array.isArray(sideEffects)) { + hasSideEffects = createFilter$1(sideEffects, null, { resolve: pkgDir }); + } + else { + hasSideEffects = () => true; + } + const pkg = { + dir: pkgDir, + data, + hasSideEffects, + webResolvedImports: {}, + nodeResolvedImports: {}, + setResolvedCache(key, entry, targetWeb) { + if (targetWeb) { + pkg.webResolvedImports[key] = entry; + } + else { + pkg.nodeResolvedImports[key] = entry; + } + }, + getResolvedCache(key, targetWeb) { + if (targetWeb) { + return pkg.webResolvedImports[key]; + } + else { + return pkg.nodeResolvedImports[key]; + } + } + }; + packageCache.set(cacheKey, pkg); + return pkg; +} +function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options, targetWeb) { + var _a, _b; + const cached = getResolvedCache('.', targetWeb); + if (cached) { + return cached; + } + try { + let entryPoint; + // resolve exports field with highest priority + // using https://github.com/lukeed/resolve.exports + if (data.exports) { + entryPoint = resolveExports(data, '.', options, targetWeb); + } + // if exports resolved to .mjs, still resolve other fields. + // This is because .mjs files can technically import .cjs files which would + // make them invalid for pure ESM environments - so if other module/browser + // fields are present, prioritize those instead. + if (targetWeb && (!entryPoint || entryPoint.endsWith('.mjs'))) { + // check browser field + // https://github.com/defunctzombie/package-browser-field-spec + const browserEntry = typeof data.browser === 'string' + ? data.browser + : isObject$3(data.browser) && data.browser['.']; + if (browserEntry) { + // check if the package also has a "module" field. + if (typeof data.module === 'string' && data.module !== browserEntry) { + // if both are present, we may have a problem: some package points both + // to ESM, with "module" targeting Node.js, while some packages points + // "module" to browser ESM and "browser" to UMD. + // the heuristics here is to actually read the browser entry when + // possible and check for hints of UMD. If it is UMD, prefer "module" + // instead; Otherwise, assume it's ESM and use it. + const resolvedBrowserEntry = tryFsResolve(path__default.join(dir, browserEntry), options); + if (resolvedBrowserEntry) { + const content = fs__default.readFileSync(resolvedBrowserEntry, 'utf-8'); + if ((/typeof exports\s*==/.test(content) && + /typeof module\s*==/.test(content)) || + /module\.exports\s*=/.test(content)) { + // likely UMD or CJS(!!! e.g. firebase 7.x), prefer module + entryPoint = data.module; + } + } + } + else { + entryPoint = browserEntry; + } + } + } + if (!entryPoint || entryPoint.endsWith('.mjs')) { + for (const field of options.mainFields || DEFAULT_MAIN_FIELDS) { + if (typeof data[field] === 'string') { + entryPoint = data[field]; + break; + } + } + } + entryPoint = entryPoint || data.main || 'index.js'; + // make sure we don't get scripts when looking for sass + if (((_a = options.mainFields) === null || _a === void 0 ? void 0 : _a[0]) === 'sass' && + !((_b = options.extensions) === null || _b === void 0 ? void 0 : _b.includes(path__default.extname(entryPoint)))) { + entryPoint = ''; + options.skipPackageJson = true; + } + // resolve object browser field in package.json + const { browser: browserField } = data; + if (targetWeb && isObject$3(browserField)) { + entryPoint = mapWithBrowserField(entryPoint, browserField) || entryPoint; + } + entryPoint = path__default.join(dir, entryPoint); + const resolvedEntryPoint = tryFsResolve(entryPoint, options); + if (resolvedEntryPoint) { + isDebug$5 && + debug$b(`[package entry] ${source.cyan(id)} -> ${source.dim(resolvedEntryPoint)}`); + setResolvedCache('.', resolvedEntryPoint, targetWeb); + return resolvedEntryPoint; + } + else { + packageEntryFailure(id); + } + } + catch (e) { + packageEntryFailure(id, e.message); + } +} +function packageEntryFailure(id, details) { + throw new Error(`Failed to resolve entry for package "${id}". ` + + `The package may have incorrect main/module/exports specified in its package.json` + + (details ? ': ' + details : '.')); +} +function resolveExports(pkg, key, options, targetWeb) { + const conditions = [options.isProduction ? 'production' : 'development']; + if (!options.isRequire) { + conditions.push('module'); + } + if (options.conditions) { + conditions.push(...options.conditions); + } + return resolve$1(pkg, key, { + browser: targetWeb, + require: options.isRequire, + conditions + }); +} +function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolvedCache, dir, data }, options, targetWeb) { + id = '.' + id.slice(data.name.length); + const cache = getResolvedCache(id, targetWeb); + if (cache) { + return cache; + } + let relativeId = id; + const { exports: exportsField, browser: browserField } = data; + // map relative based on exports data + if (exportsField) { + if (isObject$3(exportsField) && !Array.isArray(exportsField)) { + relativeId = resolveExports(data, relativeId, options, targetWeb); + } + else { + // not exposed + relativeId = undefined; + } + if (!relativeId) { + throw new Error(`Package subpath '${relativeId}' is not defined by "exports" in ` + + `${path__default.join(dir, 'package.json')}.`); + } + } + else if (targetWeb && isObject$3(browserField)) { + const mapped = mapWithBrowserField(relativeId, browserField); + if (mapped) { + relativeId = mapped; + } + else if (mapped === false) { + return (webResolvedImports[id] = browserExternalId); + } + } + if (relativeId) { + const resolved = tryFsResolve(path__default.join(dir, relativeId), options, !exportsField, // try index only if no exports field + targetWeb); + if (resolved) { + isDebug$5 && + debug$b(`[node/deep-import] ${source.cyan(id)} -> ${source.dim(resolved)}`); + setResolvedCache(id, resolved, targetWeb); + return resolved; + } + } +} +function tryResolveBrowserMapping(id, importer, options, isFilePath) { + let res; + const pkg = importer && idToPkgMap.get(importer); + if (pkg && isObject$3(pkg.data.browser)) { + const mapId = isFilePath ? './' + slash$3(path__default.relative(pkg.dir, id)) : id; + const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser); + if (browserMappedPath) { + const fsPath = path__default.join(pkg.dir, browserMappedPath); + if ((res = tryFsResolve(fsPath, options))) { + isDebug$5 && + debug$b(`[browser mapped] ${source.cyan(id)} -> ${source.dim(res)}`); + idToPkgMap.set(res, pkg); + return { + id: res, + moduleSideEffects: pkg.hasSideEffects(res) + }; + } + } + else if (browserMappedPath === false) { + return browserExternalId; + } + } +} +/** + * given a relative path in pkg dir, + * return a relative path in pkg dir, + * mapped with the "map" object + * + * - Returning `undefined` means there is no browser mapping for this id + * - Returning `false` means this id is explicitly externalized for browser + */ +function mapWithBrowserField(relativePathInPkgDir, map) { + const normalizedPath = path__default.posix.normalize(relativePathInPkgDir); + for (const key in map) { + const normalizedKey = path__default.posix.normalize(key); + if (normalizedPath === normalizedKey || + equalWithoutSuffix(normalizedPath, normalizedKey, '.js') || + equalWithoutSuffix(normalizedPath, normalizedKey, '/index.js')) { + return map[key]; + } + } +} +function equalWithoutSuffix(path, key, suffix) { + return key.endsWith(suffix) && key.slice(0, -suffix.length) === path; +} + +/** + * Heuristics for determining whether a dependency should be externalized for + * server-side rendering. + * + * TODO right now externals are imported using require(), we probably need to + * rework this when more libraries ship native ESM distributions for Node. + */ +function resolveSSRExternal(config, knownImports, ssrExternals = new Set(), seen = new Set()) { + var _a, _b, _c, _d; + if (((_a = config.ssr) === null || _a === void 0 ? void 0 : _a.noExternal) === true) { + return []; + } + const { root } = config; + const pkgContent = lookupFile(root, ['package.json']); + if (!pkgContent) { + return []; + } + const pkg = JSON.parse(pkgContent); + const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined); + const deps = unique([ + ...importedDeps, + ...Object.keys(pkg.devDependencies || {}), + ...Object.keys(pkg.dependencies || {}) + ]); + const resolveOptions = { + root, + isProduction: false, + isBuild: true + }; + const depsToTrace = new Set(); + for (const id of deps) { + if (seen.has(id)) { + continue; + } + seen.add(id); + let entry; + let requireEntry; + try { + entry = (_b = tryNodeResolve(id, undefined, resolveOptions, true, undefined, true)) === null || _b === void 0 ? void 0 : _b.id; + requireEntry = require.resolve(id, { paths: [root] }); + } + catch (e) { + // resolve failed, assume include + continue; + } + if (!entry) { + // no esm entry but has require entry (is this even possible?) + ssrExternals.add(id); + continue; + } + if (!entry.includes('node_modules')) { + // entry is not a node dep, possibly linked - don't externalize + // instead, trace its dependencies. + depsToTrace.add(id); + continue; + } + if (entry !== requireEntry) { + // has separate esm/require entry, assume require entry is cjs + ssrExternals.add(id); + } + else { + // node resolve and esm resolve resolves to the same file. + if (!/\.m?js$/.test(entry)) { + // entry is not js, cannot externalize + continue; + } + // check if the entry is cjs + const content = fs__default.readFileSync(entry, 'utf-8'); + if (/\bmodule\.exports\b|\bexports[.\[]|\brequire\s*\(/.test(content)) { + ssrExternals.add(id); + } + } + } + for (const id of depsToTrace) { + const depRoot = path__default.dirname(resolveFrom$3(`${id}/package.json`, root)); + resolveSSRExternal({ + ...config, + root: depRoot + }, knownImports, ssrExternals, seen); + } + if ((_c = config.ssr) === null || _c === void 0 ? void 0 : _c.external) { + config.ssr.external.forEach((id) => ssrExternals.add(id)); + } + let externals = [...ssrExternals]; + if ((_d = config.ssr) === null || _d === void 0 ? void 0 : _d.noExternal) { + const filter = createFilter$1(undefined, config.ssr.noExternal, { + resolve: false + }); + externals = externals.filter((id) => filter(id)); + } + return externals.filter((id) => id !== 'vite'); +} +function shouldExternalizeForSSR(id, externals) { + const should = externals.some((e) => { + if (id === e) { + return true; + } + // deep imports, check ext before externalizing - only externalize + // extension-less imports and explicit .js imports + if (id.startsWith(e + '/') && (!path__default.extname(id) || id.endsWith('.js'))) { + return true; + } + }); + return should; +} +function getNpmPackageName(importPath) { + const parts = importPath.split('/'); + if (parts[0].startsWith('@')) { + if (!parts[1]) + return null; + return `${parts[0]}/${parts[1]}`; + } + else { + return parts[0]; + } +} + +function ssrManifestPlugin(config) { + // module id => preload assets mapping + const ssrManifest = {}; + const base = config.base; + return { + name: 'vite:manifest', + generateBundle(_options, bundle) { + for (const file in bundle) { + const chunk = bundle[file]; + if (chunk.type === 'chunk') { + // links for certain entry chunks are already generated in static HTML + // in those cases we only need to record info for non-entry chunks + const cssFiles = chunk.isEntry + ? null + : chunkToEmittedCssFileMap.get(chunk); + const assetFiles = chunkToEmittedAssetsMap.get(chunk); + for (const id in chunk.modules) { + const normalizedId = normalizePath$3(path$w.relative(config.root, id)); + const mappedChunks = ssrManifest[normalizedId] || (ssrManifest[normalizedId] = []); + if (!chunk.isEntry) { + mappedChunks.push(base + chunk.fileName); + } + if (cssFiles) { + cssFiles.forEach((file) => { + mappedChunks.push(base + file); + }); + } + if (assetFiles) { + assetFiles.forEach((file) => { + mappedChunks.push(base + file); + }); + } + } + } + } + this.emitFile({ + fileName: 'ssr-manifest.json', + type: 'asset', + source: JSON.stringify(ssrManifest, null, 2) + }); + } + }; +} + +// Reserved word lists for various dialects of the language + +var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" +}; + +// And the keywords + +var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; + +var keywords = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" +}; + +var keywordRelationalOperator = /^in(stanceof)?$/; + +// ## Character categories + +// Big ugly regular expressions that match characters in the +// whitespace, identifier, and identifier-start categories. These +// are only applied when a character is found to actually have a +// code point above 128. +// Generated by `bin/generate-identifier-regex.js`. +var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + +var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + +// These are a run-length and offset encoded representation of the +// >0xffff code points that are a valid part of identifiers. The +// offset starts at 0x10000, and each pair of numbers represents an +// offset to the next range, and then a size of the range. They were +// generated by bin/generate-identifier-regex.js + +// eslint-disable-next-line comma-spacing +var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938]; + +// eslint-disable-next-line comma-spacing +var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239]; + +// This has a complexity linear to the value of the code. The +// assumption is that looking up astral identifier characters is +// rare. +function isInAstralSet(code, set) { + var pos = 0x10000; + for (var i = 0; i < set.length; i += 2) { + pos += set[i]; + if (pos > code) { return false } + pos += set[i + 1]; + if (pos >= code) { return true } + } +} + +// Test whether a given character code starts an identifier. + +function isIdentifierStart(code, astral) { + if (code < 65) { return code === 36 } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) +} + +// Test whether a given character is part of an identifier. + +function isIdentifierChar(code, astral) { + if (code < 48) { return code === 36 } + if (code < 58) { return true } + if (code < 65) { return false } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) +} + +// ## Token types + +// The assignment of fine-grained, information-carrying type objects +// allows the tokenizer to store the information it has about a +// token in a way that is very cheap for the parser to look up. + +// All token type variables start with an underscore, to make them +// easy to recognize. + +// The `beforeExpr` property is used to disambiguate between regular +// expressions and divisions. It is set on all token types that can +// be followed by an expression (thus, a slash after them would be a +// regular expression). +// +// The `startsExpr` property is used to check if the token ends a +// `yield` expression. It is set on all token types that either can +// directly start an expression (like a quotation mark) or can +// continue an expression (like the body of a string). +// +// `isLoop` marks a keyword as starting a loop, which is important +// to know when parsing a label, in order to allow or disallow +// continue jumps to that label. + +var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; +}; + +function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) +} +var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; + +// Map keyword names to token types. + +var keywords$1 = {}; + +// Succinct definitions of keyword token types +function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name; + return keywords$1[name] = new TokenType(name, options) +} + +var types = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + coalesce: binop("??", 1), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) +}; + +// Matches a whole line break (where CRLF is considered a single +// line break). Used to count lines. + +var lineBreak = /\r\n?|\n|\u2028|\u2029/; +var lineBreakG = new RegExp(lineBreak.source, "g"); + +function isNewLine(code, ecma2019String) { + return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) +} + +var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + +var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + +var ref = Object.prototype; +var hasOwnProperty$1 = ref.hasOwnProperty; +var toString$1 = ref.toString; + +// Checks if an object has a property. + +function has$1(obj, propName) { + return hasOwnProperty$1.call(obj, propName) +} + +var isArray = Array.isArray || (function (obj) { return ( + toString$1.call(obj) === "[object Array]" +); }); + +function wordsRegexp(words) { + return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") +} + +// These are used when `options.locations` is on, for the +// `startLoc` and `endLoc` properties. + +var Position = function Position(line, col) { + this.line = line; + this.column = col; +}; + +Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) +}; + +var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } +}; + +// The `getLineInfo` function is mostly useful when the +// `locations` option is off (for performance reasons) and you +// want to find the line/column position for a given character +// offset. `input` should be the code string that the offset refers +// into. + +function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + lineBreakG.lastIndex = cur; + var match = lineBreakG.exec(input); + if (match && match.index < offset) { + ++line; + cur = match.index + match[0].length; + } else { + return new Position(line, offset - cur) + } + } +} + +// A second argument must be given to configure the parser process. +// These options are recognized (only `ecmaVersion` is required): + +var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the + // latest version the library supports). This influences support + // for strict mode, the set of reserved words, and support for + // new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called + // when a semicolon is automatically inserted. It will be passed + // the position of the comma as an offset, and if `locations` is + // enabled, it is given the location as a `{line, column}` object + // as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file + // is allowed and treated as a line comment. + allowHashBang: false, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false +}; + +// Interpret and default an options object + +var warnedAboutEcmaVersion = false; + +function getOptions(opts) { + var options = {}; + + for (var opt in defaultOptions) + { options[opt] = opts && has$1(opts, opt) ? opts[opt] : defaultOptions[opt]; } + + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } + + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } + + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function (token) { return tokens.push(token); }; + } + if (isArray(options.onComment)) + { options.onComment = pushComment(options, options.onComment); } + + return options +} + +function pushComment(options, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text, + start: start, + end: end + }; + if (options.locations) + { comment.loc = new SourceLocation(this, startLoc, endLoc); } + if (options.ranges) + { comment.range = [start, end]; } + array.push(comment); + } +} + +// Each scope gets a bitset that may contain these flags +var + SCOPE_TOP = 1, + SCOPE_FUNCTION = 2, + SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128; + +function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) +} + +// Used in checkLVal* and declareName to determine the type of a binding +var + BIND_NONE = 0, // Not a binding + BIND_VAR = 1, // Var-style binding + BIND_LEXICAL = 2, // Let- or const-style binding + BIND_FUNCTION = 3, // Function declaration + BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding + BIND_OUTSIDE = 5; // Special case for function names as bound inside the function + +var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { reserved += " await"; } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false; + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + + // Properties of the current token: + // Its type + this.type = types.eof; + // For tokens that include more information than their type, the value + this.value = null; + // Its start and end offset + this.start = this.end = this.pos; + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition(); + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext(); + this.exprAllowed = true; + + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + // Labels in scope. + this.labels = []; + // Thus-far undefined exports. + this.undefinedExports = Object.create(null); + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } + + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + + // For RegExp validation + this.regexpState = null; + + // The stack of private names. + // Each element has two properties: 'declared' and 'used'. + // When it exited from the outermost class definition, all used private names must be declared. + this.privateNameStack = []; +}; + +var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } }; + +Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node) +}; + +prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; +prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; +prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; +prototypeAccessors.canAwait.get = function () { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var scope = this.scopeStack[i]; + if (scope.inClassFieldInit) { return false } + if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } + } + return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction +}; +prototypeAccessors.allowSuper.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod +}; +prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; +prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; +prototypeAccessors.inNonArrowFunction.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & SCOPE_FUNCTION) > 0 || inClassFieldInit +}; + +Parser.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; + + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls +}; + +Parser.parse = function parse (input, options) { + return new this(options, input).parse() +}; + +Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() +}; + +Parser.tokenizer = function tokenizer (input, options) { + return new this(options, input) +}; + +Object.defineProperties( Parser.prototype, prototypeAccessors ); + +var pp = Parser.prototype; + +// ## Parser utilities + +var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; +pp.strictDirective = function(start) { + for (;;) { + // Try to find string literal. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { return false } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || + (lineBreak.test(spaceAfter[0]) && + !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) + } + start += match[0].length; + + // Skip semicolon, if any. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") + { start++; } + } +}; + +// Predicate that tests whether the next token is of the given +// type, and if yes, consumes it as a side effect. + +pp.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false + } +}; + +// Tests whether parsed token is a contextual keyword. + +pp.isContextual = function(name) { + return this.type === types.name && this.value === name && !this.containsEsc +}; + +// Consumes contextual keyword if possible. + +pp.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true +}; + +// Asserts that following token is given contextual keyword. + +pp.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } +}; + +// Test whether a semicolon can be inserted at the current position. + +pp.canInsertSemicolon = function() { + return this.type === types.eof || + this.type === types.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) +}; + +pp.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true + } +}; + +// Consume a semicolon, or, failing that, see if we are allowed to +// pretend that there is a semicolon at this position. + +pp.semicolon = function() { + if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } +}; + +pp.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) + { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } + if (!notNext) + { this.next(); } + return true + } +}; + +// Expect a token of a given type. If found, consume it, otherwise, +// raise an unexpected token error. + +pp.expect = function(type) { + this.eat(type) || this.unexpected(); +}; + +// Raise an unexpected token error. + +pp.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); +}; + +function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; +} + +pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { return } + if (refDestructuringErrors.trailingComma > -1) + { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } +}; + +pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { return false } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } + if (shorthandAssign >= 0) + { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } + if (doubleProto >= 0) + { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } +}; + +pp.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } + if (this.awaitPos) + { this.raise(this.awaitPos, "Await expression cannot be a default value"); } +}; + +pp.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") + { return this.isSimpleAssignTarget(expr.expression) } + return expr.type === "Identifier" || expr.type === "MemberExpression" +}; + +var pp$1 = Parser.prototype; + +// ### Statement parsing + +// Parse a program. Initializes the parser, reads any number of +// statements, and wraps them in a Program node. Optionally takes a +// `program` argument. If present, the statements will be appended +// to its body instead of creating a new node. + +pp$1.parseTopLevel = function(node) { + var exports = Object.create(null); + if (!node.body) { node.body = []; } + while (this.type !== types.eof) { + var stmt = this.parseStatement(null, true, exports); + node.body.push(stmt); + } + if (this.inModule) + { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) + { + var name = list[i]; + + this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); + } } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType; + return this.finishNode(node, "Program") +}; + +var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + +pp$1.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + // For ambiguous cases, determine if a LexicalDeclaration (or only a + // Statement) is allowed here. If context is not empty then only a Statement + // is allowed. However, `let [` is an explicit negative lookahead for + // ExpressionStatement, so special-case it first. + if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral + if (context) { return false } + + if (nextCh === 123) { return true } // '{' + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } + if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { return true } + } + return false +}; + +// check 'async [no LineTerminator here] function' +// - 'async /*foo*/ function' is OK. +// - 'async /*\n*/ function' is invalid. +pp$1.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || + !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) +}; + +// Parse a single statement. +// +// If expecting a statement and finding a slash operator, parse a +// regular expression literal. This is to handle cases like +// `if (foo) /blah/.exec(foo)`, where looking at the previous token +// does not help. + +pp$1.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + + if (this.isLet(context)) { + starttype = types._var; + kind = "let"; + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case types._debugger: return this.parseDebuggerStatement(node) + case types._do: return this.parseDoStatement(node) + case types._for: return this.parseForStatement(node) + case types._function: + // Function as sole body of either an if statement or a labeled statement + // works, but not when it is part of a labeled statement that is the sole + // body of an if statement. + if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } + return this.parseFunctionStatement(node, false, !context) + case types._class: + if (context) { this.unexpected(); } + return this.parseClass(node, true) + case types._if: return this.parseIfStatement(node) + case types._return: return this.parseReturnStatement(node) + case types._switch: return this.parseSwitchStatement(node) + case types._throw: return this.parseThrowStatement(node) + case types._try: return this.parseTryStatement(node) + case types._const: case types._var: + kind = kind || this.value; + if (context && kind !== "var") { this.unexpected(); } + return this.parseVarStatement(node, kind) + case types._while: return this.parseWhileStatement(node) + case types._with: return this.parseWithStatement(node) + case types.braceL: return this.parseBlock(true, node) + case types.semi: return this.parseEmptyStatement(node) + case types._export: + case types._import: + if (this.options.ecmaVersion > 10 && starttype === types._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) // '(' or '.' + { return this.parseExpressionStatement(node, this.parseExpression()) } + } + + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } + if (!this.inModule) + { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } + } + return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { this.unexpected(); } + this.next(); + return this.parseFunctionStatement(node, true, !context) + } + + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) + { return this.parseLabeledStatement(node, maybeName, expr, context) } + else { return this.parseExpressionStatement(node, expr) } + } +}; + +pp$1.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } + else if (this.type !== types.name) { this.unexpected(); } + else { + node.label = this.parseIdent(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } + if (node.label && isBreak) { break } + } + } + if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") +}; + +pp$1.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") +}; + +pp$1.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) + { this.eat(types.semi); } + else + { this.semicolon(); } + return this.finishNode(node, "DoWhileStatement") +}; + +// Disambiguating between a `for` and a `for`/`in` or `for`/`of` +// loop is non-trivial. Basically, we have to parse the init `var` +// statement or expression, disallowing the `in` operator (see +// the second parameter to `parseExpression`), and then check +// whether the next token is `in` or `of`. When there is no init +// part (semicolon immediately after the opening parenthesis), it +// is a regular `for` loop. + +pp$1.parseForStatement = function(node) { + this.next(); + var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types.parenL); + if (this.type === types.semi) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, null) + } + var isLet = this.isLet(); + if (this.type === types._var || this.type === types._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + return this.parseForIn(node, init$1) + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init$1) + } + var refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); + if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) +}; + +pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) +}; + +pp$1.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement") +}; + +pp$1.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") +}; + +pp$1.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur; + for (var sawDefault = false; this.type !== types.braceR;) { + if (this.type === types._case || this.type === types._default) { + var isCase = this.type === types._case; + if (cur) { this.finishNode(cur, "SwitchCase"); } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } + sawDefault = true; + cur.test = null; + } + this.expect(types.colon); + } else { + if (!cur) { this.unexpected(); } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { this.finishNode(cur, "SwitchCase"); } + this.next(); // Closing brace + this.labels.pop(); + return this.finishNode(node, "SwitchStatement") +}; + +pp$1.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + { this.raise(this.lastTokEnd, "Illegal newline after throw"); } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement") +}; + +// Reused empty array added for node fields that are always empty. + +var empty = []; + +pp$1.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types.parenL)) { + clause.param = this.parseBindingAtom(); + var simple = clause.param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types.parenR); + } else { + if (this.options.ecmaVersion < 10) { this.unexpected(); } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) + { this.raise(node.start, "Missing catch or finally clause"); } + return this.finishNode(node, "TryStatement") +}; + +pp$1.parseVarStatement = function(node, kind) { + this.next(); + this.parseVar(node, false, kind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") +}; + +pp$1.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement") +}; + +pp$1.parseWithStatement = function(node) { + if (this.strict) { this.raise(this.start, "'with' in strict mode"); } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement") +}; + +pp$1.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") +}; + +pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) + { + var label = list[i$1]; + + if (label.name === maybeName) + { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } } + var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this.labels[i]; + if (label$1.statementStart === node.start) { + // Update information about previous labels on this node + label$1.statementStart = this.start; + label$1.kind = kind; + } else { break } + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement") +}; + +pp$1.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") +}; + +// Parse a semicolon-enclosed block of statements, handling `"use +// strict"` declarations when `allowStrict` is true (used for +// function bodies). + +pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); + + node.body = []; + this.expect(types.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (this.type !== types.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + if (exitStrict) { this.strict = false; } + this.next(); + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") +}; + +// Parse a regular `for` loop. The disambiguation code in +// `parseStatement` will already have parsed the init statement or +// expression. + +pp$1.parseFor = function(node, init) { + node.init = init; + this.expect(types.semi); + node.test = this.type === types.semi ? null : this.parseExpression(); + this.expect(types.semi); + node.update = this.type === types.parenR ? null : this.parseExpression(); + this.expect(types.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement") +}; + +// Parse a `for`/`in` and `for`/`of` loop, which are almost +// same from parser's perspective. + +pp$1.parseForIn = function(node, init) { + var isForIn = this.type === types._in; + this.next(); + + if ( + init.type === "VariableDeclaration" && + init.declarations[0].init != null && + ( + !isForIn || + this.options.ecmaVersion < 8 || + this.strict || + init.kind !== "var" || + init.declarations[0].id.type !== "Identifier" + ) + ) { + this.raise( + init.start, + ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") + ); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") +}; + +// Parse a list of variable declarations. + +pp$1.parseVar = function(node, isFor, kind) { + node.declarations = []; + node.kind = kind; + for (;;) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { + this.unexpected(); + } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types.comma)) { break } + } + return node +}; + +pp$1.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); +}; + +var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + +// Parse a function declaration or literal (depending on the +// `statement & FUNC_STATEMENT`). + +// Remove `allowExpressionBody` for 7.0.0, as it is only called with false +pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) + { this.unexpected(); } + node.generator = this.eat(types.star); + } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) + // If it is a regular function declaration in sloppy mode, then it is + // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding + // mode depends on properties of the current scope (see + // treatFunctionsAsVar). + { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } + } + + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + + if (!(statement & FUNC_STATEMENT)) + { node.id = this.type === types.name ? this.parseIdent() : null; } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") +}; + +pp$1.parseFunctionParams = function(node) { + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); +}; + +// Parse a class declaration or literal (depending on the +// `isStatement` parameter). + +pp$1.parseClass = function(node, isStatement) { + this.next(); + + // ecma-262 14.6 Class Definitions + // A class definition is always strict mode code. + var oldStrict = this.strict; + this.strict = true; + + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types.braceL); + while (this.type !== types.braceR) { + var element = this.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); } + hadConstructor = true; + } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") +}; + +pp$1.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types.semi)) { return null } + + var ecmaVersion = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + + // Parse modifiers + node.static = false; + if (this.eatContextual("static")) { + if (this.isClassElementNameStart() || this.type === types.star) { + node.static = true; + } else { + keyName = "static"; + } + } + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + + // Parse element name + if (keyName) { + // 'async', 'get', 'set', or 'static' were not a keyword contextually. + // The last token is any of those. Make it the element name. + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + + // Parse element value + if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. + if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + + return node +}; + +pp$1.isClassElementNameStart = function() { + return ( + this.type === types.name || + this.type === types.privateId || + this.type === types.num || + this.type === types.string || + this.type === types.bracketL || + this.type.keyword + ) +}; + +pp$1.parseClassElementName = function(element) { + if (this.type === types.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } +}; + +pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + // Check key and flags + var key = method.key; + if (method.kind === "constructor") { + if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } + if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + + // Parse value + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + + // Check value + if (method.kind === "get" && value.params.length !== 0) + { this.raiseRecoverable(value.start, "getter should have no params"); } + if (method.kind === "set" && value.params.length !== 1) + { this.raiseRecoverable(value.start, "setter should have exactly one param"); } + if (method.kind === "set" && value.params[0].type === "RestElement") + { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } + + return this.finishNode(method, "MethodDefinition") +}; + +pp$1.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + + if (this.eat(types.eq)) { + // To raise SyntaxError if 'arguments' exists in the initializer. + var scope = this.currentThisScope(); + var inClassFieldInit = scope.inClassFieldInit; + scope.inClassFieldInit = true; + field.value = this.parseMaybeAssign(); + scope.inClassFieldInit = inClassFieldInit; + } else { + field.value = null; + } + this.semicolon(); + + return this.finishNode(field, "PropertyDefinition") +}; + +pp$1.parseClassId = function(node, isStatement) { + if (this.type === types.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLValSimple(node.id, BIND_LEXICAL, false); } + } else { + if (isStatement === true) + { this.unexpected(); } + node.id = null; + } +}; + +pp$1.parseClassSuper = function(node) { + node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; +}; + +pp$1.enterClassBody = function() { + var element = {declared: Object.create(null), used: []}; + this.privateNameStack.push(element); + return element.declared +}; + +pp$1.exitClassBody = function() { + var ref = this.privateNameStack.pop(); + var declared = ref.declared; + var used = ref.used; + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i = 0; i < used.length; ++i) { + var id = used[i]; + if (!has$1(declared, id.name)) { + if (parent) { + parent.used.push(id); + } else { + this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); + } + } + } +}; + +function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; + } + + // `class { get #a(){}; static set #a(_){} }` is also conflict. + if ( + curr === "iget" && next === "iset" || + curr === "iset" && next === "iget" || + curr === "sget" && next === "sset" || + curr === "sset" && next === "sget" + ) { + privateNameMap[name] = "true"; + return false + } else if (!curr) { + privateNameMap[name] = next; + return false + } else { + return true + } +} + +function checkKeyName(node, name) { + var computed = node.computed; + var key = node.key; + return !computed && ( + key.type === "Identifier" && key.name === name || + key.type === "Literal" && key.value === name + ) +} + +// Parses module export declaration. + +pp$1.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types.star)) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseIdent(true); + this.checkExport(exports, node.exported.name, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration") + } + if (this.eat(types._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart); + var isAsync; + if (this.type === types._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { this.next(); } + node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); + } else if (this.type === types._class) { + var cNode = this.startNode(); + node.declaration = this.parseClass(cNode, "nullableID"); + } else { + node.declaration = this.parseMaybeAssign(); + this.semicolon(); + } + return this.finishNode(node, "ExportDefaultDeclaration") + } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseStatement(null); + if (node.declaration.type === "VariableDeclaration") + { this.checkVariableExport(exports, node.declaration.declarations); } + else + { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } + node.specifiers = []; + node.source = null; + } else { // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; + + this.checkUnreserved(spec.local); + // check if export is defined + this.checkLocalExport(spec.local); + } + + node.source = null; + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration") +}; + +pp$1.checkExport = function(exports, name, pos) { + if (!exports) { return } + if (has$1(exports, name)) + { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } + exports[name] = true; +}; + +pp$1.checkPatternExport = function(exports, pat) { + var type = pat.type; + if (type === "Identifier") + { this.checkExport(exports, pat.name, pat.start); } + else if (type === "ObjectPattern") + { for (var i = 0, list = pat.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this.checkPatternExport(exports, prop); + } } + else if (type === "ArrayPattern") + { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + + if (elt) { this.checkPatternExport(exports, elt); } + } } + else if (type === "Property") + { this.checkPatternExport(exports, pat.value); } + else if (type === "AssignmentPattern") + { this.checkPatternExport(exports, pat.left); } + else if (type === "RestElement") + { this.checkPatternExport(exports, pat.argument); } + else if (type === "ParenthesizedExpression") + { this.checkPatternExport(exports, pat.expression); } +}; + +pp$1.checkVariableExport = function(exports, decls) { + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; + + this.checkPatternExport(exports, decl.id); + } +}; + +pp$1.shouldParseExportStatement = function() { + return this.type.keyword === "var" || + this.type.keyword === "const" || + this.type.keyword === "class" || + this.type.keyword === "function" || + this.isLet() || + this.isAsyncFunction() +}; + +// Parses a comma-separated list of module exports. + +pp$1.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + // export { x, y as z } [from '...'] + this.expect(types.braceL); + while (!this.eat(types.braceR)) { + if (!first) { + this.expect(types.comma); + if (this.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var node = this.startNode(); + node.local = this.parseIdent(true); + node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local; + this.checkExport(exports, node.exported.name, node.exported.start); + nodes.push(this.finishNode(node, "ExportSpecifier")); + } + return nodes +}; + +// Parses import declaration. + +pp$1.parseImport = function(node) { + this.next(); + // import '...' + if (this.type === types.string) { + node.specifiers = empty; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration") +}; + +// Parses a comma-separated list of module imports. + +pp$1.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types.name) { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); + if (!this.eat(types.comma)) { return nodes } + } + if (this.type === types.star) { + var node$1 = this.startNode(); + this.next(); + this.expectContextual("as"); + node$1.local = this.parseIdent(); + this.checkLValSimple(node$1.local, BIND_LEXICAL); + nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); + return nodes + } + this.expect(types.braceL); + while (!this.eat(types.braceR)) { + if (!first) { + this.expect(types.comma); + if (this.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var node$2 = this.startNode(); + node$2.imported = this.parseIdent(true); + if (this.eatContextual("as")) { + node$2.local = this.parseIdent(); + } else { + this.checkUnreserved(node$2.imported); + node$2.local = node$2.imported; + } + this.checkLValSimple(node$2.local, BIND_LEXICAL); + nodes.push(this.finishNode(node$2, "ImportSpecifier")); + } + return nodes +}; + +// Set `ExpressionStatement#directive` property for directive prologues. +pp$1.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } +}; +pp$1.isDirectiveCandidate = function(statement) { + return ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + typeof statement.expression.value === "string" && + // Reject parenthesized strings. + (this.input[statement.start] === "\"" || this.input[statement.start] === "'") + ) +}; + +var pp$2 = Parser.prototype; + +// Convert existing expression atom to assignable pattern +// if possible. + +pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } + break + + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break + + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.toAssignable(prop, isBinding); + // Early error: + // AssignmentRestProperty[Yield, Await] : + // `...` DestructuringAssignmentTarget[Yield, Await] + // + // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. + if ( + prop.type === "RestElement" && + (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") + ) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break + + case "Property": + // AssignmentProperty has type === "Property" + if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } + this.toAssignable(node.value, isBinding); + break + + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break + + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") + { this.raise(node.argument.start, "Rest elements cannot have a default value"); } + break + + case "AssignmentExpression": + if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break + + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (!isBinding) { break } + + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + return node +}; + +// Convert list of expression atoms to binding list. + +pp$2.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { this.toAssignable(elt, isBinding); } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + { this.unexpected(last.argument.start); } + } + return exprList +}; + +// Parses spread element. + +pp$2.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") +}; + +pp$2.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types.name) + { this.unexpected(); } + + node.argument = this.parseBindingAtom(); + + return this.finishNode(node, "RestElement") +}; + +// Parses lvalue (assignable) atom. + +pp$2.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types.bracketR, true, true); + return this.finishNode(node, "ArrayPattern") + + case types.braceL: + return this.parseObj(true) + } + } + return this.parseIdent() +}; + +pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { first = false; } + else { this.expect(types.comma); } + if (allowEmpty && this.type === types.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close)) { + break + } else if (this.type === types.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } + this.expect(close); + break + } else { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + elts.push(elem); + } + } + return elts +}; + +pp$2.parseBindingListItem = function(param) { + return param +}; + +// Parses assignment pattern around given atom if possible. + +pp$2.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern") +}; + +// The following three functions all verify that a node is an lvalue — +// something that can be bound, or assigned to. In order to do so, they perform +// a variety of checks: +// +// - Check that none of the bound/assigned-to identifiers are reserved words. +// - Record name declarations for bindings in the appropriate scope. +// - Check duplicate argument names, if checkClashes is set. +// +// If a complex binding pattern is encountered (e.g., object and array +// destructuring), the entire pattern is recursively checked. +// +// There are three versions of checkLVal*() appropriate for different +// circumstances: +// +// - checkLValSimple() shall be used if the syntactic construct supports +// nothing other than identifiers and member expressions. Parenthesized +// expressions are also correctly handled. This is generally appropriate for +// constructs for which the spec says +// +// > It is a Syntax Error if AssignmentTargetType of [the production] is not +// > simple. +// +// It is also appropriate for checking if an identifier is valid and not +// defined elsewhere, like import declarations or function/class identifiers. +// +// Examples where this is used include: +// a += …; +// import a from '…'; +// where a is the node to be checked. +// +// - checkLValPattern() shall be used if the syntactic construct supports +// anything checkLValSimple() supports, as well as object and array +// destructuring patterns. This is generally appropriate for constructs for +// which the spec says +// +// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor +// > an ArrayLiteral and AssignmentTargetType of [the production] is not +// > simple. +// +// Examples where this is used include: +// (a = …); +// const a = …; +// try { … } catch (a) { … } +// where a is the node to be checked. +// +// - checkLValInnerPattern() shall be used if the syntactic construct supports +// anything checkLValPattern() supports, as well as default assignment +// patterns, rest elements, and other constructs that may appear within an +// object or array destructuring pattern. +// +// As a special case, function parameters also use checkLValInnerPattern(), +// as they also support defaults and rest constructs. +// +// These functions deliberately support both assignment and binding constructs, +// as the logic for both is exceedingly similar. If the node is the target of +// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it +// should be set to the appropriate BIND_* constant, like BIND_VAR or +// BIND_LEXICAL. +// +// If the function is called with a non-BIND_NONE bindingType, then +// additionally a checkClashes object may be specified to allow checking for +// duplicate argument names. checkClashes is ignored if the provided construct +// is an assignment (i.e., bindingType is BIND_NONE). + +pp$2.checkLValSimple = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + var isBind = bindingType !== BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (checkClashes) { + if (has$1(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + } + break + + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ParenthesizedExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } + return this.checkLValSimple(expr.expression, bindingType, checkClashes) + + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } +}; + +pp$2.checkLValPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break + + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + + if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } + } + break + + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } +}; + +pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "Property": + // AssignmentProperty has type === "Property" + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break + + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break + + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break + + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } +}; + +// A recursive descent parser operates by defining functions for all + +var pp$3 = Parser.prototype; + +// Check if property name clashes with already added. +// Object/class getters and setters are not allowed to clash — +// either with each other or with an init property — and in +// strict mode, init properties are also not allowed to be repeated. + +pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") + { return } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + { return } + var key = prop.key; + var name; + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) + { refDestructuringErrors.doubleProto = key.start; } + // Backwards-compat kludge. Can be removed in version 6.0 + } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } + } + propHash.proto = true; + } + return + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) + { this.raiseRecoverable(key.start, "Redefinition of property"); } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; +}; + +// ### Expression parsing + +// These nest, from the most general expression type at the top to +// 'atomic', nondivisible expression types at the bottom. Most of +// the functions will simply let the function(s) below them parse, +// and, *if* the syntactic construct they handle is present, wrap +// the AST node that the inner parser gave them in another node. + +// Parse a full expression. The optional arguments are used to +// forbid the `in` operator (in for loops initalization expressions) +// and provide reference for storing '=' operator inside shorthand +// property assignment in contexts where both object expression +// and object pattern might appear (so it's possible to raise +// delayed syntax error at correct position). + +pp$3.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr +}; + +// Parse an assignment expression. This includes applications of +// operators like `+=`. + +pp$3.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(forInit) } + // The tokenizer will assume an expression is allowed after + // `yield`, but this isn't that kind of yield + else { this.exprAllowed = false; } + } + + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } + + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types.parenL || this.type === types.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types.eq) + { left = this.toAssignable(left, false, refDestructuringErrors); } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) + { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly + if (this.type === types.eq) + { this.checkLValPattern(left); } + else + { this.checkLValSimple(left); } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + return left +}; + +// Parse a ternary conditional (`?:`) operator. + +pp$3.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + if (this.eat(types.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression") + } + return expr +}; + +// Start the precedence parser. + +pp$3.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) +}; + +// Parse binary operators with the operator precedence parsing +// algorithm. `left` is the left-hand side of the operator. +// `minPrec` provides context that allows the function to stop and +// defer further parser to one of its callers when it encounters an +// operator that has a lower precedence than the set it is parsing. + +pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types._in)) { + if (prec > minPrec) { + var logical = this.type === types.logicalOR || this.type === types.logicalAND; + var coalesce = this.type === types.coalesce; + if (coalesce) { + // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. + // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. + prec = types.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) + } + } + return left +}; + +pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") +}; + +// Parse unary operators, both prefix and postfix. + +pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLValSimple(node.argument); } + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) + { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else { + expr = this.parseExprSubscripts(refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + + if (!incDec && this.eat(types.starstar)) { + if (sawUnary) + { this.unexpected(this.lastTokStart); } + else + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } + } else { + return expr + } +}; + +function isPrivateFieldAccess(node) { + return ( + node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || + node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) + ) +} + +// Parse call, dot, and `[]`-subscript expressions. + +pp$3.parseExprSubscripts = function(refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") + { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } + } + return result +}; + +pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && + this.potentialArrowAt === base.start; + var optionalChained = false; + + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained); + + if (element.optional) { optionalChained = true; } + if (element === base || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); + } + return element + } + + base = element; + } +}; + +pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types.questionDot); + if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } + + var computed = this.eat(types.bracketL); + if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(types.bracketR); + } else if (this.type === types.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) + { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true) + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this.parseTemplate({isTagged: true}); + base = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base +}; + +// Parse an atomic expression — either a single token that is an +// expression, an expression started by a keyword like `function` or +// `new`, or an expression wrapped in punctuation like `()`, `[]`, +// or `{}`. + +pp$3.parseExprAtom = function(refDestructuringErrors) { + // If a division operator appears in an expression position, the + // tokenizer got confused, and we force it to read a regexp instead. + if (this.type === types.slash) { this.readRegexp(); } + + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types._super: + if (!this.allowSuper) + { this.raise(this.start, "'super' keyword outside a method"); } + node = this.startNode(); + this.next(); + if (this.type === types.parenL && !this.allowDirectSuper) + { this.raise(node.start, "super() call outside constructor of a subclass"); } + // The `super` keyword can appear at below: + // SuperProperty: + // super [ Expression ] + // super . IdentifierName + // SuperCall: + // super ( Arguments ) + if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) + { this.unexpected(); } + return this.finishNode(node, "Super") + + case types._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") + + case types.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) + { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc && + (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) + } + } + return id + + case types.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node + + case types.num: case types.string: + return this.parseLiteral(this.value) + + case types._null: case types._true: case types._false: + node = this.startNode(); + node.value = this.type === types._null ? null : this.type === types._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal") + + case types.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) + { refDestructuringErrors.parenthesizedAssign = start; } + if (refDestructuringErrors.parenthesizedBind < 0) + { refDestructuringErrors.parenthesizedBind = start; } + } + return expr + + case types.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") + + case types.braceL: + return this.parseObj(false, refDestructuringErrors) + + case types._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) + + case types._class: + return this.parseClass(this.startNode(), false) + + case types._new: + return this.parseNew() + + case types.backQuote: + return this.parseTemplate() + + case types._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport() + } else { + return this.unexpected() + } + + default: + this.unexpected(); + } +}; + +pp$3.parseExprImport = function() { + var node = this.startNode(); + + // Consume `import` as an identifier for `import.meta`. + // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } + var meta = this.parseIdent(true); + + switch (this.type) { + case types.parenL: + return this.parseDynamicImport(node) + case types.dot: + node.meta = meta; + return this.parseImportMeta(node) + default: + this.unexpected(); + } +}; + +pp$3.parseDynamicImport = function(node) { + this.next(); // skip `(` + + // Parse node.source. + node.source = this.parseMaybeAssign(); + + // Verify ending. + if (!this.eat(types.parenR)) { + var errorPos = this.start; + if (this.eat(types.comma) && this.eat(types.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + + return this.finishNode(node, "ImportExpression") +}; + +pp$3.parseImportMeta = function(node) { + this.next(); // skip `.` + + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + + if (node.property.name !== "meta") + { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) + { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } + + return this.finishNode(node, "MetaProperty") +}; + +pp$3.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } + this.next(); + return this.finishNode(node, "Literal") +}; + +pp$3.parseParenExpression = function() { + this.expect(types.parenL); + var val = this.parseExpression(); + this.expect(types.parenR); + return val +}; + +pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + // Do not save awaitIdentPos to allow checking awaits nested in parameters + while (this.type !== types.parenR) { + first ? first = false : this.expect(types.comma); + if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) { + lastIsComma = true; + break + } else if (this.type === types.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } + break + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.start, innerEndLoc = this.startLoc; + this.expect(types.parenR); + + if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList) + } + + if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } + if (spreadStart) { this.unexpected(spreadStart); } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val + } +}; + +pp$3.parseParenItem = function(item) { + return item +}; + +pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) +}; + +// New's precedence is slightly tricky. It must allow its argument to +// be a `[]` or dot subscript expression, but not a call — at least, +// not without wrapping it in parentheses. Thus, it uses the noCalls +// argument to parseSubscripts to prevent it from consuming the +// argument list. + +var empty$1 = []; + +pp$3.parseNew = function() { + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } + var node = this.startNode(); + var meta = this.parseIdent(true); + if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { + node.meta = meta; + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } + if (!this.inNonArrowFunction) + { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import; + node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); + if (isImport && node.callee.type === "ImportExpression") { + this.raise(startPos, "Cannot use new with import()"); + } + if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } + else { node.arguments = empty$1; } + return this.finishNode(node, "NewExpression") +}; + +// Parse template expression. + +pp$3.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; + + var elem = this.startNode(); + if (this.type === types.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value, + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types.backQuote; + return this.finishNode(elem, "TemplateElement") +}; + +pp$3.parseTemplate = function(ref) { + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({isTagged: isTagged}); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); } + this.expect(types.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types.braceR); + node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); + } + this.next(); + return this.finishNode(node, "TemplateLiteral") +}; + +pp$3.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && + (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && + !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) +}; + +// Parse an object literal or binding pattern. + +pp$3.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types.braceR)) { + if (!first) { + this.expect(types.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") +}; + +pp$3.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types.comma) { + this.raise(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement") + } + // To disallow parenthesized identifier via `this.toAssignable()`. + if (this.type === types.parenL && refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0) { + refDestructuringErrors.parenthesizedAssign = this.start; + } + if (refDestructuringErrors.parenthesizedBind < 0) { + refDestructuringErrors.parenthesizedBind = this.start; + } + } + // Parse argument. + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + // To disallow trailing comma via `this.toAssignable()`. + if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + // Finish + return this.finishNode(prop, "SpreadElement") + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) + { isGenerator = this.eat(types.star); } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); + this.parsePropertyName(prop, refDestructuringErrors); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property") +}; + +pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types.colon) + { this.unexpected(); } + + if (this.eat(types.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { + if (isPattern) { this.unexpected(); } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && + this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) { + if (isGenerator || isAsync) { this.unexpected(); } + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") + { this.raiseRecoverable(start, "getter should have no params"); } + else + { this.raiseRecoverable(start, "setter should have exactly one param"); } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } + } + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { this.unexpected(); } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = startPos; } + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.shorthand = true; + } else { this.unexpected(); } +}; + +pp$3.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types.bracketR); + return prop.key + } else { + prop.computed = false; + } + } + return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") +}; + +// Initialize empty function node. + +pp$3.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } + if (this.options.ecmaVersion >= 8) { node.async = false; } +}; + +// Parse object or class method. + +pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.initFunction(node); + if (this.options.ecmaVersion >= 6) + { node.generator = isGenerator; } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") +}; + +// Parse arrow function expression with given parameters. + +pp$3.parseArrowExpression = function(node, params, isAsync) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") +}; + +// Parse function body and check parameters. + +pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { + var isExpression = isArrowFunction && this.type !== types.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (useStrict && nonSimple) + { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } + } + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { this.strict = true; } + + // Add the params to varDeclaredNames to ensure that an error is thrown + // if a let/const declaration in the function clashes with one of the params. + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } + node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); +}; + +pp$3.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; + + if (param.type !== "Identifier") { return false + } } + return true +}; + +// Checks function params for various disallowed patterns such as using "eval" +// or "arguments" and duplicate parameters. + +pp$3.checkParams = function(node, allowDuplicates) { + var nameHash = Object.create(null); + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } +}; + +// Parses a comma-separated list of expressions, and returns them as +// an array. `close` is the token type that ends the list, and +// `allowEmpty` can be turned on to allow subsequent commas with +// nothing in between them to be parsed as `null` (which is needed +// for array literals). + +pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this.expect(types.comma); + if (allowTrailingComma && this.afterTrailingComma(close)) { break } + } else { first = false; } + + var elt = (void 0); + if (allowEmpty && this.type === types.comma) + { elt = null; } + else if (this.type === types.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0) + { refDestructuringErrors.trailingComma = this.start; } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts +}; + +pp$3.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; + + if (this.inGenerator && name === "yield") + { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } + if (this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } + if (this.currentThisScope().inClassFieldInit && name === "arguments") + { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } + if (this.keywords.test(name)) + { this.raise(start, ("Unexpected keyword '" + name + "'")); } + if (this.options.ecmaVersion < 6 && + this.input.slice(start, end).indexOf("\\") !== -1) { return } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } + this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); + } +}; + +// Parse the next token as an identifier. If `liberal` is true (used +// when parsing properties), it will also convert keywords into +// identifiers. + +pp$3.parseIdent = function(liberal, isBinding) { + var node = this.startNode(); + if (this.type === types.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + + // To fix https://github.com/acornjs/acorn/issues/575 + // `class` and `function` keywords push new context into this.context. + // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. + // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword + if ((node.name === "class" || node.name === "function") && + (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + } else { + this.unexpected(); + } + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node +}; + +pp$3.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types.privateId) { + node.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "PrivateIdentifier"); + + // For validating existence + if (this.privateNameStack.length === 0) { + this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); + } + + return node +}; + +// Parses yield expression inside generator. + +pp$3.parseYield = function(forInit) { + if (!this.yieldPos) { this.yieldPos = this.start; } + + var node = this.startNode(); + this.next(); + if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression") +}; + +pp$3.parseAwait = function() { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + return this.finishNode(node, "AwaitExpression") +}; + +var pp$4 = Parser.prototype; + +// This function is used to raise exceptions on parse errors. It +// takes an offset integer (into the current `input`) to indicate +// the location of the error, attaches the position to the end +// of the error message, and then raises a `SyntaxError` with that +// message. + +pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; err.loc = loc; err.raisedAt = this.pos; + throw err +}; + +pp$4.raiseRecoverable = pp$4.raise; + +pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } +}; + +var pp$5 = Parser.prototype; + +var Scope = function Scope(flags) { + this.flags = flags; + // A list of var-declared names in the current lexical scope + this.var = []; + // A list of lexically-declared names in the current lexical scope + this.lexical = []; + // A list of lexically-declared FunctionDeclaration names in the current lexical scope + this.functions = []; + // A switch to disallow the identifier reference 'arguments' + this.inClassFieldInit = false; +}; + +// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + +pp$5.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); +}; + +pp$5.exitScope = function() { + this.scopeStack.pop(); +}; + +// The spec says: +// > At the top level of a function, or script, function declarations are +// > treated like var declarations rather than like lexical declarations. +pp$5.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) +}; + +pp$5.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && (scope.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) + { redeclared = scope$2.lexical.indexOf(name) > -1; } + else + { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } + scope$2.functions.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || + !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break + } + scope$3.var.push(name); + if (this.inModule && (scope$3.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + if (scope$3.flags & SCOPE_VAR) { break } + } + } + if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } +}; + +pp$5.checkLocalExport = function(id) { + // scope.functions must be empty as Module code is always strict. + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && + this.scopeStack[0].var.indexOf(id.name) === -1) { + this.undefinedExports[id.name] = id; + } +}; + +pp$5.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] +}; + +pp$5.currentVarScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { return scope } + } +}; + +// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. +pp$5.currentThisScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } + } +}; + +var Node = function Node(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) + { this.loc = new SourceLocation(parser, loc); } + if (parser.options.directSourceFile) + { this.sourceFile = parser.options.directSourceFile; } + if (parser.options.ranges) + { this.range = [pos, 0]; } +}; + +// Start an AST node, attaching a start offset. + +var pp$6 = Parser.prototype; + +pp$6.startNode = function() { + return new Node(this, this.start, this.startLoc) +}; + +pp$6.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) +}; + +// Finish an AST node, adding `type` and `end` properties. + +function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) + { node.loc.end = loc; } + if (this.options.ranges) + { node.range[1] = pos; } + return node +} + +pp$6.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) +}; + +// Finish node at given position + +pp$6.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) +}; + +pp$6.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { newNode[prop] = node[prop]; } + return newNode +}; + +// The algorithm used to determine whether a regexp can appear at a + +var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; +}; + +var types$1 = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) +}; + +var pp$7 = Parser.prototype; + +pp$7.initialContext = function() { + return [types$1.b_stat] +}; + +pp$7.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types$1.f_expr || parent === types$1.f_stat) + { return true } + if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) + { return !parent.isExpr } + + // The check for `tt.name && exprAllowed` detects whether we are + // after a `yield` or `of` construct. See the `updateContext` for + // `tt.name`. + if (prevType === types._return || prevType === types.name && this.exprAllowed) + { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } + if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) + { return true } + if (prevType === types.braceL) + { return parent === types$1.b_stat } + if (prevType === types._var || prevType === types._const || prevType === types.name) + { return false } + return !this.exprAllowed +}; + +pp$7.inGeneratorContext = function() { + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this.context[i]; + if (context.token === "function") + { return context.generator } + } + return false +}; + +pp$7.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types.dot) + { this.exprAllowed = false; } + else if (update = type.updateContext) + { update.call(this, prevType); } + else + { this.exprAllowed = type.beforeExpr; } +}; + +// Token-specific context update code + +types.parenR.updateContext = types.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return + } + var out = this.context.pop(); + if (out === types$1.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; +}; + +types.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); + this.exprAllowed = true; +}; + +types.dollarBraceL.updateContext = function() { + this.context.push(types$1.b_tmpl); + this.exprAllowed = true; +}; + +types.parenL.updateContext = function(prevType) { + var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; + this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); + this.exprAllowed = true; +}; + +types.incDec.updateContext = function() { + // tokExprAllowed stays unchanged +}; + +types._function.updateContext = types._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types._else && + !(prevType === types.semi && this.curContext() !== types$1.p_stat) && + !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && + !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) + { this.context.push(types$1.f_expr); } + else + { this.context.push(types$1.f_stat); } + this.exprAllowed = false; +}; + +types.backQuote.updateContext = function() { + if (this.curContext() === types$1.q_tmpl) + { this.context.pop(); } + else + { this.context.push(types$1.q_tmpl); } + this.exprAllowed = false; +}; + +types.star.updateContext = function(prevType) { + if (prevType === types._function) { + var index = this.context.length - 1; + if (this.context[index] === types$1.f_expr) + { this.context[index] = types$1.f_expr_gen; } + else + { this.context[index] = types$1.f_gen; } + } + this.exprAllowed = true; +}; + +types.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { + if (this.value === "of" && !this.exprAllowed || + this.value === "yield" && this.inGeneratorContext()) + { allowed = true; } + } + this.exprAllowed = allowed; +}; + +// This file contains Unicode properties extracted from the ECMAScript +// specification. The lists are extracted like so: +// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) + +// #table-binary-unicode-properties +var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; +var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; +var ecma11BinaryProperties = ecma10BinaryProperties; +var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; +var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties +}; + +// #table-unicode-general-category-values +var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; + +// #table-unicode-script-values +var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; +var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; +var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; +var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; +var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues +}; + +var data = {}; +function buildUnicodeData(ecmaVersion) { + var d = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; + + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; +} +buildUnicodeData(9); +buildUnicodeData(10); +buildUnicodeData(11); +buildUnicodeData(12); + +var pp$8 = Parser.prototype; + +var RegExpValidationState = function RegExpValidationState(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = []; + this.backReferenceNames = []; +}; + +RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; +}; + +RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); +}; + +// If u flag is given, this returns the code point at the index (it combines a surrogate pair). +// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). +RegExpValidationState.prototype.at = function at (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return c + } + var next = s.charCodeAt(i + 1); + return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c +}; + +RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || + (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { + return i + 1 + } + return i + 2 +}; + +RegExpValidationState.prototype.current = function current (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.pos, forceU) +}; + +RegExpValidationState.prototype.lookahead = function lookahead (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.nextIndex(this.pos, forceU), forceU) +}; + +RegExpValidationState.prototype.advance = function advance (forceU) { + if ( forceU === void 0 ) forceU = false; + + this.pos = this.nextIndex(this.pos, forceU); +}; + +RegExpValidationState.prototype.eat = function eat (ch, forceU) { + if ( forceU === void 0 ) forceU = false; + + if (this.current(forceU) === ch) { + this.advance(forceU); + return true + } + return false +}; + +function codePointToString(ch) { + if (ch <= 0xFFFF) { return String.fromCharCode(ch) } + ch -= 0x10000; + return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) +} + +/** + * Validate the flags part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ +pp$8.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } + } +}; + +/** + * Validate the pattern part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ +pp$8.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + + // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of + // parsing contains a |GroupName|, reparse with the goal symbol + // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* + // exception if _P_ did not conform to the grammar, if any elements of _P_ + // were not matched by the parse, or if any Early Error conditions exist. + if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { + state.switchN = true; + this.regexp_pattern(state); + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern +pp$8.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames.length = 0; + state.backReferenceNames.length = 0; + + this.regexp_disjunction(state); + + if (state.pos !== state.source.length) { + // Make the same messages as V8. + if (state.eat(0x29 /* ) */)) { + state.raise("Unmatched ')'"); + } + if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; + + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction +pp$8.regexp_disjunction = function(state) { + this.regexp_alternative(state); + while (state.eat(0x7C /* | */)) { + this.regexp_alternative(state); + } + + // Make the same message as V8. + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(0x7B /* { */)) { + state.raise("Lone quantifier brackets"); + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative +pp$8.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) + { } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term +pp$8.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + // Handle `QuantifiableAssertion Quantifier` alternative. + // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion + // is a QuantifiableAssertion. + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + // Make the same message as V8. + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true + } + + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } + + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion +pp$8.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } + + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } + + // Lookahead / Lookbehind + if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(0x3C /* < */); + } + if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { + this.regexp_disjunction(state); + if (!state.eat(0x29 /* ) */)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true + } + } + + state.pos = start; + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier +pp$8.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; + + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix +pp$8.regexp_eatQuantifierPrefix = function(state, noError) { + return ( + state.eat(0x2A /* * */) || + state.eat(0x2B /* + */) || + state.eat(0x3F /* ? */) || + this.regexp_eatBracedQuantifier(state, noError) + ) +}; +pp$8.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(0x7B /* { */)) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat(0x7D /* } */)) { + // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom +pp$8.regexp_eatAtom = function(state) { + return ( + this.regexp_eatPatternCharacters(state) || + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) + ) +}; +pp$8.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatAtomEscape(state)) { + return true + } + state.pos = start; + } + return false +}; +pp$8.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(0x28 /* ( */)) { + if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + return true + } + state.raise("Unterminated group"); + } + state.pos = start; + } + return false +}; +pp$8.regexp_eatCapturingGroup = function(state) { + if (state.eat(0x28 /* ( */)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 0x3F /* ? */) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + state.numCapturingParens += 1; + return true + } + state.raise("Unterminated group"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom +pp$8.regexp_eatExtendedAtom = function(state) { + return ( + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) || + this.regexp_eatInvalidBracedQuantifier(state) || + this.regexp_eatExtendedPatternCharacter(state) + ) +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier +pp$8.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter +pp$8.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false +}; +function isSyntaxCharacter(ch) { + return ( + ch === 0x24 /* $ */ || + ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || + ch === 0x2E /* . */ || + ch === 0x3F /* ? */ || + ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter +// But eat eager. +pp$8.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter +pp$8.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if ( + ch !== -1 && + ch !== 0x24 /* $ */ && + !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && + ch !== 0x2E /* . */ && + ch !== 0x3F /* ? */ && + ch !== 0x5B /* [ */ && + ch !== 0x5E /* ^ */ && + ch !== 0x7C /* | */ + ) { + state.advance(); + return true + } + return false +}; + +// GroupSpecifier :: +// [empty] +// `?` GroupName +pp$8.regexp_groupSpecifier = function(state) { + if (state.eat(0x3F /* ? */)) { + if (this.regexp_eatGroupName(state)) { + if (state.groupNames.indexOf(state.lastStringValue) !== -1) { + state.raise("Duplicate capture group name"); + } + state.groupNames.push(state.lastStringValue); + return + } + state.raise("Invalid group"); + } +}; + +// GroupName :: +// `<` RegExpIdentifierName `>` +// Note: this updates `state.lastStringValue` property with the eaten name. +pp$8.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(0x3C /* < */)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { + return true + } + state.raise("Invalid capture group name"); + } + return false +}; + +// RegExpIdentifierName :: +// RegExpIdentifierStart +// RegExpIdentifierName RegExpIdentifierPart +// Note: this updates `state.lastStringValue` property with the eaten name. +pp$8.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true + } + return false +}; + +// RegExpIdentifierStart :: +// UnicodeIDStart +// `$` +// `_` +// `\` RegExpUnicodeEscapeSequence[+U] +pp$8.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false +}; +function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ +} + +// RegExpIdentifierPart :: +// UnicodeIDContinue +// `$` +// `_` +// `\` RegExpUnicodeEscapeSequence[+U] +// +// +pp$8.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false +}; +function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape +pp$8.regexp_eatAtomEscape = function(state) { + if ( + this.regexp_eatBackReference(state) || + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) || + (state.switchN && this.regexp_eatKGroupName(state)) + ) { + return true + } + if (state.switchU) { + // Make the same message as V8. + if (state.current() === 0x63 /* c */) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false +}; +pp$8.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape + if (n > state.maxBackReference) { + state.maxBackReference = n; + } + return true + } + if (n <= state.numCapturingParens) { + return true + } + state.pos = start; + } + return false +}; +pp$8.regexp_eatKGroupName = function(state) { + if (state.eat(0x6B /* k */)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true + } + state.raise("Invalid named reference"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape +pp$8.regexp_eatCharacterEscape = function(state) { + return ( + this.regexp_eatControlEscape(state) || + this.regexp_eatCControlLetter(state) || + this.regexp_eatZero(state) || + this.regexp_eatHexEscapeSequence(state) || + this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || + (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || + this.regexp_eatIdentityEscape(state) + ) +}; +pp$8.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(0x63 /* c */)) { + if (this.regexp_eatControlLetter(state)) { + return true + } + state.pos = start; + } + return false +}; +pp$8.regexp_eatZero = function(state) { + if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape +pp$8.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 0x74 /* t */) { + state.lastIntValue = 0x09; /* \t */ + state.advance(); + return true + } + if (ch === 0x6E /* n */) { + state.lastIntValue = 0x0A; /* \n */ + state.advance(); + return true + } + if (ch === 0x76 /* v */) { + state.lastIntValue = 0x0B; /* \v */ + state.advance(); + return true + } + if (ch === 0x66 /* f */) { + state.lastIntValue = 0x0C; /* \f */ + state.advance(); + return true + } + if (ch === 0x72 /* r */) { + state.lastIntValue = 0x0D; /* \r */ + state.advance(); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter +pp$8.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false +}; +function isControlLetter(ch) { + return ( + (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || + (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) + ) +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence +pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if ( forceU === void 0 ) forceU = false; + + var start = state.pos; + var switchU = forceU || state.switchU; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { + var leadSurrogateEnd = state.pos; + if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 0xDC00 && trail <= 0xDFFF) { + state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + return true + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true + } + if ( + switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + + return false +}; +function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape +pp$8.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true + } + if (state.eat(0x2F /* / */)) { + state.lastIntValue = 0x2F; /* / */ + return true + } + return false + } + + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape +pp$8.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape +pp$8.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return true + } + + if ( + state.switchU && + this.options.ecmaVersion >= 9 && + (ch === 0x50 /* P */ || ch === 0x70 /* p */) + ) { + state.lastIntValue = -1; + state.advance(); + if ( + state.eat(0x7B /* { */) && + this.regexp_eatUnicodePropertyValueExpression(state) && + state.eat(0x7D /* } */) + ) { + return true + } + state.raise("Invalid property name"); + } + + return false +}; +function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) +} + +// UnicodePropertyValueExpression :: +// UnicodePropertyName `=` UnicodePropertyValue +// LoneUnicodePropertyNameOrValue +pp$8.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + + // UnicodePropertyName `=` UnicodePropertyValue + if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return true + } + } + state.pos = start; + + // LoneUnicodePropertyNameOrValue + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); + return true + } + return false +}; +pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!has$1(state.unicodeProperties.nonBinary, name)) + { state.raise("Invalid property name"); } + if (!state.unicodeProperties.nonBinary[name].test(value)) + { state.raise("Invalid property value"); } +}; +pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (!state.unicodeProperties.binary.test(nameOrValue)) + { state.raise("Invalid property name"); } +}; + +// UnicodePropertyName :: +// UnicodePropertyNameCharacters +pp$8.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" +}; +function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 0x5F /* _ */ +} + +// UnicodePropertyValue :: +// UnicodePropertyValueCharacters +pp$8.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" +}; +function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) +} + +// LoneUnicodePropertyNameOrValue :: +// UnicodePropertyValueCharacters +pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass +pp$8.regexp_eatCharacterClass = function(state) { + if (state.eat(0x5B /* [ */)) { + state.eat(0x5E /* ^ */); + this.regexp_classRanges(state); + if (state.eat(0x5D /* ] */)) { + return true + } + // Unreachable since it threw "unterminated regular expression" error before. + state.raise("Unterminated character class"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges +// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges +// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash +pp$8.regexp_classRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom +// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash +pp$8.regexp_eatClassAtom = function(state) { + var start = state.pos; + + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatClassEscape(state)) { + return true + } + if (state.switchU) { + // Make the same message as V8. + var ch$1 = state.current(); + if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + + var ch = state.current(); + if (ch !== 0x5D /* ] */) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape +pp$8.regexp_eatClassEscape = function(state) { + var start = state.pos; + + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true + } + + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; + } + + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter +pp$8.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence +pp$8.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(0x78 /* x */)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits +pp$8.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } + return state.pos !== start +}; +function isDecimalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits +pp$8.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start +}; +function isHexDigit(ch) { + return ( + (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || + (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || + (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) + ) +} +function hexToInt(ch) { + if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { + return 10 + (ch - 0x41 /* A */) + } + if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { + return 10 + (ch - 0x61 /* a */) + } + return ch - 0x30 /* 0 */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence +// Allows only 0-377(octal) i.e. 0-255(decimal). +pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit +pp$8.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 0x30; /* 0 */ + state.advance(); + return true + } + state.lastIntValue = 0; + return false +}; +function isOctalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits +// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit +// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence +pp$8.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true +}; + +// Object type used to represent tokens. Note that normally, tokens +// simply exist as properties on the parser object. This is only +// used for the onToken callback and the external tokenizer. + +var Token = function Token(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) + { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } + if (p.options.ranges) + { this.range = [p.start, p.end]; } +}; + +// ## Tokenizer + +var pp$9 = Parser.prototype; + +// Move to the next token + +pp$9.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) + { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } + if (this.options.onToken) + { this.options.onToken(new Token(this)); } + + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); +}; + +pp$9.getToken = function() { + this.next(); + return new Token(this) +}; + +// If we're in an ES6 environment, make parsers iterable +if (typeof Symbol !== "undefined") + { pp$9[Symbol.iterator] = function() { + var this$1$1 = this; + + return { + next: function () { + var token = this$1$1.getToken(); + return { + done: token.type === types.eof, + value: token + } + } + } + }; } + +// Toggle strict mode. Re-reads the next number or string to please +// pedantic tests (`"use strict"; 010;` should fail). + +pp$9.curContext = function() { + return this.context[this.context.length - 1] +}; + +// Read a single token, updating the parser object's token-related +// properties. + +pp$9.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } + + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types.eof) } + + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } +}; + +pp$9.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + { return this.readWord() } + + return this.getTokenFromCode(code) +}; + +pp$9.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 0xd7ff || code >= 0xdc00) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 +}; + +pp$9.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } + this.pos = end + 2; + if (this.options.locations) { + lineBreakG.lastIndex = start; + var match; + while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { + ++this.curLine; + this.lineStart = match.index + match[0].length; + } + } + if (this.options.onComment) + { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()); } +}; + +pp$9.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) + { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()); } +}; + +// Called at the start of the parse and after every token. Skips +// whitespace and comments, and. + +pp$9.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: case 160: // ' ' + ++this.pos; + break + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: case 8232: case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break + case 47: // '/' + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: // '*' + this.skipBlockComment(); + break + case 47: + this.skipLineComment(2); + break + default: + break loop + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop + } + } + } +}; + +// Called at the end of every token. Sets `end`, `val`, and +// maintains `context` and `exprAllowed`, and skips the space after +// the token, so that the next one's `start` will point at the +// right position. + +pp$9.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { this.endLoc = this.curPosition(); } + var prevType = this.type; + this.type = type; + this.value = val; + + this.updateContext(prevType); +}; + +// ### Token reading + +// This is the function that is called to fetch the next token. It +// is somewhat obscure, because it works in character codes rather +// than characters, and because operator parsing has been inlined +// into it. +// +// All in the name of speed. +// +pp$9.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { return this.readNumber(true) } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' + this.pos += 3; + return this.finishToken(types.ellipsis) + } else { + ++this.pos; + return this.finishToken(types.dot) + } +}; + +pp$9.readToken_slash = function() { // '/' + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { ++this.pos; return this.readRegexp() } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.slash, 1) +}; + +pp$9.readToken_mult_modulo_exp = function(code) { // '%*' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types.star : types.modulo; + + // exponentiation operator ** and **= + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + + if (next === 61) { return this.finishOp(types.assign, size + 1) } + return this.finishOp(tokentype, size) +}; + +pp$9.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { return this.finishOp(types.assign, 3) } + } + return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) + } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) +}; + +pp$9.readToken_caret = function() { // '^' + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.bitwiseXOR, 1) +}; + +pp$9.readToken_plus_min = function(code) { // '+-' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && + (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types.incDec, 2) + } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.plusMin, 1) +}; + +pp$9.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } + return this.finishOp(types.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `/; +const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im; +const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im; +const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im; +function esbuildScanPlugin(config, container, depImports, missing, entries) { + var _a, _b; + const seen = new Map(); + const resolve = async (id, importer) => { + const key = id + (importer && path__default.dirname(importer)); + if (seen.has(key)) { + return seen.get(key); + } + const resolved = await container.resolveId(id, importer && normalizePath$4(importer)); + const res = resolved === null || resolved === void 0 ? void 0 : resolved.id; + seen.set(key, res); + return res; + }; + const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include; + const exclude = [ + ...(((_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude) || []), + '@vite/client', + '@vite/env' + ]; + const externalUnlessEntry = ({ path }) => ({ + path, + external: !entries.includes(path) + }); + return { + name: 'vite:dep-scan', + setup(build) { + // external urls + build.onResolve({ filter: externalRE }, ({ path }) => ({ + path, + external: true + })); + // data urls + build.onResolve({ filter: dataUrlRE }, ({ path }) => ({ + path, + external: true + })); + // html types: extract script contents ----------------------------------- + build.onResolve({ filter: htmlTypesRE }, async ({ path, importer }) => { + return { + path: await resolve(path, importer), + namespace: 'html' + }; + }); + // extract scripts inside HTML-like files and treat it as a js module + build.onLoad({ filter: htmlTypesRE, namespace: 'html' }, async ({ path }) => { + let raw = fs__default.readFileSync(path, 'utf-8'); + // Avoid matching the content of the comment + raw = raw.replace(commentRE, ''); + const isHtml = path.endsWith('.html'); + const regex = isHtml ? scriptModuleRE : scriptRE; + regex.lastIndex = 0; + let js = ''; + let loader = 'js'; + let match; + while ((match = regex.exec(raw))) { + const [, openTag, content] = match; + const srcMatch = openTag.match(srcRE); + const typeMatch = openTag.match(typeRE); + const langMatch = openTag.match(langRE); + const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]); + const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]); + // skip type="application/ld+json" and other non-JS types + if (type && + !(type.includes('javascript') || + type.includes('ecmascript') || + type === 'module')) { + continue; + } + if (lang === 'ts' || lang === 'tsx' || lang === 'jsx') { + loader = lang; + } + if (srcMatch) { + const src = srcMatch[1] || srcMatch[2] || srcMatch[3]; + js += `import ${JSON.stringify(src)}\n`; + } + else if (content.trim()) { + js += content + '\n'; + } + } + // empty singleline & multiline comments to avoid matching comments + const code = js + .replace(multilineCommentsRE, '/* */') + .replace(singlelineCommentsRE, ''); + if (loader.startsWith('ts') && + (path.endsWith('.svelte') || + (path.endsWith('.vue') && /) or Svelte, imports may seem + // unused to esbuild and dropped in the build output, which prevents + // esbuild from crawling further. + // the solution is to add `import 'x'` for every source to force + // esbuild to keep crawling due to potential side effects. + let m; + while ((m = importsRE.exec(code)) != null) { + // This is necessary to avoid infinite loops with zero-width matches + if (m.index === importsRE.lastIndex) { + importsRE.lastIndex++; + } + js += `\nimport ${m[1]}`; + } + } + if (!code.includes(`export default`)) { + js += `\nexport default {}`; + } + if (code.includes('import.meta.glob')) { + return { + // transformGlob already transforms to js + loader: 'js', + contents: await transformGlob(js, path, config.root, loader) + }; + } + return { + loader, + contents: js + }; + }); + // bare imports: record and externalize ---------------------------------- + build.onResolve({ + // avoid matching windows volume + filter: /^[\w@][^:]/ + }, async ({ path: id, importer }) => { + if (exclude === null || exclude === void 0 ? void 0 : exclude.some((e) => e === id || id.startsWith(e + '/'))) { + return externalUnlessEntry({ path: id }); + } + if (depImports[id]) { + return externalUnlessEntry({ path: id }); + } + const resolved = await resolve(id, importer); + if (resolved) { + if (shouldExternalizeDep(resolved, id)) { + return externalUnlessEntry({ path: id }); + } + if (resolved.includes('node_modules') || (include === null || include === void 0 ? void 0 : include.includes(id))) { + // dependency or forced included, externalize and stop crawling + if (OPTIMIZABLE_ENTRY_RE.test(resolved)) { + depImports[id] = resolved; + } + return externalUnlessEntry({ path: id }); + } + else { + const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined; + // linked package, keep crawling + return { + path: path__default.resolve(resolved), + namespace + }; + } + } + else { + missing[id] = normalizePath$4(importer); + } + }); + // Externalized file types ----------------------------------------------- + // these are done on raw ids using esbuild's native regex filter so it + // should be faster than doing it in the catch-all via js + // they are done after the bare import resolve because a package name + // may end with these extensions + // css & json + build.onResolve({ + filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|json)$/ + }, externalUnlessEntry); + // known asset types + build.onResolve({ + filter: new RegExp(`\\.(${KNOWN_ASSET_TYPES.join('|')})$`) + }, externalUnlessEntry); + // known vite query types: ?worker, ?raw + build.onResolve({ filter: SPECIAL_QUERY_RE }, ({ path }) => ({ + path, + external: true + })); + // catch all ------------------------------------------------------------- + build.onResolve({ + filter: /.*/ + }, async ({ path: id, importer }) => { + // use vite resolver to support urls and omitted extensions + const resolved = await resolve(id, importer); + if (resolved) { + if (shouldExternalizeDep(resolved, id)) { + return externalUnlessEntry({ path: id }); + } + const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined; + return { + path: path__default.resolve(cleanUrl(resolved)), + namespace + }; + } + else { + // resolve failed... probably unsupported type + return externalUnlessEntry({ path: id }); + } + }); + // for jsx/tsx, we need to access the content and check for + // presence of import.meta.glob, since it results in import relationships + // but isn't crawled by esbuild. + build.onLoad({ filter: JS_TYPES_RE }, ({ path: id }) => { + let ext = path__default.extname(id).slice(1); + if (ext === 'mjs') + ext = 'js'; + let contents = fs__default.readFileSync(id, 'utf-8'); + if (ext.endsWith('x') && config.esbuild && config.esbuild.jsxInject) { + contents = config.esbuild.jsxInject + `\n` + contents; + } + if (contents.includes('import.meta.glob')) { + return transformGlob(contents, id, config.root, ext).then((contents) => ({ + loader: ext, + contents + })); + } + return { + loader: ext, + contents + }; + }); + } + }; +} +async function transformGlob(source, importer, root, loader) { + // transform the content first since es-module-lexer can't handle non-js + if (loader !== 'js') { + source = (await esbuild.transform(source, { loader })).code; + } + await init; + const imports = parse$d(source)[0]; + const s = new MagicString(source); + for (let index = 0; index < imports.length; index++) { + const { s: start, e: end, ss: expStart } = imports[index]; + const url = source.slice(start, end); + if (url !== 'import.meta') + continue; + if (source.slice(end, end + 5) !== '.glob') + continue; + const { importsString, exp, endIndex } = await transformImportGlob(source, start, normalizePath$4(importer), index, root); + s.prepend(importsString); + s.overwrite(expStart, endIndex, exp); + } + return s.toString(); +} +function shouldExternalizeDep(resolvedId, rawId) { + // not a valid file path + if (!path__default.isAbsolute(resolvedId)) { + return true; + } + // virtual id + if (resolvedId === rawId || resolvedId.includes('\0')) { + return true; + } + // resolved is not a scannable type + if (!JS_TYPES_RE.test(resolvedId) && !htmlTypesRE.test(resolvedId)) { + return true; + } + return false; +} + +/** + * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL + * + * Supports tempalte string with dynamic segments: + * ``` + * new URL(`./dir/${name}.png`, import.meta.url) + * // transformed to + * import.meta.globEager('./dir/**.png')[`./dir/${name}.png`].default + * ``` + */ +function assetImportMetaUrlPlugin(config) { + return { + name: 'asset-import-meta-url', + async transform(code, id, ssr) { + if (code.includes('new URL') && code.includes(`import.meta.url`)) { + const importMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\)/g; + const noCommentsCode = code + .replace(multilineCommentsRE, (m) => ' '.repeat(m.length)) + .replace(singlelineCommentsRE, (m) => ' '.repeat(m.length)); + let s = null; + let match; + while ((match = importMetaUrlRE.exec(noCommentsCode))) { + const { 0: exp, 1: rawUrl, index } = match; + if (ssr) { + this.error(`\`new URL(url, import.meta.url)\` is not supported in SSR.`, index); + } + if (!s) + s = new MagicString(code); + // potential dynamic template string + if (rawUrl[0] === '`' && /\$\{/.test(rawUrl)) { + const ast = this.parse(rawUrl); + const templateLiteral = ast.body[0].expression; + if (templateLiteral.expressions.length) { + const pattern = buildGlobPattern(templateLiteral); + // Note: native import.meta.url is not supported in the baseline + // target so we use window.location here - + s.overwrite(index, index + exp.length, `new URL(import.meta.globEagerDefault(${JSON.stringify(pattern)})[${rawUrl}], window.location)`); + continue; + } + } + const url = rawUrl.slice(1, -1); + const file = path__default.resolve(path__default.dirname(id), url); + const builtUrl = await fileToUrl(file, config, this); + s.overwrite(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, window.location)`); + } + if (s) { + return { + code: s.toString(), + map: config.build.sourcemap ? s.generateMap({ hires: true }) : null + }; + } + } + return null; + } + }; +} +function buildGlobPattern(ast) { + let pattern = ''; + let lastElementIndex = -1; + for (const exp of ast.expressions) { + for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) { + const el = ast.quasis[i]; + if (el.end < exp.start) { + pattern += el.value.raw; + lastElementIndex = i; + } + } + pattern += '**'; + } + for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) { + pattern += ast.quasis[i].value.raw; + } + return pattern; +} + +function loadFallbackPlugin() { + return { + name: 'load-fallback', + async load(id) { + try { + return fs$v.promises.readFile(cleanUrl(id), 'utf-8'); + } + catch (e) { + return fs$v.promises.readFile(id, 'utf-8'); + } + } + }; +} + +function resolveBuildOptions(raw) { + const resolved = { + target: 'modules', + polyfillModulePreload: true, + outDir: 'dist', + assetsDir: 'assets', + assetsInlineLimit: 4096, + cssCodeSplit: !(raw === null || raw === void 0 ? void 0 : raw.lib), + sourcemap: false, + rollupOptions: {}, + commonjsOptions: { + include: [/node_modules/], + extensions: ['.js', '.cjs'], + ...raw === null || raw === void 0 ? void 0 : raw.commonjsOptions + }, + dynamicImportVarsOptions: { + warnOnError: true, + exclude: [/node_modules/], + ...raw === null || raw === void 0 ? void 0 : raw.dynamicImportVarsOptions + }, + minify: (raw === null || raw === void 0 ? void 0 : raw.ssr) ? false : 'terser', + terserOptions: {}, + write: true, + emptyOutDir: null, + manifest: false, + lib: false, + ssr: false, + ssrManifest: false, + brotliSize: true, + chunkSizeWarningLimit: 500, + watch: null, + ...raw + }; + // handle special build targets + if (resolved.target === 'modules') { + // Support browserslist + // "defaults and supports es6-module and supports es6-module-dynamic-import", + resolved.target = [ + 'es2019', + 'edge88', + 'firefox78', + 'chrome87', + 'safari13.1' + ]; + } + else if (resolved.target === 'esnext' && resolved.minify === 'terser') { + // esnext + terser: limit to es2019 so it can be minified by terser + resolved.target = 'es2019'; + } + // normalize false string into actual false + if (resolved.minify === 'false') { + resolved.minify = false; + } + return resolved; +} +function resolveBuildPlugins(config) { + const options = config.build; + return { + pre: [ + buildHtmlPlugin(config), + commonjs(options.commonjsOptions), + dataURIPlugin(), + dynamicImportVariables(options.dynamicImportVarsOptions), + assetImportMetaUrlPlugin(config), + ...(options.rollupOptions.plugins + ? options.rollupOptions.plugins.filter((p) => !!p) + : []) + ], + post: [ + buildImportAnalysisPlugin(config), + buildEsbuildPlugin(config), + ...(options.minify && options.minify !== 'esbuild' + ? [terserPlugin(options.terserOptions)] + : []), + ...(options.manifest ? [manifestPlugin(config)] : []), + ...(options.ssrManifest ? [ssrManifestPlugin(config)] : []), + buildReporterPlugin(config), + loadFallbackPlugin() + ] + }; +} +/** + * Track parallel build calls and only stop the esbuild service when all + * builds are done. (#1098) + */ +let parallelCallCounts = 0; +// we use a separate counter to track since the call may error before the +// bundle is even pushed. +const parallelBuilds = []; +/** + * Bundles the app for production. + * Returns a Promise containing the build result. + */ +async function build(inlineConfig = {}) { + parallelCallCounts++; + try { + return await doBuild(inlineConfig); + } + finally { + parallelCallCounts--; + if (parallelCallCounts <= 0) { + await Promise.all(parallelBuilds.map((bundle) => bundle.close())); + parallelBuilds.length = 0; + } + } +} +async function doBuild(inlineConfig = {}) { + var _a, _b, _c, _d; + const config = await resolveConfig(inlineConfig, 'build', 'production'); + const options = config.build; + const ssr = !!options.ssr; + const libOptions = options.lib; + config.logger.info(source.cyan(`vite v${require('vite/package.json').version} ${source.green(`building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`)}`)); + const resolve = (p) => path__default.resolve(config.root, p); + const input = libOptions + ? resolve(libOptions.entry) + : typeof options.ssr === 'string' + ? resolve(options.ssr) + : ((_a = options.rollupOptions) === null || _a === void 0 ? void 0 : _a.input) || resolve('index.html'); + if (ssr && typeof input === 'string' && input.endsWith('.html')) { + throw new Error(`rollupOptions.input should not be an html file when building for SSR. ` + + `Please specify a dedicated SSR entry.`); + } + const outDir = resolve(options.outDir); + // inject ssr arg to plugin load/transform hooks + const plugins = (ssr ? config.plugins.map((p) => injectSsrFlagToHooks(p)) : config.plugins); + // inject ssrExternal if present + const userExternal = (_b = options.rollupOptions) === null || _b === void 0 ? void 0 : _b.external; + let external = userExternal; + if (ssr) { + // see if we have cached deps data available + let knownImports; + if (config.cacheDir) { + const dataPath = path__default.join(config.cacheDir, '_metadata.json'); + try { + const data = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8')); + knownImports = Object.keys(data.optimized); + } + catch (e) { } + } + if (!knownImports) { + // no dev deps optimization data, do a fresh scan + knownImports = Object.keys((await scanImports(config)).deps); + } + external = resolveExternal(resolveSSRExternal(config, knownImports), userExternal); + } + const rollup = require('rollup'); + const rollupOptions = { + input, + preserveEntrySignatures: ssr + ? 'allow-extension' + : libOptions + ? 'strict' + : false, + ...options.rollupOptions, + plugins, + external, + onwarn(warning, warn) { + onRollupWarning(warning, warn, config); + } + }; + const outputBuildError = (e) => { + let msg = source.red((e.plugin ? `[${e.plugin}] ` : '') + e.message); + if (e.id) { + msg += `\nfile: ${source.cyan(e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : ''))}`; + } + if (e.frame) { + msg += `\n` + source.yellow(e.frame); + } + config.logger.error(msg, { error: e }); + }; + try { + const pkgName = libOptions && getPkgName(config.root); + const buildOutputOptions = (output = {}) => { + return { + dir: outDir, + format: ssr ? 'cjs' : 'es', + exports: ssr ? 'named' : 'auto', + sourcemap: options.sourcemap, + name: libOptions ? libOptions.name : undefined, + entryFileNames: ssr + ? `[name].js` + : libOptions + ? resolveLibFilename(libOptions, output.format || 'es', pkgName) + : path__default.posix.join(options.assetsDir, `[name].[hash].js`), + chunkFileNames: libOptions + ? `[name].js` + : path__default.posix.join(options.assetsDir, `[name].[hash].js`), + assetFileNames: libOptions + ? `[name].[ext]` + : path__default.posix.join(options.assetsDir, `[name].[hash].[ext]`), + // #764 add `Symbol.toStringTag` when build es module into cjs chunk + // #1048 add `Symbol.toStringTag` for module default export + namespaceToStringTag: true, + inlineDynamicImports: ssr && typeof input === 'string', + manualChunks: !ssr && + !libOptions && + (output === null || output === void 0 ? void 0 : output.format) !== 'umd' && + (output === null || output === void 0 ? void 0 : output.format) !== 'iife' + ? createMoveToVendorChunkFn() + : undefined, + ...output + }; + }; + // resolve lib mode outputs + const outputs = resolveBuildOutputs((_c = options.rollupOptions) === null || _c === void 0 ? void 0 : _c.output, libOptions, config.logger); + // watch file changes with rollup + if (config.build.watch) { + config.logger.info(source.cyanBright(`\nwatching for file changes...`)); + const output = []; + if (Array.isArray(outputs)) { + for (const resolvedOutput of outputs) { + output.push(buildOutputOptions(resolvedOutput)); + } + } + else { + output.push(buildOutputOptions(outputs)); + } + const watcherOptions = config.build.watch; + const watcher = rollup.watch({ + ...rollupOptions, + output, + watch: { + ...watcherOptions, + chokidar: { + ignored: [ + '**/node_modules/**', + '**/.git/**', + ...(((_d = watcherOptions === null || watcherOptions === void 0 ? void 0 : watcherOptions.chokidar) === null || _d === void 0 ? void 0 : _d.ignored) || []) + ], + ignoreInitial: true, + ignorePermissionErrors: true, + ...watcherOptions.chokidar + } + } + }); + watcher.on('event', (event) => { + if (event.code === 'BUNDLE_START') { + config.logger.info(source.cyanBright(`\nbuild started...`)); + if (options.write) { + prepareOutDir(outDir, options.emptyOutDir, config); + } + } + else if (event.code === 'BUNDLE_END') { + event.result.close(); + config.logger.info(source.cyanBright(`built in ${event.duration}ms.`)); + } + else if (event.code === 'ERROR') { + outputBuildError(event.error); + } + }); + // stop watching + watcher.close(); + return watcher; + } + // write or generate files with rollup + const bundle = await rollup.rollup(rollupOptions); + parallelBuilds.push(bundle); + const generate = (output = {}) => { + return bundle[options.write ? 'write' : 'generate'](buildOutputOptions(output)); + }; + if (options.write) { + prepareOutDir(outDir, options.emptyOutDir, config); + } + if (Array.isArray(outputs)) { + const res = []; + for (const output of outputs) { + res.push(await generate(output)); + } + return res; + } + else { + return await generate(outputs); + } + } + catch (e) { + outputBuildError(e); + throw e; + } +} +function prepareOutDir(outDir, emptyOutDir, config) { + if (fs__default.existsSync(outDir)) { + if (emptyOutDir == null && + !normalizePath$4(outDir).startsWith(config.root + '/')) { + // warn if outDir is outside of root + config.logger.warn(source.yellow(`\n${source.bold(`(!)`)} outDir ${source.white.dim(outDir)} is not inside project root and will not be emptied.\n` + + `Use --emptyOutDir to override.\n`)); + } + else if (emptyOutDir !== false) { + emptyDir(outDir, ['.git']); + } + } + if (config.publicDir && fs__default.existsSync(config.publicDir)) { + copyDir(config.publicDir, outDir); + } +} +function getPkgName(root) { + const { name } = JSON.parse(lookupFile(root, ['package.json']) || `{}`); + if (!name) + throw new Error('no name found in package.json'); + return name.startsWith('@') ? name.split('/')[1] : name; +} +function createMoveToVendorChunkFn(config) { + const cache = new Map(); + return (id, { getModuleInfo }) => { + if (id.includes('node_modules') && + !isCSSRequest(id) && + staticImportedByEntry(id, getModuleInfo, cache)) { + return 'vendor'; + } + }; +} +function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) { + if (cache.has(id)) { + return cache.get(id); + } + if (importStack.includes(id)) { + // circular deps! + cache.set(id, false); + return false; + } + const mod = getModuleInfo(id); + if (!mod) { + cache.set(id, false); + return false; + } + if (mod.isEntry) { + cache.set(id, true); + return true; + } + const someImporterIs = mod.importers.some((importer) => staticImportedByEntry(importer, getModuleInfo, cache, importStack.concat(id))); + cache.set(id, someImporterIs); + return someImporterIs; +} +function resolveLibFilename(libOptions, format, pkgName) { + return typeof libOptions.fileName === 'function' + ? libOptions.fileName(format) + : `${libOptions.fileName || pkgName}.${format}.js`; +} +function resolveBuildOutputs(outputs, libOptions, logger) { + if (libOptions) { + const formats = libOptions.formats || ['es', 'umd']; + if ((formats.includes('umd') || formats.includes('iife')) && + !libOptions.name) { + throw new Error(`Option "build.lib.name" is required when output formats ` + + `include "umd" or "iife".`); + } + if (!outputs) { + return formats.map((format) => ({ format })); + } + else if (!Array.isArray(outputs)) { + return formats.map((format) => ({ ...outputs, format })); + } + else if (libOptions.formats) { + // user explicitly specifying own output array + logger.warn(source.yellow(`"build.lib.formats" will be ignored because ` + + `"build.rollupOptions.output" is already an array format`)); + } + } + return outputs; +} +const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]; +const dynamicImportWarningIgnoreList = [ + `Unsupported expression`, + `statically analyzed` +]; +function onRollupWarning(warning, warn, config) { + var _a; + if (warning.code === 'UNRESOLVED_IMPORT') { + const id = warning.source; + const importer = warning.importer; + // throw unless it's commonjs external... + if (!importer || !/\?commonjs-external$/.test(importer)) { + throw new Error(`[vite]: Rollup failed to resolve import "${id}" from "${importer}".\n` + + `This is most likely unintended because it can break your application at runtime.\n` + + `If you do want to externalize this module explicitly add it to\n` + + `\`build.rollupOptions.external\``); + } + } + if (warning.plugin === 'rollup-plugin-dynamic-import-variables' && + dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg))) { + return; + } + if (!warningIgnoreList.includes(warning.code)) { + const userOnWarn = (_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.onwarn; + if (userOnWarn) { + userOnWarn(warning, warn); + } + else if (warning.code === 'PLUGIN_WARNING') { + config.logger.warn(`${source.bold.yellow(`[plugin:${warning.plugin}]`)} ${source.yellow(warning.message)}`); + } + else { + warn(warning); + } + } +} +function resolveExternal(ssrExternals, user) { + return ((id, parentId, isResolved) => { + if (shouldExternalizeForSSR(id, ssrExternals)) { + return true; + } + if (user) { + if (typeof user === 'function') { + return user(id, parentId, isResolved); + } + else if (Array.isArray(user)) { + return user.some((test) => isExternal(id, test)); + } + else { + return isExternal(id, user); + } + } + }); +} +function isExternal(id, test) { + if (typeof test === 'string') { + return id === test; + } + else { + return test.test(id); + } +} +function injectSsrFlagToHooks(p) { + const { resolveId, load, transform } = p; + return { + ...p, + resolveId: wrapSsrHook(resolveId), + load: wrapSsrHook(load), + transform: wrapSsrHook(transform) + }; +} +function wrapSsrHook(fn) { + if (!fn) + return; + return function (...args) { + return fn.call(this, ...args, true); + }; +} + +var build$1 = { + __proto__: null, + resolveBuildOptions: resolveBuildOptions, + resolveBuildPlugins: resolveBuildPlugins, + build: build, + resolveLibFilename: resolveLibFilename, + onRollupWarning: onRollupWarning +}; + +var src$1 = {exports: {}}; + +var browser$1 = {exports: {}}; + +var debug$9 = {exports: {}}; + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +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$a(val); + } else if (type === 'number' && isNaN(val) === false) { + 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$a(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|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 '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) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} + +(function (module, exports) { +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = ms; + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.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". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // 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 match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + 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.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} +}(debug$9, debug$9.exports)); + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +(function (module, exports) { +exports = module.exports = debug$9.exports; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * 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 + */ + +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') { + return true; + } + + // 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+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!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 ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // 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; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * 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 { + return window.localStorage; + } catch (e) {} +} +}(browser$1, browser$1.exports)); + +var node$1 = {exports: {}}; + +/** + * Module dependencies. + */ + +(function (module, exports) { +var tty = require$$0__default; +var util = require$$0__default$3; + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = debug$9.exports; +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')(); +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = fs__default; + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require$$4__default$1; + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); +}(node$1, node$1.exports)); + +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + src$1.exports = browser$1.exports; +} else { + src$1.exports = node$1.exports; +} + +var src = {exports: {}}; + +var browser = {exports: {}}; + +var debug$8 = {exports: {}}; + +(function (module, exports) { +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = ms; + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.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". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // 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 match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + 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.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} +}(debug$8, debug$8.exports)); + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +(function (module, exports) { +exports = module.exports = debug$8.exports; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * 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 + */ + +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') { + return true; + } + + // 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+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!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 ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // 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; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * 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 { + return window.localStorage; + } catch (e) {} +} +}(browser, browser.exports)); + +var node = {exports: {}}; + +/** + * Module dependencies. + */ + +(function (module, exports) { +var tty = require$$0__default; +var util = require$$0__default$3; + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = debug$8.exports; +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')(); +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = fs__default; + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require$$4__default$1; + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); +}(node, node.exports)); + +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + src.exports = browser.exports; +} else { + src.exports = node.exports; +} + +/*! + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +var encodeurl = encodeUrl$1; + +/** + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. + * @private + */ + +var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g; + +/** + * RegExp to match unmatched surrogate pair. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g; + +/** + * String to replace unmatched surrogate pair with. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2'; + +/** + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. + * + * This function will take an already-encoded URL and encode all the non-URL + * code points. This function will not encode the "%" character unless it is + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will + * be encoded as `%25foo`). + * + * This encode is meant to be "safe" and does not throw errors. It will try as + * hard as it can to properly encode the given URL, including replacing any raw, + * unpaired surrogate pairs with the Unicode replacement character prior to + * encoding. + * + * @param {string} url + * @return {string} + * @public + */ + +function encodeUrl$1 (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) +} + +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +var escapeHtml_1 = escapeHtml$1; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml$1(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} + +var onFinished$2 = {exports: {}}; + +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +var eeFirst = first$1; + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first$1(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = []; + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i]; + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0]; + + for (var j = 1; j < arr.length; j++) { + var event = arr[j]; + var fn = listener(event, callback); + + // listen to the event + ee.on(event, fn); + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }); + } + } + + function callback() { + cleanup(); + done.apply(null, arguments); + } + + function cleanup() { + var x; + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i]; + x.ee.removeListener(x.event, x.fn); + } + } + + function thunk(fn) { + done = fn; + } + + thunk.cancel = cleanup; + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length); + var ee = this; + var err = event === 'error' + ? arg1 + : null; + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + done(err, ee, event, args); + } +} + +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +onFinished$2.exports = onFinished$1; +onFinished$2.exports.isFinished = isFinished$1; + +/** + * Module dependencies. + * @private + */ + +var first = eeFirst; + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer$2 = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); }; + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished$1(msg, listener) { + if (isFinished$1(msg) !== false) { + defer$2(listener, null, msg); + return msg + } + + // attach the listener to the message + attachListener(msg, listener); + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished$1(msg) { + var socket = msg.socket; + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener(msg, callback) { + var eeMsg; + var eeSocket; + var finished = false; + + function onFinish(error) { + eeMsg.cancel(); + eeSocket.cancel(); + + finished = true; + callback(error); + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish); + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket); + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish); + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket); + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket); + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket); + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished; + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg); + attachFinishedListener(msg, attached); + } + + attached.queue.push(listener); +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null; + if (!listener.queue) return + + var queue = listener.queue; + listener.queue = null; + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg); + } + } + + listener.queue = []; + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket; + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket); + callback(socket); + }; +} + +var parseurl$1 = {exports: {}}; + +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + * @private + */ + +var url$3 = require$$0__default$7; +var parse$9 = url$3.parse; +var Url = url$3.Url; + +/** + * Module exports. + * @public + */ + +parseurl$1.exports = parseurl; +parseurl$1.exports.original = originalurl; + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function parseurl (req) { + var url = req.url; + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl; + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url); + parsed._raw = url; + + return (req._parsedUrl = parsed) +} +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function originalurl (req) { + var url = req.originalUrl; + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl; + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url); + parsed._raw = url; + + return (req._parsedOriginalUrl = parsed) +} +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @private + */ + +function fastparse (str) { + if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { + return parse$9(str) + } + + var pathname = str; + var query = null; + var search = null; + + // This takes the regexp from https://github.com/joyent/node/pull/7878 + // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ + // And unrolls it into a for loop + for (var i = 1; i < str.length; i++) { + switch (str.charCodeAt(i)) { + case 0x3f: /* ? */ + if (search === null) { + pathname = str.substring(0, i); + query = str.substring(i + 1); + search = str.substring(i); + } + break + case 0x09: /* \t */ + case 0x0a: /* \n */ + case 0x0c: /* \f */ + case 0x0d: /* \r */ + case 0x20: /* */ + case 0x23: /* # */ + case 0xa0: + case 0xfeff: + return parse$9(str) + } + } + + var url = Url !== undefined + ? new Url() + : {}; + + url.path = str; + url.href = str; + url.pathname = pathname; + + if (search !== null) { + url.query = query; + url.search = search; + } + + return url +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @private + */ + +function fresh (url, parsedUrl) { + return typeof parsedUrl === 'object' && + parsedUrl !== null && + (Url === undefined || parsedUrl instanceof Url) && + parsedUrl._raw === url +} + +var require$$0$1 = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "(Unused)", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +}; + +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + * @private + */ + +var codes = require$$0$1; + +/** + * Module exports. + * @public + */ + +var statuses$1 = status; + +// status code to message map +status.STATUS_CODES = codes; + +// array of status codes +status.codes = populateStatusesMap(status, codes); + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +}; + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +}; + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +}; + +/** + * Populate the statuses map for given codes. + * @private + */ + +function populateStatusesMap (statuses, codes) { + var arr = []; + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code]; + var status = Number(code); + + // Populate properties + statuses[status] = message; + statuses[message] = status; + statuses[message.toLowerCase()] = status; + + // Add to array + arr.push(status); + }); + + return arr +} + +/** + * Get the status code. + * + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + if (!status[code]) throw new Error('invalid status code: ' + code) + return code + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10); + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n) + return n + } + + n = status[code.toLowerCase()]; + if (!n) throw new Error('invalid status message: "' + code + '"') + return n +} + +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +var unpipe_1 = unpipe$1; + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data'); + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe$1(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe(); + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener; + var listeners = stream.listeners('close'); + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i]; + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream); + } +} + +/*! + * finalhandler + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + * @private + */ + +var debug$7 = src.exports('finalhandler'); +var encodeUrl = encodeurl; +var escapeHtml = escapeHtml_1; +var onFinished = onFinished$2.exports; +var parseUrl$1 = parseurl$1.exports; +var statuses = statuses$1; +var unpipe = unpipe_1; + +/** + * Module variables. + * @private + */ + +var DOUBLE_SPACE_REGEXP = /\x20{2}/g; +var NEWLINE_REGEXP = /\n/g; + +/* istanbul ignore next */ +var defer$1 = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)); }; +var isFinished = onFinished.isFinished; + +/** + * Create a minimal HTML document. + * + * @param {string} message + * @private + */ + +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replace(NEWLINE_REGEXP, '
') + .replace(DOUBLE_SPACE_REGEXP, '  '); + + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Module exports. + * @public + */ + +var finalhandler_1 = finalhandler$1; + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler$1 (req, res, options) { + var opts = options || {}; + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development'; + + // get error callback + var onerror = opts.onerror; + + return function (err) { + var headers; + var msg; + var status; + + // ignore 404 on in-flight response + if (!err && headersSent(res)) { + debug$7('cannot 404 after headers sent'); + return + } + + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err); + + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res); + } else { + // respect headers from error + headers = getErrorHeaders(err); + } + + // get error message + msg = getErrorMessage(err, status, env); + } else { + // not found + status = 404; + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)); + } + + debug$7('default %s', status); + + // schedule onerror callback + if (err && onerror) { + defer$1(onerror, err, req, res); + } + + // cannot actually respond + if (headersSent(res)) { + debug$7('cannot %d after headers sent', status); + req.socket.destroy(); + return + } + + // send response + send$2(req, res, status, headers, msg); + } +} + +/** + * Get headers from Error object. + * + * @param {Error} err + * @return {object} + * @private + */ + +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } + + var headers = Object.create(null); + var keys = Object.keys(err.headers); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + headers[key] = err.headers[key]; + } + + return headers +} + +/** + * Get message from Error object, fallback to status message. + * + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private + */ + +function getErrorMessage (err, status, env) { + var msg; + + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack; + + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString(); + } + } + + return msg || statuses[status] +} + +/** + * Get status code from Error object. + * + * @param {Error} err + * @return {number} + * @private + */ + +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status + } + + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } + + return undefined +} + +/** + * Get resource name for the request. + * + * This is typically just the original pathname of the request + * but will fallback to "resource" is that cannot be determined. + * + * @param {IncomingMessage} req + * @return {string} + * @private + */ + +function getResourceName (req) { + try { + return parseUrl$1.original(req).pathname + } catch (e) { + return 'resource' + } +} + +/** + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} + * @private + */ + +function getResponseStatusCode (res) { + var status = res.statusCode; + + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500; + } + + return status +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ + +function send$2 (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message); + + // response status + res.statusCode = status; + res.statusMessage = statuses[status]; + + // response headers + setHeaders(res, headers); + + // security headers + res.setHeader('Content-Security-Policy', "default-src 'none'"); + res.setHeader('X-Content-Type-Options', 'nosniff'); + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8'); + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')); + + if (req.method === 'HEAD') { + res.end(); + return + } + + res.end(body, 'utf8'); + } + + if (isFinished(req)) { + write(); + return + } + + // unpipe everything from the request + unpipe(req); + + // flush the request + onFinished(req, write); + req.resume(); +} + +/** + * Set response headers from an object. + * + * @param {OutgoingMessage} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + if (!headers) { + return + } + + var keys = Object.keys(headers); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + res.setHeader(key, headers[key]); + } +} + +var utilsMerge = {exports: {}}; + +/** + * Merge object b with object a. + * + * var a = { foo: 'bar' } + * , b = { bar: 'baz' }; + * + * merge(a, b); + * // => { foo: 'bar', bar: 'baz' } + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api public + */ + +(function (module, exports) { +module.exports = function(a, b){ + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; +}; +}(utilsMerge)); + +/*! + * connect + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + * @private + */ + +var debug$6 = src$1.exports('connect:dispatcher'); +var EventEmitter$3 = require$$0__default$6.EventEmitter; +var finalhandler = finalhandler_1; +var http$4 = require$$1__default$1; +var merge = utilsMerge.exports; +var parseUrl = parseurl$1.exports; + +/** + * Module exports. + * @public + */ + +var connect = createServer$1; + +/** + * Module variables. + * @private + */ + +var env$1 = process.env.NODE_ENV || 'development'; +var proto = {}; + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); }; + +/** + * Create a new connect server. + * + * @return {function} + * @public + */ + +function createServer$1() { + function app(req, res, next){ app.handle(req, res, next); } + merge(app, proto); + merge(app, EventEmitter$3.prototype); + app.route = '/'; + app.stack = []; + return app; +} + +/** + * Utilize the given middleware `handle` to the given `route`, + * defaulting to _/_. This "route" is the mount-point for the + * middleware, when given a value other than _/_ the middleware + * is only effective when that segment is present in the request's + * pathname. + * + * For example if we were to mount a function at _/admin_, it would + * be invoked on _/admin_, and _/admin/settings_, however it would + * not be invoked for _/_, or _/posts_. + * + * @param {String|Function|Server} route, callback or server + * @param {Function|Server} callback or server + * @return {Server} for chaining + * @public + */ + +proto.use = function use(route, fn) { + var handle = fn; + var path = route; + + // default route to '/' + if (typeof route !== 'string') { + handle = route; + path = '/'; + } + + // wrap sub-apps + if (typeof handle.handle === 'function') { + var server = handle; + server.route = path; + handle = function (req, res, next) { + server.handle(req, res, next); + }; + } + + // wrap vanilla http.Servers + if (handle instanceof http$4.Server) { + handle = handle.listeners('request')[0]; + } + + // strip trailing slash + if (path[path.length - 1] === '/') { + path = path.slice(0, -1); + } + + // add the middleware + debug$6('use %s %s', path || '/', handle.name || 'anonymous'); + this.stack.push({ route: path, handle: handle }); + + return this; +}; + +/** + * Handle server requests, punting them down + * the middleware stack. + * + * @private + */ + +proto.handle = function handle(req, res, out) { + var index = 0; + var protohost = getProtohost(req.url) || ''; + var removed = ''; + var slashAdded = false; + var stack = this.stack; + + // final function handler + var done = out || finalhandler(req, res, { + env: env$1, + onerror: logerror + }); + + // store the original URL + req.originalUrl = req.originalUrl || req.url; + + function next(err) { + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; + } + + if (removed.length !== 0) { + req.url = protohost + removed + req.url.substr(protohost.length); + removed = ''; + } + + // next callback + var layer = stack[index++]; + + // all done + if (!layer) { + defer(done, err); + return; + } + + // route data + var path = parseUrl(req).pathname || '/'; + var route = layer.route; + + // skip this layer if the route doesn't match + if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) { + return next(err); + } + + // skip if route match does not border "/", ".", or end + var c = path.length > route.length && path[route.length]; + if (c && c !== '/' && c !== '.') { + return next(err); + } + + // trim off the part of the url that matches the route + if (route.length !== 0 && route !== '/') { + removed = route; + req.url = protohost + req.url.substr(protohost.length + removed.length); + + // ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + } + + // call the layer handle + call(layer.handle, route, err, req, res, next); + } + + next(); +}; + +/** + * Listen for connections. + * + * This method takes the same arguments + * as node's `http.Server#listen()`. + * + * HTTP and HTTPS: + * + * If you run your application both as HTTP + * and HTTPS you may wrap them individually, + * since your Connect "server" is really just + * a JavaScript `Function`. + * + * var connect = require('connect') + * , http = require('http') + * , https = require('https'); + * + * var app = connect(); + * + * http.createServer(app).listen(80); + * https.createServer(options, app).listen(443); + * + * @return {http.Server} + * @api public + */ + +proto.listen = function listen() { + var server = http$4.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Invoke a route handle. + * @private + */ + +function call(handle, route, err, req, res, next) { + var arity = handle.length; + var error = err; + var hasError = Boolean(err); + + debug$6('%s %s : %s', handle.name || '', route, req.originalUrl); + + try { + if (hasError && arity === 4) { + // error-handling middleware + handle(err, req, res, next); + return; + } else if (!hasError && arity < 4) { + // request-handling middleware + handle(req, res, next); + return; + } + } catch (e) { + // replace the error + error = e; + } + + // continue + next(error); +} + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + if (env$1 !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Get get protocol + host for a URL. + * + * @param {string} url + * @private + */ + +function getProtohost(url) { + if (url.length === 0 || url[0] === '/') { + return undefined; + } + + var fqdnIndex = url.indexOf('://'); + + return fqdnIndex !== -1 && url.lastIndexOf('?', fqdnIndex) === -1 + ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined; +} + +var lib$1 = {exports: {}}; + +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +var vary$1 = {exports: {}}; + +/*! + * vary + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +vary$1.exports = vary; +vary$1.exports.append = append; + +/** + * RegExp to match field-name in RFC 7230 sec 3.2 + * + * field-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + */ + +var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @public + */ + +function append (header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required') + } + + if (!field) { + throw new TypeError('field argument is required') + } + + // get fields array + var fields = !Array.isArray(field) + ? parse$8(String(field)) + : field; + + // assert on invalid field names + for (var j = 0; j < fields.length; j++) { + if (!FIELD_NAME_REGEXP.test(fields[j])) { + throw new TypeError('field argument contains an invalid header name') + } + } + + // existing, unspecified vary + if (header === '*') { + return header + } + + // enumerate current values + var val = header; + var vals = parse$8(header.toLowerCase()); + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*' + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase(); + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld); + val = val + ? val + ', ' + fields[i] + : fields[i]; + } + } + + return val +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @private + */ + +function parse$8 (header) { + var end = 0; + var list = []; + var start = 0; + + // gather tokens + for (var i = 0, len = header.length; i < len; i++) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1; + } + break + case 0x2c: /* , */ + list.push(header.substring(start, end)); + start = end = i + 1; + break + default: + end = i + 1; + break + } + } + + // final token + list.push(header.substring(start, end)); + + return list +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @public + */ + +function vary (res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required') + } + + // get existing header + var val = res.getHeader('Vary') || ''; + var header = Array.isArray(val) + ? val.join(', ') + : String(val); + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val); + } +} + +(function () { + + var assign = objectAssign; + var vary = vary$1.exports; + + var defaults = { + origin: '*', + methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', + preflightContinue: false, + optionsSuccessStatus: 204 + }; + + function isString(s) { + return typeof s === 'string' || s instanceof String; + } + + function isOriginAllowed(origin, allowedOrigin) { + if (Array.isArray(allowedOrigin)) { + for (var i = 0; i < allowedOrigin.length; ++i) { + if (isOriginAllowed(origin, allowedOrigin[i])) { + return true; + } + } + return false; + } else if (isString(allowedOrigin)) { + return origin === allowedOrigin; + } else if (allowedOrigin instanceof RegExp) { + return allowedOrigin.test(origin); + } else { + return !!allowedOrigin; + } + } + + function configureOrigin(options, req) { + var requestOrigin = req.headers.origin, + headers = [], + isAllowed; + + if (!options.origin || options.origin === '*') { + // allow any origin + headers.push([{ + key: 'Access-Control-Allow-Origin', + value: '*' + }]); + } else if (isString(options.origin)) { + // fixed origin + headers.push([{ + key: 'Access-Control-Allow-Origin', + value: options.origin + }]); + headers.push([{ + key: 'Vary', + value: 'Origin' + }]); + } else { + isAllowed = isOriginAllowed(requestOrigin, options.origin); + // reflect origin + headers.push([{ + key: 'Access-Control-Allow-Origin', + value: isAllowed ? requestOrigin : false + }]); + headers.push([{ + key: 'Vary', + value: 'Origin' + }]); + } + + return headers; + } + + function configureMethods(options) { + var methods = options.methods; + if (methods.join) { + methods = options.methods.join(','); // .methods is an array, so turn it into a string + } + return { + key: 'Access-Control-Allow-Methods', + value: methods + }; + } + + function configureCredentials(options) { + if (options.credentials === true) { + return { + key: 'Access-Control-Allow-Credentials', + value: 'true' + }; + } + return null; + } + + function configureAllowedHeaders(options, req) { + var allowedHeaders = options.allowedHeaders || options.headers; + var headers = []; + + if (!allowedHeaders) { + allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers + headers.push([{ + key: 'Vary', + value: 'Access-Control-Request-Headers' + }]); + } else if (allowedHeaders.join) { + allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string + } + if (allowedHeaders && allowedHeaders.length) { + headers.push([{ + key: 'Access-Control-Allow-Headers', + value: allowedHeaders + }]); + } + + return headers; + } + + function configureExposedHeaders(options) { + var headers = options.exposedHeaders; + if (!headers) { + return null; + } else if (headers.join) { + headers = headers.join(','); // .headers is an array, so turn it into a string + } + if (headers && headers.length) { + return { + key: 'Access-Control-Expose-Headers', + value: headers + }; + } + return null; + } + + function configureMaxAge(options) { + var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString(); + if (maxAge && maxAge.length) { + return { + key: 'Access-Control-Max-Age', + value: maxAge + }; + } + return null; + } + + function applyHeaders(headers, res) { + for (var i = 0, n = headers.length; i < n; i++) { + var header = headers[i]; + if (header) { + if (Array.isArray(header)) { + applyHeaders(header, res); + } else if (header.key === 'Vary' && header.value) { + vary(res, header.value); + } else if (header.value) { + res.setHeader(header.key, header.value); + } + } + } + } + + function cors(options, req, res, next) { + var headers = [], + method = req.method && req.method.toUpperCase && req.method.toUpperCase(); + + if (method === 'OPTIONS') { + // preflight + headers.push(configureOrigin(options, req)); + headers.push(configureCredentials(options)); + headers.push(configureMethods(options)); + headers.push(configureAllowedHeaders(options, req)); + headers.push(configureMaxAge(options)); + headers.push(configureExposedHeaders(options)); + applyHeaders(headers, res); + + if (options.preflightContinue) { + next(); + } else { + // Safari (and potentially other browsers) need content-length 0, + // for 204 or they just hang waiting for a body + res.statusCode = options.optionsSuccessStatus; + res.setHeader('Content-Length', '0'); + res.end(); + } + } else { + // actual response + headers.push(configureOrigin(options, req)); + headers.push(configureCredentials(options)); + headers.push(configureExposedHeaders(options)); + applyHeaders(headers, res); + next(); + } + } + + function middlewareWrapper(o) { + // if options are static (either via defaults or custom options passed in), wrap in a function + var optionsCallback = null; + if (typeof o === 'function') { + optionsCallback = o; + } else { + optionsCallback = function (req, cb) { + cb(null, o); + }; + } + + return function corsMiddleware(req, res, next) { + optionsCallback(req, function (err, options) { + if (err) { + next(err); + } else { + var corsOptions = assign({}, defaults, options); + var originCallback = null; + if (corsOptions.origin && typeof corsOptions.origin === 'function') { + originCallback = corsOptions.origin; + } else if (corsOptions.origin) { + originCallback = function (origin, cb) { + cb(null, corsOptions.origin); + }; + } + + if (originCallback) { + originCallback(req.headers.origin, function (err2, origin) { + if (err2 || !origin) { + next(err2); + } else { + corsOptions.origin = origin; + cors(corsOptions, req, res, next); + } + }); + } else { + next(); + } + } + }); + }; + } + + // can pass either an options hash, an options delegate, or nothing + lib$1.exports = middlewareWrapper; + +}()); + +var corsMiddleware = lib$1.exports; + +var chokidar = {}; + +const fs$b = fs__default; +const { Readable } = require$$0__default$2; +const sysPath$3 = path__default; +const { promisify: promisify$4 } = require$$0__default$3; +const picomatch$1 = picomatch$3; + +const readdir$1 = promisify$4(fs$b.readdir); +const stat$3 = promisify$4(fs$b.stat); +const lstat$2 = promisify$4(fs$b.lstat); +const realpath$1 = promisify$4(fs$b.realpath); + +/** + * @typedef {Object} EntryInfo + * @property {String} path + * @property {String} fullPath + * @property {fs.Stats=} stats + * @property {fs.Dirent=} dirent + * @property {String} basename + */ + +const BANG$2 = '!'; +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'; +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; + if (typeof filter === 'function') return filter; + + if (typeof filter === 'string') { + const glob = picomatch$1(filter.trim()); + return entry => glob(entry.basename); + } + + if (Array.isArray(filter)) { + const positive = []; + const negative = []; + for (const item of filter) { + const trimmed = item.trim(); + if (trimmed.charAt(0) === BANG$2) { + negative.push(picomatch$1(trimmed.slice(1))); + } else { + positive.push(picomatch$1(trimmed)); + } + } + + if (negative.length > 0) { + if (positive.length > 0) { + return entry => + positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename)); + } + return entry => !negative.some(f => f(entry.basename)); + } + return entry => positive.some(f => f(entry.basename)); + } +}; + +class ReaddirpStream extends Readable { + static get defaultOptions() { + return { + root: '.', + /* eslint-disable no-unused-vars */ + fileFilter: (path) => true, + directoryFilter: (path) => true, + /* eslint-enable no-unused-vars */ + type: FILE_TYPE, + lstat: false, + depth: 2147483648, + alwaysStat: false + }; + } + + constructor(options = {}) { + super({ + objectMode: true, + autoDestroy: true, + highWaterMark: options.highWaterMark || 4096 + }); + const opts = { ...ReaddirpStream.defaultOptions, ...options }; + const { root, type } = opts; + + this._fileFilter = normalizeFilter(opts.fileFilter); + this._directoryFilter = normalizeFilter(opts.directoryFilter); + + const statMethod = opts.lstat ? lstat$2 : stat$3; + // Use bigint stats if it's windows and stat() supports options (node 10+). + if (wantBigintFsStats) { + this._stat = path => statMethod(path, { bigint: true }); + } else { + this._stat = statMethod; + } + + this._maxDepth = opts.depth; + this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsEverything = type === EVERYTHING_TYPE; + this._root = sysPath$3.resolve(root); + this._isDirent = ('Dirent' in fs$b) && !opts.alwaysStat; + this._statsProp = this._isDirent ? 'dirent' : 'stats'; + this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent }; + + // Launch stream with one parent, the root dir. + this.parents = [this._exploreDir(root, 1)]; + this.reading = false; + this.parent = undefined; + } + + async _read(batch) { + if (this.reading) return; + this.reading = true; + + try { + while (!this.destroyed && batch > 0) { + const { path, depth, files = [] } = this.parent || {}; + + if (files.length > 0) { + const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path)); + for (const entry of await Promise.all(slice)) { + if (this.destroyed) return; + + const entryType = await this._getEntryType(entry); + if (entryType === 'directory' && this._directoryFilter(entry)) { + if (depth <= this._maxDepth) { + this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); + } + + if (this._wantsDir) { + this.push(entry); + batch--; + } + } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) { + if (this._wantsFile) { + this.push(entry); + batch--; + } + } + } + } else { + const parent = this.parents.pop(); + if (!parent) { + this.push(null); + break; + } + this.parent = await parent; + if (this.destroyed) return; + } + } + } catch (error) { + this.destroy(error); + } finally { + this.reading = false; + } + } + + async _exploreDir(path, depth) { + let files; + try { + files = await readdir$1(path, this._rdOptions); + } catch (error) { + this._onError(error); + } + return { files, depth, path }; + } + + async _formatEntry(dirent, path) { + let entry; + try { + const basename = this._isDirent ? dirent.name : dirent; + const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename)); + entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename }; + entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); + } catch (err) { + this._onError(err); + } + return entry; + } + + _onError(err) { + if (isNormalFlowError(err) && !this.destroyed) { + this.emit('warn', err); + } else { + this.destroy(err); + } + } + + async _getEntryType(entry) { + // entry may be undefined, because a warning or an error were emitted + // and the statsProp is undefined + const stats = entry && entry[this._statsProp]; + if (!stats) { + return; + } + if (stats.isFile()) { + return 'file'; + } + if (stats.isDirectory()) { + return 'directory'; + } + if (stats && stats.isSymbolicLink()) { + const full = entry.fullPath; + try { + const entryRealPath = await realpath$1(full); + const entryRealPathStats = await lstat$2(entryRealPath); + if (entryRealPathStats.isFile()) { + return 'file'; + } + if (entryRealPathStats.isDirectory()) { + const len = entryRealPath.length; + if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) { + const recursiveError = new Error( + `Circular symlink detected: "${full}" points to "${entryRealPath}"` + ); + recursiveError.code = RECURSIVE_ERROR_CODE; + return this._onError(recursiveError); + } + return 'directory'; + } + } catch (error) { + this._onError(error); + } + } + } + + _includeAsFile(entry) { + const stats = entry && entry[this._statsProp]; + + return stats && this._wantsEverything && !stats.isDirectory(); + } +} + +/** + * @typedef {Object} ReaddirpArguments + * @property {Function=} fileFilter + * @property {Function=} directoryFilter + * @property {String=} type + * @property {Number=} depth + * @property {String=} root + * @property {Boolean=} lstat + * @property {Boolean=} bigint + */ + +/** + * Main function which ends up calling readdirRec and reads all files and directories in given root recursively. + * @param {String} root Root directory + * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth + */ +const readdirp$1 = (root, options = {}) => { + let type = options.entryType || options.type; + if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility + if (type) options.type = type; + if (!root) { + throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)'); + } else if (typeof root !== 'string') { + throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)'); + } else if (type && !ALL_TYPES.includes(type)) { + throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`); + } + + options.root = root; + return new ReaddirpStream(options); +}; + +const readdirpPromise = (root, options = {}) => { + return new Promise((resolve, reject) => { + const files = []; + readdirp$1(root, options) + .on('data', entry => files.push(entry)) + .on('end', () => resolve(files)) + .on('error', error => reject(error)); + }); +}; + +readdirp$1.promise = readdirpPromise; +readdirp$1.ReaddirpStream = ReaddirpStream; +readdirp$1.default = readdirp$1; + +var readdirp_1 = readdirp$1; + +var anymatch$2 = {exports: {}}; + +/*! + * normalize-path + * + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. + */ + +var normalizePath$2 = function(path, stripTrailing) { + if (typeof path !== 'string') { + throw new TypeError('expected path to be a string'); + } + + if (path === '\\' || path === '/') return '/'; + + var len = path.length; + if (len <= 1) return path; + + // ensure that win32 namespaces has two leading slashes, so that the path is + // handled properly by the win32 version of path.parse() after being normalized + // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + var prefix = ''; + if (len > 4 && path[3] === '\\') { + var ch = path[2]; + if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { + path = path.slice(2); + prefix = '//'; + } + } + + var segs = path.split(/[/\\]+/); + if (stripTrailing !== false && segs[segs.length - 1] === '') { + segs.pop(); + } + return prefix + segs.join('/'); +}; + +Object.defineProperty(anymatch$2.exports, "__esModule", { value: true }); + +const picomatch = picomatch$3; +const normalizePath$1 = normalizePath$2; + +/** + * @typedef {(testString: string) => boolean} AnymatchFn + * @typedef {string|RegExp|AnymatchFn} AnymatchPattern + * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher + */ +const BANG$1 = '!'; +const DEFAULT_OPTIONS = {returnIndex: false}; +const arrify$1 = (item) => Array.isArray(item) ? item : [item]; + +/** + * @param {AnymatchPattern} matcher + * @param {object} options + * @returns {AnymatchFn} + */ +const createPattern = (matcher, options) => { + if (typeof matcher === 'function') { + return matcher; + } + if (typeof matcher === 'string') { + const glob = picomatch(matcher, options); + return (string) => matcher === string || glob(string); + } + if (matcher instanceof RegExp) { + return (string) => matcher.test(string); + } + return (string) => false; +}; + +/** + * @param {Array} patterns + * @param {Array} negPatterns + * @param {String|Array} args + * @param {Boolean} returnIndex + * @returns {boolean|number} + */ +const matchPatterns = (patterns, negPatterns, args, returnIndex) => { + const isList = Array.isArray(args); + const _path = isList ? args[0] : args; + if (!isList && typeof _path !== 'string') { + throw new TypeError('anymatch: second argument must be a string: got ' + + Object.prototype.toString.call(_path)) + } + const path = normalizePath$1(_path); + + for (let index = 0; index < negPatterns.length; index++) { + const nglob = negPatterns[index]; + if (nglob(path)) { + return returnIndex ? -1 : false; + } + } + + const applied = isList && [path].concat(args.slice(1)); + for (let index = 0; index < patterns.length; index++) { + const pattern = patterns[index]; + if (isList ? pattern(...applied) : pattern(path)) { + return returnIndex ? index : true; + } + } + + return returnIndex ? -1 : false; +}; + +/** + * @param {AnymatchMatcher} matchers + * @param {Array|string} testString + * @param {object} options + * @returns {boolean|number|Function} + */ +const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => { + if (matchers == null) { + throw new TypeError('anymatch: specify first argument'); + } + const opts = typeof options === 'boolean' ? {returnIndex: options} : options; + const returnIndex = opts.returnIndex || false; + + // Early cache for matchers. + const mtchers = arrify$1(matchers); + const negatedGlobs = mtchers + .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1) + .map(item => item.slice(1)) + .map(item => picomatch(item, opts)); + const patterns = mtchers + .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1)) + .map(matcher => createPattern(matcher, opts)); + + if (testString == null) { + return (testString, ri = false) => { + const returnIndex = typeof ri === 'boolean' ? ri : false; + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); + } + } + + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); +}; + +anymatch$1.default = anymatch$1; +anymatch$2.exports = anymatch$1; + +var require$$0 = [ + "3dm", + "3ds", + "3g2", + "3gp", + "7z", + "a", + "aac", + "adp", + "ai", + "aif", + "aiff", + "alz", + "ape", + "apk", + "appimage", + "ar", + "arj", + "asf", + "au", + "avi", + "bak", + "baml", + "bh", + "bin", + "bk", + "bmp", + "btif", + "bz2", + "bzip2", + "cab", + "caf", + "cgm", + "class", + "cmx", + "cpio", + "cr2", + "cur", + "dat", + "dcm", + "deb", + "dex", + "djvu", + "dll", + "dmg", + "dng", + "doc", + "docm", + "docx", + "dot", + "dotm", + "dra", + "DS_Store", + "dsk", + "dts", + "dtshd", + "dvb", + "dwg", + "dxf", + "ecelp4800", + "ecelp7470", + "ecelp9600", + "egg", + "eol", + "eot", + "epub", + "exe", + "f4v", + "fbs", + "fh", + "fla", + "flac", + "flatpak", + "fli", + "flv", + "fpx", + "fst", + "fvt", + "g3", + "gh", + "gif", + "graffle", + "gz", + "gzip", + "h261", + "h263", + "h264", + "icns", + "ico", + "ief", + "img", + "ipa", + "iso", + "jar", + "jpeg", + "jpg", + "jpgv", + "jpm", + "jxr", + "key", + "ktx", + "lha", + "lib", + "lvp", + "lz", + "lzh", + "lzma", + "lzo", + "m3u", + "m4a", + "m4v", + "mar", + "mdi", + "mht", + "mid", + "midi", + "mj2", + "mka", + "mkv", + "mmr", + "mng", + "mobi", + "mov", + "movie", + "mp3", + "mp4", + "mp4a", + "mpeg", + "mpg", + "mpga", + "mxu", + "nef", + "npx", + "numbers", + "nupkg", + "o", + "odp", + "ods", + "odt", + "oga", + "ogg", + "ogv", + "otf", + "ott", + "pages", + "pbm", + "pcx", + "pdb", + "pdf", + "pea", + "pgm", + "pic", + "png", + "pnm", + "pot", + "potm", + "potx", + "ppa", + "ppam", + "ppm", + "pps", + "ppsm", + "ppsx", + "ppt", + "pptm", + "pptx", + "psd", + "pya", + "pyc", + "pyo", + "pyv", + "qt", + "rar", + "ras", + "raw", + "resources", + "rgb", + "rip", + "rlc", + "rmf", + "rmvb", + "rpm", + "rtf", + "rz", + "s3m", + "s7z", + "scpt", + "sgi", + "shar", + "snap", + "sil", + "sketch", + "slk", + "smv", + "snk", + "so", + "stl", + "suo", + "sub", + "swf", + "tar", + "tbz", + "tbz2", + "tga", + "tgz", + "thmx", + "tif", + "tiff", + "tlz", + "ttc", + "ttf", + "txz", + "udf", + "uvh", + "uvi", + "uvm", + "uvp", + "uvs", + "uvu", + "viv", + "vob", + "war", + "wav", + "wax", + "wbmp", + "wdp", + "weba", + "webm", + "webp", + "whl", + "wim", + "wm", + "wma", + "wmv", + "wmx", + "woff", + "woff2", + "wrm", + "wvx", + "xbm", + "xif", + "xla", + "xlam", + "xls", + "xlsb", + "xlsm", + "xlsx", + "xlt", + "xltm", + "xltx", + "xm", + "xmind", + "xpi", + "xpm", + "xwd", + "xz", + "z", + "zip", + "zipx" +]; + +var binaryExtensions$1 = require$$0; + +const path$a = path__default; +const binaryExtensions = binaryExtensions$1; + +const extensions = new Set(binaryExtensions); + +var isBinaryPath$1 = filePath => extensions.has(path$a.extname(filePath).slice(1).toLowerCase()); + +var constants$1 = {}; + +(function (exports) { + +const {sep} = path__default; +const {platform} = process; +const os = require$$0__default$1; + +exports.EV_ALL = 'all'; +exports.EV_READY = 'ready'; +exports.EV_ADD = 'add'; +exports.EV_CHANGE = 'change'; +exports.EV_ADD_DIR = 'addDir'; +exports.EV_UNLINK = 'unlink'; +exports.EV_UNLINK_DIR = 'unlinkDir'; +exports.EV_RAW = 'raw'; +exports.EV_ERROR = 'error'; + +exports.STR_DATA = 'data'; +exports.STR_END = 'end'; +exports.STR_CLOSE = 'close'; + +exports.FSEVENT_CREATED = 'created'; +exports.FSEVENT_MODIFIED = 'modified'; +exports.FSEVENT_DELETED = 'deleted'; +exports.FSEVENT_MOVED = 'moved'; +exports.FSEVENT_CLONED = 'cloned'; +exports.FSEVENT_UNKNOWN = 'unknown'; +exports.FSEVENT_TYPE_FILE = 'file'; +exports.FSEVENT_TYPE_DIRECTORY = 'directory'; +exports.FSEVENT_TYPE_SYMLINK = 'symlink'; + +exports.KEY_LISTENERS = 'listeners'; +exports.KEY_ERR = 'errHandlers'; +exports.KEY_RAW = 'rawEmitters'; +exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW]; + +exports.DOT_SLASH = `.${sep}`; + +exports.BACK_SLASH_RE = /\\/g; +exports.DOUBLE_SLASH_RE = /\/\//; +exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/; +exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; +exports.REPLACER_RE = /^\.[/\\]/; + +exports.SLASH = '/'; +exports.SLASH_SLASH = '//'; +exports.BRACE_START = '{'; +exports.BANG = '!'; +exports.ONE_DOT = '.'; +exports.TWO_DOTS = '..'; +exports.STAR = '*'; +exports.GLOBSTAR = '**'; +exports.ROOT_GLOBSTAR = '/**/*'; +exports.SLASH_GLOBSTAR = '/**'; +exports.DIR_SUFFIX = 'Dir'; +exports.ANYMATCH_OPTS = {dot: true}; +exports.STRING_TYPE = 'string'; +exports.FUNCTION_TYPE = 'function'; +exports.EMPTY_STR = ''; +exports.EMPTY_FN = () => {}; +exports.IDENTITY_FN = val => val; + +exports.isWindows = platform === 'win32'; +exports.isMacos = platform === 'darwin'; +exports.isLinux = platform === 'linux'; +exports.isIBMi = os.type() === 'OS400'; +}(constants$1)); + +const fs$a = fs__default; +const sysPath$2 = path__default; +const { promisify: promisify$3 } = require$$0__default$3; +const isBinaryPath = isBinaryPath$1; +const { + isWindows: isWindows$2, + isLinux, + EMPTY_FN: EMPTY_FN$2, + EMPTY_STR: EMPTY_STR$1, + KEY_LISTENERS, + KEY_ERR, + KEY_RAW, + HANDLER_KEYS, + EV_CHANGE: EV_CHANGE$2, + EV_ADD: EV_ADD$2, + EV_ADD_DIR: EV_ADD_DIR$2, + EV_ERROR: EV_ERROR$2, + STR_DATA: STR_DATA$1, + STR_END: STR_END$2, + BRACE_START: BRACE_START$1, + STAR +} = constants$1; + +const THROTTLE_MODE_WATCH = 'watch'; + +const open$1 = promisify$3(fs$a.open); +const stat$2 = promisify$3(fs$a.stat); +const lstat$1 = promisify$3(fs$a.lstat); +const close = promisify$3(fs$a.close); +const fsrealpath = promisify$3(fs$a.realpath); + +const statMethods$1 = { lstat: lstat$1, stat: stat$2 }; + +// TODO: emit errors properly. Example: EMFILE on Macos. +const foreach = (val, fn) => { + if (val instanceof Set) { + val.forEach(fn); + } else { + fn(val); + } +}; + +const addAndConvert = (main, prop, item) => { + let container = main[prop]; + if (!(container instanceof Set)) { + main[prop] = container = new Set([container]); + } + container.add(item); +}; + +const clearItem = cont => key => { + const set = cont[key]; + if (set instanceof Set) { + set.clear(); + } else { + delete cont[key]; + } +}; + +const delFromSet = (main, prop, item) => { + const container = main[prop]; + if (container instanceof Set) { + container.delete(item); + } else if (container === item) { + delete main[prop]; + } +}; + +const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; + +/** + * @typedef {String} Path + */ + +// fs_watch helpers + +// object to hold per-process fs_watch instances +// (may be shared across chokidar FSWatcher instances) + +/** + * @typedef {Object} FsWatchContainer + * @property {Set} listeners + * @property {Set} errHandlers + * @property {Set} rawEmitters + * @property {fs.FSWatcher=} watcher + * @property {Boolean=} watcherUnusable + */ + +/** + * @type {Map} + */ +const FsWatchInstances = new Map(); + +/** + * Instantiates the fs_watch interface + * @param {String} path to be watched + * @param {Object} options to be passed to fs_watch + * @param {Function} listener main event handler + * @param {Function} errHandler emits info about errors + * @param {Function} emitRaw emits raw event data + * @returns {fs.FSWatcher} new fsevents instance + */ +function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { + const handleEvent = (rawEvent, evPath) => { + listener(path); + emitRaw(rawEvent, evPath, {watchedPath: path}); + + // emit based on events occurring for files from a directory's watcher in + // case the file's watcher misses it (and rely on throttling to de-dupe) + if (evPath && path !== evPath) { + fsWatchBroadcast( + sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath) + ); + } + }; + try { + return fs$a.watch(path, options, handleEvent); + } catch (error) { + errHandler(error); + } +} + +/** + * Helper for passing fs_watch event data to a collection of listeners + * @param {Path} fullPath absolute path bound to fs_watch instance + * @param {String} type listener type + * @param {*=} val1 arguments to be passed to listeners + * @param {*=} val2 + * @param {*=} val3 + */ +const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => { + const cont = FsWatchInstances.get(fullPath); + if (!cont) return; + foreach(cont[type], (listener) => { + listener(val1, val2, val3); + }); +}; + +/** + * Instantiates the fs_watch interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path + * @param {String} fullPath absolute path + * @param {Object} options to be passed to fs_watch + * @param {Object} handlers container for event listener functions + */ +const setFsWatchListener = (path, fullPath, options, handlers) => { + const {listener, errHandler, rawEmitter} = handlers; + let cont = FsWatchInstances.get(fullPath); + + /** @type {fs.FSWatcher=} */ + let watcher; + if (!options.persistent) { + watcher = createFsWatchInstance( + path, options, listener, errHandler, rawEmitter + ); + return watcher.close.bind(watcher); + } + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_ERR, errHandler); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + watcher = createFsWatchInstance( + path, + options, + fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), + errHandler, // no need to use broadcast here + fsWatchBroadcast.bind(null, fullPath, KEY_RAW) + ); + if (!watcher) return; + watcher.on(EV_ERROR$2, async (error) => { + const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); + cont.watcherUnusable = true; // documented since Node 10.4.1 + // Workaround for https://github.com/joyent/node/issues/4337 + if (isWindows$2 && error.code === 'EPERM') { + try { + const fd = await open$1(path, 'r'); + await close(fd); + broadcastErr(error); + } catch (err) {} + } else { + broadcastErr(error); + } + }); + cont = { + listeners: listener, + errHandlers: errHandler, + rawEmitters: rawEmitter, + watcher + }; + FsWatchInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // removes this instance's listeners and closes the underlying fs_watch + // instance if there are no more listeners left + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_ERR, errHandler); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + // Check to protect against issue gh-730. + // if (cont.watcherUnusable) { + cont.watcher.close(); + // } + FsWatchInstances.delete(fullPath); + HANDLER_KEYS.forEach(clearItem(cont)); + cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +// fs_watchFile helpers + +// object to hold per-process fs_watchFile instances +// (may be shared across chokidar FSWatcher instances) +const FsWatchFileInstances = new Map(); + +/** + * Instantiates the fs_watchFile interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path to be watched + * @param {String} fullPath absolute path + * @param {Object} options options to be passed to fs_watchFile + * @param {Object} handlers container for event listener functions + * @returns {Function} closer + */ +const setFsWatchFileListener = (path, fullPath, options, handlers) => { + const {listener, rawEmitter} = handlers; + let cont = FsWatchFileInstances.get(fullPath); + + const copts = cont && cont.options; + if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { + fs$a.unwatchFile(fullPath); + cont = undefined; + } + + /* eslint-enable no-unused-vars, prefer-destructuring */ + + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + // TODO + // listeners.add(listener); + // rawEmitters.add(rawEmitter); + cont = { + listeners: listener, + rawEmitters: rawEmitter, + options, + watcher: fs$a.watchFile(fullPath, options, (curr, prev) => { + foreach(cont.rawEmitters, (rawEmitter) => { + rawEmitter(EV_CHANGE$2, fullPath, {curr, prev}); + }); + const currmtime = curr.mtimeMs; + if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { + foreach(cont.listeners, (listener) => listener(path, curr)); + } + }) + }; + FsWatchFileInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // Removes this instance's listeners and closes the underlying fs_watchFile + // instance if there are no more listeners left. + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + FsWatchFileInstances.delete(fullPath); + fs$a.unwatchFile(fullPath); + cont.options = cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +/** + * @mixin + */ +class NodeFsHandler$1 { + +/** + * @param {import("../index").FSWatcher} fsW + */ +constructor(fsW) { + this.fsw = fsW; + this._boundHandleError = (error) => fsW._handleError(error); +} + +/** + * Watch file for changes with fs_watchFile or fs_watch. + * @param {String} path to file or dir + * @param {Function} listener on fs change + * @returns {Function} closer for the watcher instance + */ +_watchWithNodeFs(path, listener) { + const opts = this.fsw.options; + const directory = sysPath$2.dirname(path); + const basename = sysPath$2.basename(path); + const parent = this.fsw._getWatchedDir(directory); + parent.add(basename); + const absolutePath = sysPath$2.resolve(path); + const options = {persistent: opts.persistent}; + if (!listener) listener = EMPTY_FN$2; + + let closer; + if (opts.usePolling) { + options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? + opts.binaryInterval : opts.interval; + closer = setFsWatchFileListener(path, absolutePath, options, { + listener, + rawEmitter: this.fsw._emitRaw + }); + } else { + closer = setFsWatchListener(path, absolutePath, options, { + listener, + errHandler: this._boundHandleError, + rawEmitter: this.fsw._emitRaw + }); + } + return closer; +} + +/** + * Watch a file and emit add event if warranted. + * @param {Path} file Path + * @param {fs.Stats} stats result of fs_stat + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @returns {Function} closer for the watcher instance + */ +_handleFile(file, stats, initialAdd) { + if (this.fsw.closed) { + return; + } + const dirname = sysPath$2.dirname(file); + const basename = sysPath$2.basename(file); + const parent = this.fsw._getWatchedDir(dirname); + // stats is always present + let prevStats = stats; + + // if the file is already being watched, do nothing + if (parent.has(basename)) return; + + const listener = async (path, newStats) => { + if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return; + if (!newStats || newStats.mtimeMs === 0) { + try { + const newStats = await stat$2(file); + if (this.fsw.closed) return; + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE$2, file, newStats); + } + if (isLinux && prevStats.ino !== newStats.ino) { + this.fsw._closeFile(path); + prevStats = newStats; + this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener)); + } else { + prevStats = newStats; + } + } catch (error) { + // Fix issues where mtime is null but file is still present + this.fsw._remove(dirname, basename); + } + // add is about to be emitted if file not already tracked in parent + } else if (parent.has(basename)) { + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE$2, file, newStats); + } + prevStats = newStats; + } + }; + // kick off the watcher + const closer = this._watchWithNodeFs(file, listener); + + // emit an add event if we're supposed to + if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { + if (!this.fsw._throttle(EV_ADD$2, file, 0)) return; + this.fsw._emit(EV_ADD$2, file, stats); + } + + return closer; +} + +/** + * Handle symlinks encountered while reading a dir. + * @param {Object} entry returned by readdirp + * @param {String} directory path of dir being read + * @param {String} path of this item + * @param {String} item basename of this item + * @returns {Promise} true if no more processing is needed for this entry. + */ +async _handleSymlink(entry, directory, path, item) { + if (this.fsw.closed) { + return; + } + const full = entry.fullPath; + const dir = this.fsw._getWatchedDir(directory); + + if (!this.fsw.options.followSymlinks) { + // watch symlink directly (don't follow) and detect changes + this.fsw._incrReadyCount(); + const linkPath = await fsrealpath(path); + if (this.fsw.closed) return; + if (dir.has(item)) { + if (this.fsw._symlinkPaths.get(full) !== linkPath) { + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_CHANGE$2, path, entry.stats); + } + } else { + dir.add(item); + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_ADD$2, path, entry.stats); + } + this.fsw._emitReady(); + return true; + } + + // don't follow the same symlink more than once + if (this.fsw._symlinkPaths.has(full)) { + return true; + } + + this.fsw._symlinkPaths.set(full, true); +} + +_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { + // Normalize the directory name on Windows + directory = sysPath$2.join(directory, EMPTY_STR$1); + + if (!wh.hasGlob) { + throttler = this.fsw._throttle('readdir', directory, 1000); + if (!throttler) return; + } + + const previous = this.fsw._getWatchedDir(wh.path); + const current = new Set(); + + let stream = this.fsw._readdirp(directory, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + depth: 0 + }).on(STR_DATA$1, async (entry) => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const item = entry.path; + let path = sysPath$2.join(directory, item); + current.add(item); + + if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) { + return; + } + + if (this.fsw.closed) { + stream = undefined; + return; + } + // Files that present in current directory snapshot + // but absent in previous are added to watch list and + // emit `add` event. + if (item === target || !target && !previous.has(item)) { + this.fsw._incrReadyCount(); + + // ensure relativeness of path is preserved in case of watcher reuse + path = sysPath$2.join(dir, sysPath$2.relative(dir, path)); + + this._addToNodeFs(path, initialAdd, wh, depth + 1); + } + }).on(EV_ERROR$2, this._boundHandleError); + + return new Promise(resolve => + stream.once(STR_END$2, () => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const wasThrottled = throttler ? throttler.clear() : false; + + resolve(); + + // Files that absent in current directory snapshot + // but present in previous emit `remove` event + // and are removed from @watched[directory]. + previous.getChildren().filter((item) => { + return item !== directory && + !current.has(item) && + // in case of intersecting globs; + // a path may have been filtered out of this readdir, but + // shouldn't be removed because it matches a different glob + (!wh.hasGlob || wh.filterPath({ + fullPath: sysPath$2.resolve(directory, item) + })); + }).forEach((item) => { + this.fsw._remove(directory, item); + }); + + stream = undefined; + + // one more time for any missed in case changes came in extremely quickly + if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler); + }) + ); +} + +/** + * Read directory to add / remove files from `@watched` list and re-read it on change. + * @param {String} dir fs path + * @param {fs.Stats} stats + * @param {Boolean} initialAdd + * @param {Number} depth relative to user-supplied path + * @param {String} target child path targeted for watch + * @param {Object} wh Common watch helpers for this path + * @param {String} realpath + * @returns {Promise} closer for the watcher instance. + */ +async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) { + const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir)); + const tracked = parentDir.has(sysPath$2.basename(dir)); + if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { + if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats); + } + + // ensure dir is tracked (harmless if redundant) + parentDir.add(sysPath$2.basename(dir)); + this.fsw._getWatchedDir(dir); + let throttler; + let closer; + + const oDepth = this.fsw.options.depth; + if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) { + if (!target) { + await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); + if (this.fsw.closed) return; + } + + closer = this._watchWithNodeFs(dir, (dirPath, stats) => { + // if current directory is removed, do nothing + if (stats && stats.mtimeMs === 0) return; + + this._handleRead(dirPath, false, wh, target, dir, depth, throttler); + }); + } + return closer; +} + +/** + * Handle added file, directory, or glob pattern. + * Delegates call to _handleFile / _handleDir after checks. + * @param {String} path to file or ir + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @param {Object} priorWh depth relative to user-supplied path + * @param {Number} depth Child path actually targeted for watch + * @param {String=} target Child path actually targeted for watch + * @returns {Promise} + */ +async _addToNodeFs(path, initialAdd, priorWh, depth, target) { + const ready = this.fsw._emitReady; + if (this.fsw._isIgnored(path) || this.fsw.closed) { + ready(); + return false; + } + + const wh = this.fsw._getWatchHelpers(path, depth); + if (!wh.hasGlob && priorWh) { + wh.hasGlob = priorWh.hasGlob; + wh.globFilter = priorWh.globFilter; + wh.filterPath = entry => priorWh.filterPath(entry); + wh.filterDir = entry => priorWh.filterDir(entry); + } + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods$1[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + ready(); + return false; + } + + const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1); + let closer; + if (stats.isDirectory()) { + const absPath = sysPath$2.resolve(path); + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); + if (this.fsw.closed) return; + // preserve this symlink's target path + if (absPath !== targetPath && targetPath !== undefined) { + this.fsw._symlinkPaths.set(absPath, targetPath); + } + } else if (stats.isSymbolicLink()) { + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + const parent = sysPath$2.dirname(wh.watchPath); + this.fsw._getWatchedDir(parent).add(wh.watchPath); + this.fsw._emit(EV_ADD$2, wh.watchPath, stats); + closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath); + if (this.fsw.closed) return; + + // preserve this symlink's target path + if (targetPath !== undefined) { + this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath); + } + } else { + closer = this._handleFile(wh.watchPath, stats, initialAdd); + } + ready(); + + this.fsw._addPathCloser(path, closer); + return false; + + } catch (error) { + if (this.fsw._handleError(error)) { + ready(); + return path; + } + } +} + +} + +var nodefsHandler = NodeFsHandler$1; + +var fseventsHandler = {exports: {}}; + +const fs$9 = fs__default; +const sysPath$1 = path__default; +const { promisify: promisify$2 } = require$$0__default$3; + +let fsevents; +try { + fsevents = eval('require')('fsevents'); +} catch (error) { + if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error); +} + +if (fsevents) { + // TODO: real check + const mtch = process.version.match(/v(\d+)\.(\d+)/); + if (mtch && mtch[1] && mtch[2]) { + const maj = Number.parseInt(mtch[1], 10); + const min = Number.parseInt(mtch[2], 10); + if (maj === 8 && min < 16) { + fsevents = undefined; + } + } +} + +const { + EV_ADD: EV_ADD$1, + EV_CHANGE: EV_CHANGE$1, + EV_ADD_DIR: EV_ADD_DIR$1, + EV_UNLINK: EV_UNLINK$1, + EV_ERROR: EV_ERROR$1, + STR_DATA, + STR_END: STR_END$1, + FSEVENT_CREATED, + FSEVENT_MODIFIED, + FSEVENT_DELETED, + FSEVENT_MOVED, + // FSEVENT_CLONED, + FSEVENT_UNKNOWN, + FSEVENT_TYPE_FILE, + FSEVENT_TYPE_DIRECTORY, + FSEVENT_TYPE_SYMLINK, + + ROOT_GLOBSTAR, + DIR_SUFFIX, + DOT_SLASH, + FUNCTION_TYPE: FUNCTION_TYPE$1, + EMPTY_FN: EMPTY_FN$1, + IDENTITY_FN +} = constants$1; + +const Depth = (value) => isNaN(value) ? {} : {depth: value}; + +const stat$1 = promisify$2(fs$9.stat); +const lstat = promisify$2(fs$9.lstat); +const realpath = promisify$2(fs$9.realpath); + +const statMethods = { stat: stat$1, lstat }; + +/** + * @typedef {String} Path + */ + +/** + * @typedef {Object} FsEventsWatchContainer + * @property {Set} listeners + * @property {Function} rawEmitter + * @property {{stop: Function}} watcher + */ + +// fsevents instance helper functions +/** + * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances) + * @type {Map} + */ +const FSEventsWatchers = new Map(); + +// Threshold of duplicate path prefixes at which to start +// consolidating going forward +const consolidateThreshhold = 10; + +const wrongEventFlags = new Set([ + 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912 +]); + +/** + * Instantiates the fsevents interface + * @param {Path} path path to be watched + * @param {Function} callback called when fsevents is bound and ready + * @returns {{stop: Function}} new fsevents instance + */ +const createFSEventsInstance = (path, callback) => { + const stop = fsevents.watch(path, callback); + return {stop}; +}; + +/** + * Instantiates the fsevents interface or binds listeners to an existing one covering + * the same file tree. + * @param {Path} path - to be watched + * @param {Path} realPath - real path for symlinks + * @param {Function} listener - called when fsevents emits events + * @param {Function} rawEmitter - passes data to listeners of the 'raw' event + * @returns {Function} closer + */ +function setFSEventsListener(path, realPath, listener, rawEmitter) { + let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath; + + const parentPath = sysPath$1.dirname(watchPath); + let cont = FSEventsWatchers.get(watchPath); + + // If we've accumulated a substantial number of paths that + // could have been consolidated by watching one directory + // above the current one, create a watcher on the parent + // path instead, so that we do consolidate going forward. + if (couldConsolidate(parentPath)) { + watchPath = parentPath; + } + + const resolvedPath = sysPath$1.resolve(path); + const hasSymlink = resolvedPath !== realPath; + + const filteredListener = (fullPath, flags, info) => { + if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath); + if ( + fullPath === resolvedPath || + !fullPath.indexOf(resolvedPath + sysPath$1.sep) + ) listener(fullPath, flags, info); + }; + + // check if there is already a watcher on a parent path + // modifies `watchPath` to the parent path when it finds a match + let watchedParent = false; + for (const watchedPath of FSEventsWatchers.keys()) { + if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) { + watchPath = watchedPath; + cont = FSEventsWatchers.get(watchPath); + watchedParent = true; + break; + } + } + + if (cont || watchedParent) { + cont.listeners.add(filteredListener); + } else { + cont = { + listeners: new Set([filteredListener]), + rawEmitter, + watcher: createFSEventsInstance(watchPath, (fullPath, flags) => { + if (!cont.listeners.size) return; + const info = fsevents.getInfo(fullPath, flags); + cont.listeners.forEach(list => { + list(fullPath, flags, info); + }); + + cont.rawEmitter(info.event, fullPath, info); + }) + }; + FSEventsWatchers.set(watchPath, cont); + } + + // removes this instance's listeners and closes the underlying fsevents + // instance if there are no more listeners left + return () => { + const lst = cont.listeners; + + lst.delete(filteredListener); + if (!lst.size) { + FSEventsWatchers.delete(watchPath); + if (cont.watcher) return cont.watcher.stop().then(() => { + cont.rawEmitter = cont.watcher = undefined; + Object.freeze(cont); + }); + } + }; +} + +// Decide whether or not we should start a new higher-level +// parent watcher +const couldConsolidate = (path) => { + let count = 0; + for (const watchPath of FSEventsWatchers.keys()) { + if (watchPath.indexOf(path) === 0) { + count++; + if (count >= consolidateThreshhold) { + return true; + } + } + } + + return false; +}; + +// returns boolean indicating whether fsevents can be used +const canUse = () => fsevents && FSEventsWatchers.size < 128; + +// determines subdirectory traversal levels from root to path +const calcDepth = (path, root) => { + let i = 0; + while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++; + return i; +}; + +// returns boolean indicating whether the fsevents' event info has the same type +// as the one returned by fs.stat +const sameTypes = (info, stats) => ( + info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || + info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || + info.type === FSEVENT_TYPE_FILE && stats.isFile() +); + +/** + * @mixin + */ +class FsEventsHandler$1 { + +/** + * @param {import('../index').FSWatcher} fsw + */ +constructor(fsw) { + this.fsw = fsw; +} +checkIgnored(path, stats) { + const ipaths = this.fsw._ignoredPaths; + if (this.fsw._isIgnored(path, stats)) { + ipaths.add(path); + if (stats && stats.isDirectory()) { + ipaths.add(path + ROOT_GLOBSTAR); + } + return true; + } + + ipaths.delete(path); + ipaths.delete(path + ROOT_GLOBSTAR); +} + +addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1; + this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts); +} + +async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + try { + const stats = await stat$1(path); + if (this.fsw.closed) return; + if (sameTypes(info, stats)) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } catch (error) { + if (error.code === 'EACCES') { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } +} + +handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) { + if (this.fsw.closed || this.checkIgnored(path)) return; + + if (event === EV_UNLINK$1) { + const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY; + // suppress unlink events on never before seen files + if (isDirectory || watchedDir.has(item)) { + this.fsw._remove(parent, item, isDirectory); + } + } else { + if (event === EV_ADD$1) { + // track new directories + if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path); + + if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) { + // push symlinks back to the top of the stack to get handled + const curDepth = opts.depth === undefined ? + undefined : calcDepth(fullPath, realPath) + 1; + return this._addToFsEvents(path, false, true, curDepth); + } + + // track new paths + // (other than symlinks being followed, which will be tracked soon) + this.fsw._getWatchedDir(parent).add(item); + } + /** + * @type {'add'|'addDir'|'unlink'|'unlinkDir'} + */ + const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event; + this.fsw._emit(eventName, path); + if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true); + } +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} watchPath - file/dir path to be watched with fsevents + * @param {String} realPath - real path (in case of symlinks) + * @param {Function} transform - path transformer + * @param {Function} globFilter - path filter in case a glob pattern was provided + * @returns {Function} closer for the watcher instance +*/ +_watchWithFsEvents(watchPath, realPath, transform, globFilter) { + if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return; + const opts = this.fsw.options; + const watchCallback = async (fullPath, flags, info) => { + if (this.fsw.closed) return; + if ( + opts.depth !== undefined && + calcDepth(fullPath, realPath) > opts.depth + ) return; + const path = transform(sysPath$1.join( + watchPath, sysPath$1.relative(watchPath, fullPath) + )); + if (globFilter && !globFilter(path)) return; + // ensure directories are tracked + const parent = sysPath$1.dirname(path); + const item = sysPath$1.basename(path); + const watchedDir = this.fsw._getWatchedDir( + info.type === FSEVENT_TYPE_DIRECTORY ? path : parent + ); + + // correct for wrong events emitted + if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) { + if (typeof opts.ignored === FUNCTION_TYPE$1) { + let stats; + try { + stats = await stat$1(path); + } catch (error) {} + if (this.fsw.closed) return; + if (this.checkIgnored(path, stats)) return; + if (sameTypes(info, stats)) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + switch (info.event) { + case FSEVENT_CREATED: + case FSEVENT_MODIFIED: + return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + case FSEVENT_DELETED: + case FSEVENT_MOVED: + return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } + }; + + const closer = setFSEventsListener( + watchPath, + realPath, + watchCallback, + this.fsw._emitRaw + ); + + this.fsw._emitReady(); + return closer; +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} linkPath path to symlink + * @param {String} fullPath absolute path to the symlink + * @param {Function} transform pre-existing path transformer + * @param {Number} curDepth level of subdirectories traversed to where symlink is + * @returns {Promise} + */ +async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) { + // don't follow the same symlink more than once + if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return; + + this.fsw._symlinkPaths.set(fullPath, true); + this.fsw._incrReadyCount(); + + try { + const linkTarget = await realpath(linkPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(linkTarget)) { + return this.fsw._emitReady(); + } + + this.fsw._incrReadyCount(); + + // add the linkTarget for watching with a wrapper for transform + // that causes emitted paths to incorporate the link's path + this._addToFsEvents(linkTarget || linkPath, (path) => { + let aliasedPath = linkPath; + if (linkTarget && linkTarget !== DOT_SLASH) { + aliasedPath = path.replace(linkTarget, linkPath); + } else if (path !== DOT_SLASH) { + aliasedPath = sysPath$1.join(linkPath, path); + } + return transform(aliasedPath); + }, false, curDepth); + } catch(error) { + if (this.fsw._handleError(error)) { + return this.fsw._emitReady(); + } + } +} + +/** + * + * @param {Path} newPath + * @param {fs.Stats} stats + */ +emitAdd(newPath, stats, processPath, opts, forceAdd) { + const pp = processPath(newPath); + const isDir = stats.isDirectory(); + const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp)); + const base = sysPath$1.basename(pp); + + // ensure empty dirs get tracked + if (isDir) this.fsw._getWatchedDir(pp); + if (dirObj.has(base)) return; + dirObj.add(base); + + if (!opts.ignoreInitial || forceAdd === true) { + this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats); + } +} + +initWatch(realPath, path, wh, processPath) { + if (this.fsw.closed) return; + const closer = this._watchWithFsEvents( + wh.watchPath, + sysPath$1.resolve(realPath || wh.watchPath), + processPath, + wh.globFilter + ); + this.fsw._addPathCloser(path, closer); +} + +/** + * Handle added path with fsevents + * @param {String} path file/dir path or glob pattern + * @param {Function|Boolean=} transform converts working path to what the user expects + * @param {Boolean=} forceAdd ensure add is emitted + * @param {Number=} priorDepth Level of subdirectories already traversed. + * @returns {Promise} + */ +async _addToFsEvents(path, transform, forceAdd, priorDepth) { + if (this.fsw.closed) { + return; + } + const opts = this.fsw.options; + const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN; + + const wh = this.fsw._getWatchHelpers(path); + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + throw null; + } + if (stats.isDirectory()) { + // emit addDir unless this is a glob parent + if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd); + + // don't recurse further if it would exceed depth setting + if (priorDepth && priorDepth > opts.depth) return; + + // scan the contents of the dir + this.fsw._readdirp(wh.watchPath, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + ...Depth(opts.depth - (priorDepth || 0)) + }).on(STR_DATA, (entry) => { + // need to check filterPath on dirs b/c filterDir is less restrictive + if (this.fsw.closed) { + return; + } + if (entry.stats.isDirectory() && !wh.filterPath(entry)) return; + + const joinedPath = sysPath$1.join(wh.watchPath, entry.path); + const {fullPath} = entry; + + if (wh.followSymlinks && entry.stats.isSymbolicLink()) { + // preserve the current depth here since it can't be derived from + // real paths past the symlink + const curDepth = opts.depth === undefined ? + undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1; + + this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth); + } else { + this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd); + } + }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => { + this.fsw._emitReady(); + }); + } else { + this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd); + this.fsw._emitReady(); + } + } catch (error) { + if (!error || this.fsw._handleError(error)) { + // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__- + this.fsw._emitReady(); + this.fsw._emitReady(); + } + } + + if (opts.persistent && forceAdd !== true) { + if (typeof transform === FUNCTION_TYPE$1) { + // realpath has already been resolved + this.initWatch(undefined, path, wh, processPath); + } else { + let realPath; + try { + realPath = await realpath(wh.watchPath); + } catch (e) {} + this.initWatch(realPath, path, wh, processPath); + } + } +} + +} + +fseventsHandler.exports = FsEventsHandler$1; +fseventsHandler.exports.canUse = canUse; + +const { EventEmitter: EventEmitter$2 } = require$$0__default$6; +const fs$8 = fs__default; +const sysPath = path__default; +const { promisify: promisify$1 } = require$$0__default$3; +const readdirp = readdirp_1; +const anymatch = anymatch$2.exports.default; +const globParent = globParent$2; +const isGlob = isGlob$2; +const braces = braces_1; +const normalizePath = normalizePath$2; + +const NodeFsHandler = nodefsHandler; +const FsEventsHandler = fseventsHandler.exports; +const { + EV_ALL, + EV_READY, + EV_ADD, + EV_CHANGE, + EV_UNLINK, + EV_ADD_DIR, + EV_UNLINK_DIR, + EV_RAW, + EV_ERROR, + + STR_CLOSE, + STR_END, + + BACK_SLASH_RE, + DOUBLE_SLASH_RE, + SLASH_OR_BACK_SLASH_RE, + DOT_RE, + REPLACER_RE, + + SLASH, + SLASH_SLASH, + BRACE_START, + BANG, + ONE_DOT, + TWO_DOTS, + GLOBSTAR, + SLASH_GLOBSTAR, + ANYMATCH_OPTS, + STRING_TYPE, + FUNCTION_TYPE, + EMPTY_STR, + EMPTY_FN, + + isWindows: isWindows$1, + isMacos, + isIBMi +} = constants$1; + +const stat = promisify$1(fs$8.stat); +const readdir = promisify$1(fs$8.readdir); + +/** + * @typedef {String} Path + * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName + * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType + */ + +/** + * + * @typedef {Object} WatchHelpers + * @property {Boolean} followSymlinks + * @property {'stat'|'lstat'} statMethod + * @property {Path} path + * @property {Path} watchPath + * @property {Function} entryPath + * @property {Boolean} hasGlob + * @property {Object} globFilter + * @property {Function} filterPath + * @property {Function} filterDir + */ + +const arrify = (value = []) => Array.isArray(value) ? value : [value]; +const flatten = (list, result = []) => { + list.forEach(item => { + if (Array.isArray(item)) { + flatten(item, result); + } else { + result.push(item); + } + }); + return result; +}; + +const unifyPaths = (paths_) => { + /** + * @type {Array} + */ + const paths = flatten(arrify(paths_)); + if (!paths.every(p => typeof p === STRING_TYPE)) { + throw new TypeError(`Non-string provided as watch path: ${paths}`); + } + return paths.map(normalizePathToUnix); +}; + +// If SLASH_SLASH occurs at the beginning of path, it is not replaced +// because "//StoragePC/DrivePool/Movies" is a valid network path +const toUnix = (string) => { + let str = string.replace(BACK_SLASH_RE, SLASH); + let prepend = false; + if (str.startsWith(SLASH_SLASH)) { + prepend = true; + } + while (str.match(DOUBLE_SLASH_RE)) { + str = str.replace(DOUBLE_SLASH_RE, SLASH); + } + if (prepend) { + str = SLASH + str; + } + return str; +}; + +// Our version of upath.normalize +// TODO: this is not equal to path-normalize module - investigate why +const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path))); + +const normalizeIgnored = (cwd = EMPTY_STR) => (path) => { + if (typeof path !== STRING_TYPE) return path; + return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path)); +}; + +const getAbsolutePath = (path, cwd) => { + if (sysPath.isAbsolute(path)) { + return path; + } + if (path.startsWith(BANG)) { + return BANG + sysPath.join(cwd, path.slice(1)); + } + return sysPath.join(cwd, path); +}; + +const undef = (opts, key) => opts[key] === undefined; + +/** + * Directory entry. + * @property {Path} path + * @property {Set} items + */ +class DirEntry { + /** + * @param {Path} dir + * @param {Function} removeWatcher + */ + constructor(dir, removeWatcher) { + this.path = dir; + this._removeWatcher = removeWatcher; + /** @type {Set} */ + this.items = new Set(); + } + + add(item) { + const {items} = this; + if (!items) return; + if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item); + } + + async remove(item) { + const {items} = this; + if (!items) return; + items.delete(item); + if (items.size > 0) return; + + const dir = this.path; + try { + await readdir(dir); + } catch (err) { + if (this._removeWatcher) { + this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir)); + } + } + } + + has(item) { + const {items} = this; + if (!items) return; + return items.has(item); + } + + /** + * @returns {Array} + */ + getChildren() { + const {items} = this; + if (!items) return; + return [...items.values()]; + } + + dispose() { + this.items.clear(); + delete this.path; + delete this._removeWatcher; + delete this.items; + Object.freeze(this); + } +} + +const STAT_METHOD_F = 'stat'; +const STAT_METHOD_L = 'lstat'; +class WatchHelper { + constructor(path, watchPath, follow, fsw) { + this.fsw = fsw; + this.path = path = path.replace(REPLACER_RE, EMPTY_STR); + this.watchPath = watchPath; + this.fullWatchPath = sysPath.resolve(watchPath); + this.hasGlob = watchPath !== path; + /** @type {object|boolean} */ + if (path === EMPTY_STR) this.hasGlob = false; + this.globSymlink = this.hasGlob && follow ? undefined : false; + this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false; + this.dirParts = this.getDirParts(path); + this.dirParts.forEach((parts) => { + if (parts.length > 1) parts.pop(); + }); + this.followSymlinks = follow; + this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; + } + + checkGlobSymlink(entry) { + // only need to resolve once + // first entry should always have entry.parentDir === EMPTY_STR + if (this.globSymlink === undefined) { + this.globSymlink = entry.fullParentDir === this.fullWatchPath ? + false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath}; + } + + if (this.globSymlink) { + return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath); + } + + return entry.fullPath; + } + + entryPath(entry) { + return sysPath.join(this.watchPath, + sysPath.relative(this.watchPath, this.checkGlobSymlink(entry)) + ); + } + + filterPath(entry) { + const {stats} = entry; + if (stats && stats.isSymbolicLink()) return this.filterDir(entry); + const resolvedPath = this.entryPath(entry); + const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? + this.globFilter(resolvedPath) : true; + return matchesGlob && + this.fsw._isntIgnored(resolvedPath, stats) && + this.fsw._hasReadPermissions(stats); + } + + getDirParts(path) { + if (!this.hasGlob) return []; + const parts = []; + const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path]; + expandedPath.forEach((path) => { + parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE)); + }); + return parts; + } + + filterDir(entry) { + if (this.hasGlob) { + const entryParts = this.getDirParts(this.checkGlobSymlink(entry)); + let globstar = false; + this.unmatchedGlob = !this.dirParts.some((parts) => { + return parts.every((part, i) => { + if (part === GLOBSTAR) globstar = true; + return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS); + }); + }); + } + return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats); + } +} + +/** + * Watches files & directories for changes. Emitted events: + * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` + * + * new FSWatcher() + * .add(directories) + * .on('add', path => log('File', path, 'was added')) + */ +class FSWatcher extends EventEmitter$2 { +// Not indenting methods for history sake; for now. +constructor(_opts) { + super(); + + const opts = {}; + if (_opts) Object.assign(opts, _opts); // for frozen objects + + /** @type {Map} */ + this._watched = new Map(); + /** @type {Map} */ + this._closers = new Map(); + /** @type {Set} */ + this._ignoredPaths = new Set(); + + /** @type {Map} */ + this._throttled = new Map(); + + /** @type {Map} */ + this._symlinkPaths = new Map(); + + this._streams = new Set(); + this.closed = false; + + // Set up default options. + if (undef(opts, 'persistent')) opts.persistent = true; + if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false; + if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false; + if (undef(opts, 'interval')) opts.interval = 100; + if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300; + if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false; + opts.enableBinaryInterval = opts.binaryInterval !== opts.interval; + + // Enable fsevents on OS X when polling isn't explicitly enabled. + if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling; + + // If we can't use fsevents, ensure the options reflect it's disabled. + const canUseFsEvents = FsEventsHandler.canUse(); + if (!canUseFsEvents) opts.useFsEvents = false; + + // Use polling on Mac if not using fsevents. + // Other platforms use non-polling fs_watch. + if (undef(opts, 'usePolling') && !opts.useFsEvents) { + 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; + if (envPoll !== undefined) { + const envLower = envPoll.toLowerCase(); + + if (envLower === 'false' || envLower === '0') { + opts.usePolling = false; + } else if (envLower === 'true' || envLower === '1') { + opts.usePolling = true; + } else { + opts.usePolling = !!envLower; + } + } + const envInterval = process.env.CHOKIDAR_INTERVAL; + if (envInterval) { + opts.interval = Number.parseInt(envInterval, 10); + } + + // Editor atomic write normalization enabled by default with fs.watch + if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents; + if (opts.atomic) this._pendingUnlinks = new Map(); + + if (undef(opts, 'followSymlinks')) opts.followSymlinks = true; + + if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false; + if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {}; + const awf = opts.awaitWriteFinish; + if (awf) { + if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000; + if (!awf.pollInterval) awf.pollInterval = 100; + this._pendingWrites = new Map(); + } + if (opts.ignored) opts.ignored = arrify(opts.ignored); + + let readyCalls = 0; + this._emitReady = () => { + readyCalls++; + if (readyCalls >= this._readyCount) { + this._emitReady = EMPTY_FN; + this._readyEmitted = true; + // use process.nextTick to allow time for listener to be bound + process.nextTick(() => this.emit(EV_READY)); + } + }; + this._emitRaw = (...args) => this.emit(EV_RAW, ...args); + this._readyEmitted = false; + this.options = opts; + + // Initialize with proper watcher. + if (opts.useFsEvents) { + this._fsEventsHandler = new FsEventsHandler(this); + } else { + this._nodeFsHandler = new NodeFsHandler(this); + } + + // You’re frozen when your heart’s not open. + Object.freeze(opts); +} + +// Public methods + +/** + * Adds paths to be watched on an existing FSWatcher instance + * @param {Path|Array} paths_ + * @param {String=} _origAdd private; for handling non-existent paths to be watched + * @param {Boolean=} _internal private; indicates a non-user add + * @returns {FSWatcher} for chaining + */ +add(paths_, _origAdd, _internal) { + const {cwd, disableGlobbing} = this.options; + this.closed = false; + let paths = unifyPaths(paths_); + if (cwd) { + paths = paths.map((path) => { + const absPath = getAbsolutePath(path, cwd); + + // Check `path` instead of `absPath` because the cwd portion can't be a glob + if (disableGlobbing || !isGlob(path)) { + return absPath; + } + return normalizePath(absPath); + }); + } + + // set aside negated glob strings + paths = paths.filter((path) => { + if (path.startsWith(BANG)) { + this._ignoredPaths.add(path.slice(1)); + return false; + } + + // if a path is being added that was previously ignored, stop ignoring it + this._ignoredPaths.delete(path); + this._ignoredPaths.delete(path + SLASH_GLOBSTAR); + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + + return true; + }); + + if (this.options.useFsEvents && this._fsEventsHandler) { + if (!this._readyCount) this._readyCount = paths.length; + if (this.options.persistent) this._readyCount *= 2; + paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path)); + } else { + if (!this._readyCount) this._readyCount = 0; + this._readyCount += paths.length; + Promise.all( + paths.map(async path => { + const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd); + if (res) this._emitReady(); + return res; + }) + ).then(results => { + if (this.closed) return; + results.filter(item => item).forEach(item => { + this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item)); + }); + }); + } + + return this; +} + +/** + * Close watchers or start ignoring events from specified paths. + * @param {Path|Array} paths_ - string or array of strings, file/directory paths and/or globs + * @returns {FSWatcher} for chaining +*/ +unwatch(paths_) { + if (this.closed) return this; + const paths = unifyPaths(paths_); + const {cwd} = this.options; + + paths.forEach((path) => { + // convert to absolute path unless relative path already matches + if (!sysPath.isAbsolute(path) && !this._closers.has(path)) { + if (cwd) path = sysPath.join(cwd, path); + path = sysPath.resolve(path); + } + + this._closePath(path); + + this._ignoredPaths.add(path); + if (this._watched.has(path)) { + this._ignoredPaths.add(path + SLASH_GLOBSTAR); + } + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + }); + + return this; +} + +/** + * Close watchers and remove all listeners from watched paths. + * @returns {Promise}. +*/ +close() { + if (this.closed) return this._closePromise; + this.closed = true; + + // Memory management. + this.removeAllListeners(); + const closers = []; + this._closers.forEach(closerList => closerList.forEach(closer => { + const promise = closer(); + if (promise instanceof Promise) closers.push(promise); + })); + this._streams.forEach(stream => stream.destroy()); + this._userIgnored = undefined; + this._readyCount = 0; + this._readyEmitted = false; + this._watched.forEach(dirent => dirent.dispose()); + ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => { + this[`_${key}`].clear(); + }); + + this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve(); + return this._closePromise; +} + +/** + * Expose list of watched paths + * @returns {Object} for chaining +*/ +getWatched() { + const watchList = {}; + this._watched.forEach((entry, dir) => { + const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir; + watchList[key || ONE_DOT] = entry.getChildren().sort(); + }); + return watchList; +} + +emitWithAll(event, args) { + this.emit(...args); + if (event !== EV_ERROR) this.emit(EV_ALL, ...args); +} + +// Common helpers +// -------------- + +/** + * Normalize and emit events. + * Calling _emit DOES NOT MEAN emit() would be called! + * @param {EventName} event Type of event + * @param {Path} path File or directory path + * @param {*=} val1 arguments to be passed with event + * @param {*=} val2 + * @param {*=} val3 + * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +async _emit(event, path, val1, val2, val3) { + if (this.closed) return; + + const opts = this.options; + if (isWindows$1) path = sysPath.normalize(path); + if (opts.cwd) path = sysPath.relative(opts.cwd, path); + /** @type Array */ + const args = [event, path]; + if (val3 !== undefined) args.push(val1, val2, val3); + else if (val2 !== undefined) args.push(val1, val2); + else if (val1 !== undefined) args.push(val1); + + const awf = opts.awaitWriteFinish; + let pw; + if (awf && (pw = this._pendingWrites.get(path))) { + pw.lastChange = new Date(); + return this; + } + + if (opts.atomic) { + if (event === EV_UNLINK) { + this._pendingUnlinks.set(path, args); + setTimeout(() => { + this._pendingUnlinks.forEach((entry, path) => { + this.emit(...entry); + this.emit(EV_ALL, ...entry); + this._pendingUnlinks.delete(path); + }); + }, typeof opts.atomic === 'number' ? opts.atomic : 100); + return this; + } + if (event === EV_ADD && this._pendingUnlinks.has(path)) { + event = args[0] = EV_CHANGE; + this._pendingUnlinks.delete(path); + } + } + + if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) { + const awfEmit = (err, stats) => { + if (err) { + event = args[0] = EV_ERROR; + args[1] = err; + this.emitWithAll(event, args); + } else if (stats) { + // if stats doesn't exist the file must have been deleted + if (args.length > 2) { + args[2] = stats; + } else { + args.push(stats); + } + this.emitWithAll(event, args); + } + }; + + this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit); + return this; + } + + if (event === EV_CHANGE) { + const isThrottled = !this._throttle(EV_CHANGE, path, 50); + if (isThrottled) return this; + } + + if (opts.alwaysStat && val1 === undefined && + (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE) + ) { + const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path; + let stats; + try { + stats = await stat(fullPath); + } catch (err) {} + // Suppress event when fs_stat fails, to avoid sending undefined 'stat' + if (!stats || this.closed) return; + args.push(stats); + } + this.emitWithAll(event, args); + + return this; +} + +/** + * Common handler for errors + * @param {Error} error + * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +_handleError(error) { + const code = error && error.code; + if (error && code !== 'ENOENT' && code !== 'ENOTDIR' && + (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES')) + ) { + this.emit(EV_ERROR, error); + } + return error || this.closed; +} + +/** + * Helper utility for throttling + * @param {ThrottleType} actionType type being throttled + * @param {Path} path being acted upon + * @param {Number} timeout duration of time to suppress duplicate actions + * @returns {Object|false} tracking object or false if action should be suppressed + */ +_throttle(actionType, path, timeout) { + if (!this._throttled.has(actionType)) { + this._throttled.set(actionType, new Map()); + } + + /** @type {Map} */ + const action = this._throttled.get(actionType); + /** @type {Object} */ + const actionPath = action.get(path); + + if (actionPath) { + actionPath.count++; + return false; + } + + let timeoutObject; + const clear = () => { + const item = action.get(path); + const count = item ? item.count : 0; + action.delete(path); + clearTimeout(timeoutObject); + if (item) clearTimeout(item.timeoutObject); + return count; + }; + timeoutObject = setTimeout(clear, timeout); + const thr = {timeoutObject, clear, count: 0}; + action.set(path, thr); + return thr; +} + +_incrReadyCount() { + return this._readyCount++; +} + +/** + * Awaits write operation to finish. + * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. + * @param {Path} path being acted upon + * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished + * @param {EventName} event + * @param {Function} awfEmit Callback to be called when ready for event to be emitted. + */ +_awaitWriteFinish(path, threshold, event, awfEmit) { + let timeoutHandler; + + let fullPath = path; + if (this.options.cwd && !sysPath.isAbsolute(path)) { + fullPath = sysPath.join(this.options.cwd, path); + } + + const now = new Date(); + + const awaitWriteFinish = (prevStat) => { + fs$8.stat(fullPath, (err, curStat) => { + if (err || !this._pendingWrites.has(path)) { + if (err && err.code !== 'ENOENT') awfEmit(err); + return; + } + + const now = Number(new Date()); + + if (prevStat && curStat.size !== prevStat.size) { + this._pendingWrites.get(path).lastChange = now; + } + const pw = this._pendingWrites.get(path); + const df = now - pw.lastChange; + + if (df >= threshold) { + this._pendingWrites.delete(path); + awfEmit(undefined, curStat); + } else { + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval, + curStat + ); + } + }); + }; + + if (!this._pendingWrites.has(path)) { + this._pendingWrites.set(path, { + lastChange: now, + cancelWait: () => { + this._pendingWrites.delete(path); + clearTimeout(timeoutHandler); + return event; + } + }); + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval + ); + } +} + +_getGlobIgnored() { + return [...this._ignoredPaths.values()]; +} + +/** + * Determines whether user has asked to ignore this path. + * @param {Path} path filepath or dir + * @param {fs.Stats=} stats result of fs.stat + * @returns {Boolean} + */ +_isIgnored(path, stats) { + if (this.options.atomic && DOT_RE.test(path)) return true; + if (!this._userIgnored) { + const {cwd} = this.options; + const ign = this.options.ignored; + + const ignored = ign && ign.map(normalizeIgnored(cwd)); + const paths = arrify(ignored) + .filter((path) => typeof path === STRING_TYPE && !isGlob(path)) + .map((path) => path + SLASH_GLOBSTAR); + const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths); + this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS); + } + + return this._userIgnored([path, stats]); +} + +_isntIgnored(path, stat) { + return !this._isIgnored(path, stat); +} + +/** + * Provides a set of common helpers and properties relating to symlink and glob handling. + * @param {Path} path file, directory, or glob pattern being watched + * @param {Number=} depth at any depth > 0, this isn't a glob + * @returns {WatchHelper} object containing helpers for this path + */ +_getWatchHelpers(path, depth) { + const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path); + const follow = this.options.followSymlinks; + + return new WatchHelper(path, watchPath, follow, this); +} + +// Directory helpers +// ----------------- + +/** + * Provides directory tracking objects + * @param {String} directory path of the directory + * @returns {DirEntry} the directory's tracking object + */ +_getWatchedDir(directory) { + if (!this._boundRemove) this._boundRemove = this._remove.bind(this); + const dir = sysPath.resolve(directory); + if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove)); + return this._watched.get(dir); +} + +// File helpers +// ------------ + +/** + * Check for read permissions. + * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405 + * @param {fs.Stats} stats - object, result of fs_stat + * @returns {Boolean} indicates whether the file can be read +*/ +_hasReadPermissions(stats) { + if (this.options.ignorePermissionErrors) return true; + + // stats.mode may be bigint + const md = stats && Number.parseInt(stats.mode, 10); + const st = md & 0o777; + const it = Number.parseInt(st.toString(8)[0], 10); + return Boolean(4 & it); +} + +/** + * Handles emitting unlink events for + * files and directories, and via recursion, for + * files and directories within directories that are unlinked + * @param {String} directory within which the following item is located + * @param {String} item base path of item/directory + * @returns {void} +*/ +_remove(directory, item, isDirectory) { + // if what is being deleted is a directory, get that directory's paths + // for recursive deleting and cleaning of watched object + // if it is not a directory, nestedDirectoryChildren will be empty array + const path = sysPath.join(directory, item); + const fullPath = sysPath.resolve(path); + isDirectory = isDirectory != null + ? isDirectory + : this._watched.has(path) || this._watched.has(fullPath); + + // prevent duplicate handling in case of arriving here nearly simultaneously + // via multiple paths (such as _handleFile and _handleDir) + if (!this._throttle('remove', path, 100)) return; + + // if the only watched file is removed, watch for its return + if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) { + this.add(directory, item, true); + } + + // This will create a new entry in the watched object in either case + // so we got to do the directory check beforehand + const wp = this._getWatchedDir(path); + const nestedDirectoryChildren = wp.getChildren(); + + // Recursively remove children directories / files. + nestedDirectoryChildren.forEach(nested => this._remove(path, nested)); + + // Check if item was on the watched list and remove it + const parent = this._getWatchedDir(directory); + const wasTracked = parent.has(item); + parent.remove(item); + + // Fixes issue #1042 -> Relative paths were detected and added as symlinks + // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612), + // but never removed from the map in case the path was deleted. + // This leads to an incorrect state if the path was recreated: + // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553 + if (this._symlinkPaths.has(fullPath)) { + this._symlinkPaths.delete(fullPath); + } + + // If we wait for this file to be fully written, cancel the wait. + let relPath = path; + if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path); + if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { + const event = this._pendingWrites.get(relPath).cancelWait(); + if (event === EV_ADD) return; + } + + // The Entry will either be a directory that just got removed + // or a bogus entry to a file, in either case we have to remove it + this._watched.delete(path); + this._watched.delete(fullPath); + const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK; + if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path); + + // Avoid conflicts if we later create another file with the same name + if (!this.options.useFsEvents) { + this._closePath(path); + } +} + +/** + * Closes all watchers for a path + * @param {Path} path + */ +_closePath(path) { + this._closeFile(path); + const dir = sysPath.dirname(path); + this._getWatchedDir(dir).remove(sysPath.basename(path)); +} + +/** + * Closes only file-specific watchers + * @param {Path} path + */ +_closeFile(path) { + const closers = this._closers.get(path); + if (!closers) return; + closers.forEach(closer => closer()); + this._closers.delete(path); +} + +/** + * + * @param {Path} path + * @param {Function} closer + */ +_addPathCloser(path, closer) { + if (!closer) return; + let list = this._closers.get(path); + if (!list) { + list = []; + this._closers.set(path, list); + } + list.push(closer); +} + +_readdirp(root, opts) { + if (this.closed) return; + const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts}; + let stream = readdirp(root, options); + this._streams.add(stream); + stream.once(STR_CLOSE, () => { + stream = undefined; + }); + stream.once(STR_END, () => { + if (stream) { + this._streams.delete(stream); + stream = undefined; + } + }); + return stream; +} + +} + +// Export FSWatcher class +chokidar.FSWatcher = FSWatcher; + +/** + * Instantiates watcher with paths to be tracked. + * @param {String|Array} paths file/directory paths and/or globs + * @param {Object=} options chokidar opts + * @returns an instance of FSWatcher for chaining. + */ +const watch = (paths, options) => { + const watcher = new FSWatcher(options); + watcher.add(paths); + return watcher; +}; + +chokidar.watch = watch; + +async function resolveHttpServer({ proxy }, app, httpsOptions) { + if (!httpsOptions) { + return require('http').createServer(app); + } + if (proxy) { + // #484 fallback to http1 when proxy is needed. + return require('https').createServer(httpsOptions, app); + } + else { + return require('http2').createSecureServer({ + ...httpsOptions, + allowHTTP1: true + }, app); + } +} +async function resolveHttpsConfig(config) { + if (!config.server.https) + return undefined; + const httpsOption = isObject$3(config.server.https) ? config.server.https : {}; + const { ca, cert, key, pfx } = httpsOption; + Object.assign(httpsOption, { + ca: readFileIfExists(ca), + cert: readFileIfExists(cert), + key: readFileIfExists(key), + pfx: readFileIfExists(pfx) + }); + if (!httpsOption.key || !httpsOption.cert) { + httpsOption.cert = httpsOption.key = await getCertificate(config); + } + return httpsOption; +} +function readFileIfExists(value) { + if (typeof value === 'string') { + try { + return fs__default.readFileSync(path__default.resolve(value)); + } + catch (e) { + return value; + } + } + return value; +} +/** + * https://github.com/webpack/webpack-dev-server/blob/master/lib/utils/createCertificate.js + * + * Copyright JS Foundation and other contributors + * This source code is licensed under the MIT license found in the + * LICENSE file at + * https://github.com/webpack/webpack-dev-server/blob/master/LICENSE + */ +async function createCertificate() { + const { generate } = await Promise.resolve().then(function () { return require('./dep-0e948eb3.js'); }).then(function (n) { return n.index; }); + const pems = generate(null, { + algorithm: 'sha256', + days: 30, + keySize: 2048, + extensions: [ + // { + // name: 'basicConstraints', + // cA: true, + // }, + { + name: 'keyUsage', + keyCertSign: true, + digitalSignature: true, + nonRepudiation: true, + keyEncipherment: true, + dataEncipherment: true + }, + { + name: 'extKeyUsage', + serverAuth: true, + clientAuth: true, + codeSigning: true, + timeStamping: true + }, + { + name: 'subjectAltName', + altNames: [ + { + // type 2 is DNS + type: 2, + value: 'localhost' + }, + { + type: 2, + value: 'localhost.localdomain' + }, + { + type: 2, + value: 'lvh.me' + }, + { + type: 2, + value: '*.lvh.me' + }, + { + type: 2, + value: '[::1]' + }, + { + // type 7 is IP + type: 7, + ip: '127.0.0.1' + }, + { + type: 7, + ip: 'fe80::1' + } + ] + } + ] + }); + return pems.private + pems.cert; +} +async function getCertificate(config) { + if (!config.cacheDir) + return await createCertificate(); + const cachePath = path__default.join(config.cacheDir, '_cert.pem'); + try { + const [stat, content] = await Promise.all([ + fs$v.promises.stat(cachePath), + fs$v.promises.readFile(cachePath, 'utf8') + ]); + if (Date.now() - stat.ctime.valueOf() > 30 * 24 * 60 * 60 * 1000) { + throw new Error('cache is outdated.'); + } + return content; + } + catch { + const content = await createCertificate(); + fs$v.promises + .mkdir(config.cacheDir, { recursive: true }) + .then(() => fs$v.promises.writeFile(cachePath, content)) + .catch(() => { }); + return content; + } +} +async function httpServerStart(httpServer, serverOptions) { + return new Promise((resolve, reject) => { + let { port, strictPort, host, logger } = serverOptions; + const onError = (e) => { + if (e.code === 'EADDRINUSE') { + if (strictPort) { + httpServer.removeListener('error', onError); + reject(new Error(`Port ${port} is already in use`)); + } + else { + logger.info(`Port ${port} is in use, trying another one...`); + httpServer.listen(++port, host); + } + } + else { + httpServer.removeListener('error', onError); + reject(e); + } + }; + httpServer.on('error', onError); + httpServer.listen(port, host, () => { + httpServer.removeListener('error', onError); + resolve(port); + }); + }); +} + +var bufferUtil$1 = {exports: {}}; + +var constants = { + BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + EMPTY_BUFFER: Buffer.alloc(0), + NOOP: () => {} +}; + +const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat$1(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER$3; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) return target.slice(0, offset); + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + // Required until https://github.com/nodejs/node/issues/9006 is resolved. + const length = buffer.length; + for (let i = 0; i < length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer$1(buf) { + if (buf.byteLength === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer$2(data) { + toBuffer$2.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer$2.readOnly = false; + } + + return buf; +} + +try { + const bufferUtil = require('bufferutil'); + const bu = bufferUtil.BufferUtil || bufferUtil; + + bufferUtil$1.exports = { + concat: concat$1, + mask(source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bu.mask(source, mask, output, offset, length); + }, + toArrayBuffer: toArrayBuffer$1, + toBuffer: toBuffer$2, + unmask(buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bu.unmask(buffer, mask); + } + }; +} catch (e) /* istanbul ignore next */ { + bufferUtil$1.exports = { + concat: concat$1, + mask: _mask, + toArrayBuffer: toArrayBuffer$1, + toBuffer: toBuffer$2, + unmask: _unmask + }; +} + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter$1 { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +var limiter = Limiter$1; + +const zlib = require$$0__default$4; + +const bufferUtil = bufferUtil$1.exports; +const Limiter = limiter; +const { kStatusCode: kStatusCode$2, NOOP: NOOP$1 } = constants; + +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate$4 { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {Buffer} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {Buffer} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + // + // An `'error'` event is emitted, only on Node.js < 10.0.0, if the + // `zlib.DeflateRaw` instance is closed while data is being processed. + // This can happen if `PerMessageDeflate#cleanup()` is called at the wrong + // time due to an abnormal WebSocket closure. + // + this._deflate.on('error', NOOP$1); + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) data = data.slice(0, data.length - 4); + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +var permessageDeflate = PerMessageDeflate$4; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError][kStatusCode$2] = 1009; + this.removeListener('data', inflateOnData); + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + err[kStatusCode$2] = 1007; + this[kCallback](err); +} + +var validation = {exports: {}}; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode$2(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +try { + let isValidUTF8 = require('utf-8-validate'); + + /* istanbul ignore if */ + if (typeof isValidUTF8 === 'object') { + isValidUTF8 = isValidUTF8.Validation.isValidUTF8; // utf-8-validate@<3.0.0 + } + + validation.exports = { + isValidStatusCode: isValidStatusCode$2, + isValidUTF8(buf) { + return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf); + } + }; +} catch (e) /* istanbul ignore next */ { + validation.exports = { + isValidStatusCode: isValidStatusCode$2, + isValidUTF8: _isValidUTF8 + }; +} + +const { Writable: Writable$1 } = require$$0__default$2; + +const PerMessageDeflate$3 = permessageDeflate; +const { + BINARY_TYPES: BINARY_TYPES$1, + EMPTY_BUFFER: EMPTY_BUFFER$2, + kStatusCode: kStatusCode$1, + kWebSocket: kWebSocket$2 +} = constants; +const { concat, toArrayBuffer, unmask } = bufferUtil$1.exports; +const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validation.exports; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver$1 extends Writable$1 { + /** + * Creates a Receiver instance. + * + * @param {String} [binaryType=nodebuffer] The type for binary data + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Boolean} [isServer=false] Specifies whether to operate in client or + * server mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(binaryType, extensions, isServer, maxPayload) { + super(); + + this._binaryType = binaryType || BINARY_TYPES$1[0]; + this[kWebSocket$2] = undefined; + this._extensions = extensions || {}; + this._isServer = !!isServer; + this._maxPayload = maxPayload | 0; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._state = GET_INFO; + this._loop = false; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = buf.slice(n); + return buf.slice(0, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = buf.slice(n); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + let err; + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + err = this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + err = this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + err = this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + err = this.getData(cb); + break; + default: + // `INFLATING` + this._loop = false; + return; + } + } while (this._loop); + + cb(err); + } + + /** + * Reads the first two bytes of a frame. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getInfo() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + this._loop = false; + return error$2( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) { + this._loop = false; + return error$2( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + this._loop = false; + return error$2( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if (!this._fragmented) { + this._loop = false; + return error$2( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + this._loop = false; + return error$2( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + this._loop = false; + return error$2( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + } + + if (compressed) { + this._loop = false; + return error$2( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if (this._payloadLength > 0x7d) { + this._loop = false; + return error$2( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + } + } else { + this._loop = false; + return error$2( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + this._loop = false; + return error$2( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + } + } else if (this._masked) { + this._loop = false; + return error$2( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else return this.haveLength(); + } + + /** + * Gets extended payload length (7+16). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength16() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + return this.haveLength(); + } + + /** + * Gets extended payload length (7+64). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength64() { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + this._loop = false; + return error$2( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + return this.haveLength(); + } + + /** + * Payload length has been read. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + haveLength() { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + this._loop = false; + return error$2( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER$2; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + if (this._masked) unmask(data, this._mask); + } + + if (this._opcode > 0x07) return this.controlMessage(data); + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its lenght is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + return this.dataMessage(); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + return cb( + error$2( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ) + ); + } + + this._fragments.push(buf); + } + + const er = this.dataMessage(); + if (er) return cb(er); + + this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @return {(Error|undefined)} A possible error + * @private + */ + dataMessage() { + if (this._fin) { + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else { + data = fragments; + } + + this.emit('message', data); + } else { + const buf = concat(fragments, messageLength); + + if (!isValidUTF8(buf)) { + this._loop = false; + return error$2( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('message', buf.toString()); + } + } + + this._state = GET_INFO; + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data) { + if (this._opcode === 0x08) { + this._loop = false; + + if (data.length === 0) { + this.emit('conclude', 1005, ''); + this.end(); + } else if (data.length === 1) { + return error$2( + RangeError, + 'invalid payload length 1', + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode$1(code)) { + return error$2( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + } + + const buf = data.slice(2); + + if (!isValidUTF8(buf)) { + return error$2( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('conclude', code, buf.toString()); + this.end(); + } + } else if (this._opcode === 0x09) { + this.emit('ping', data); + } else { + this.emit('pong', data); + } + + this._state = GET_INFO; + } +} + +var receiver = Receiver$1; + +/** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ +function error$2(ErrorCtor, message, prefix, statusCode, errorCode) { + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, error$2); + err.code = errorCode; + err[kStatusCode$1] = statusCode; + return err; +} + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */ +const { randomFillSync } = require$$1__default$2; + +const PerMessageDeflate$2 = permessageDeflate; +const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants; +const { isValidStatusCode } = validation.exports; +const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtil$1.exports; + +const mask = Buffer.alloc(4); + +/** + * HyBi Sender implementation. + */ +class Sender$1 { + /** + * Creates a Sender instance. + * + * @param {(net.Socket|tls.Socket)} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + */ + constructor(socket, extensions) { + this._extensions = extensions || {}; + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {Buffer} data The data to frame + * @param {Object} options Options object + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {Buffer[]} The framed data as a list of `Buffer` instances + * @public + */ + static frame(data, options) { + const merge = options.mask && options.readOnly; + let offset = options.mask ? 6 : 2; + let payloadLength = data.length; + + if (data.length >= 65536) { + offset += 8; + payloadLength = 127; + } else if (data.length > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? data.length + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(data.length, 2); + } else if (payloadLength === 127) { + target.writeUInt32BE(0, 2); + target.writeUInt32BE(data.length, 6); + } + + if (!options.mask) return [target, data]; + + randomFillSync(mask, 0, 4); + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (merge) { + applyMask(data, mask, target, offset, data.length); + return [target]; + } + + applyMask(data, mask, data, 0, data.length); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {String} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER$1; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || data === '') { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + buf.write(data, 2); + } + + if (this._deflating) { + this.enqueue([this.doClose, buf, mask, cb]); + } else { + this.doClose(buf, mask, cb); + } + } + + /** + * Frames and sends a close message. + * + * @param {Buffer} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @private + */ + doClose(data, mask, cb) { + this.sendFrame( + Sender$1.frame(data, { + fin: true, + rsv1: false, + opcode: 0x08, + mask, + readOnly: false + }), + cb + ); + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + const buf = toBuffer$1(data); + + if (buf.length > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + if (this._deflating) { + this.enqueue([this.doPing, buf, mask, toBuffer$1.readOnly, cb]); + } else { + this.doPing(buf, mask, toBuffer$1.readOnly, cb); + } + } + + /** + * Frames and sends a ping message. + * + * @param {Buffer} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified + * @param {Function} [cb] Callback + * @private + */ + doPing(data, mask, readOnly, cb) { + this.sendFrame( + Sender$1.frame(data, { + fin: true, + rsv1: false, + opcode: 0x09, + mask, + readOnly + }), + cb + ); + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + const buf = toBuffer$1(data); + + if (buf.length > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + if (this._deflating) { + this.enqueue([this.doPong, buf, mask, toBuffer$1.readOnly, cb]); + } else { + this.doPong(buf, mask, toBuffer$1.readOnly, cb); + } + } + + /** + * Frames and sends a pong message. + * + * @param {Buffer} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified + * @param {Function} [cb] Callback + * @private + */ + doPong(data, mask, readOnly, cb) { + this.sendFrame( + Sender$1.frame(data, { + fin: true, + rsv1: false, + opcode: 0x0a, + mask, + readOnly + }), + cb + ); + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const buf = toBuffer$1(data); + const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + if (this._firstFragment) { + this._firstFragment = false; + if (rsv1 && perMessageDeflate) { + rsv1 = buf.length >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + if (perMessageDeflate) { + const opts = { + fin: options.fin, + rsv1, + opcode, + mask: options.mask, + readOnly: toBuffer$1.readOnly + }; + + if (this._deflating) { + this.enqueue([this.dispatch, buf, this._compress, opts, cb]); + } else { + this.dispatch(buf, this._compress, opts, cb); + } + } else { + this.sendFrame( + Sender$1.frame(buf, { + fin: options.fin, + rsv1: false, + opcode, + mask: options.mask, + readOnly: toBuffer$1.readOnly + }), + cb + ); + } + } + + /** + * Dispatches a data message. + * + * @param {Buffer} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender$1.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName]; + + this._bufferedBytes += data.length; + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < this._queue.length; i++) { + const callback = this._queue[i][4]; + + if (typeof callback === 'function') callback(err); + } + + return; + } + + this._bufferedBytes -= data.length; + this._deflating = false; + options.readOnly = false; + this.sendFrame(Sender$1.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[1].length; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[1].length; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +var sender = Sender$1; + +/** + * Class representing an event. + * + * @private + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @param {Object} target A reference to the target to which the event was + * dispatched + */ + constructor(type, target) { + this.target = target; + this.type = type; + } +} + +/** + * Class representing a message event. + * + * @extends Event + * @private + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data + * @param {WebSocket} target A reference to the target to which the event was + * dispatched + */ + constructor(data, target) { + super('message', target); + + this.data = data; + } +} + +/** + * Class representing a close event. + * + * @extends Event + * @private + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {Number} code The status code explaining why the connection is being + * closed + * @param {String} reason A human-readable string explaining why the + * connection is closing + * @param {WebSocket} target A reference to the target to which the event was + * dispatched + */ + constructor(code, reason, target) { + super('close', target); + + this.wasClean = target._closeFrameReceived && target._closeFrameSent; + this.reason = reason; + this.code = code; + } +} + +/** + * Class representing an open event. + * + * @extends Event + * @private + */ +class OpenEvent extends Event { + /** + * Create a new `OpenEvent`. + * + * @param {WebSocket} target A reference to the target to which the event was + * dispatched + */ + constructor(target) { + super('open', target); + } +} + +/** + * Class representing an error event. + * + * @extends Event + * @private + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {Object} error The error that generated this event + * @param {WebSocket} target A reference to the target to which the event was + * dispatched + */ + constructor(error, target) { + super('error', target); + + this.message = error.message; + this.error = error; + } +} + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {Function} listener The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean`` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, listener, options) { + if (typeof listener !== 'function') return; + + function onMessage(data) { + listener.call(this, new MessageEvent(data, this)); + } + + function onClose(code, message) { + listener.call(this, new CloseEvent(code, message, this)); + } + + function onError(error) { + listener.call(this, new ErrorEvent(error, this)); + } + + function onOpen() { + listener.call(this, new OpenEvent(this)); + } + + const method = options && options.once ? 'once' : 'on'; + + if (type === 'message') { + onMessage._listener = listener; + this[method](type, onMessage); + } else if (type === 'close') { + onClose._listener = listener; + this[method](type, onClose); + } else if (type === 'error') { + onError._listener = listener; + this[method](type, onError); + } else if (type === 'open') { + onOpen._listener = listener; + this[method](type, onOpen); + } else { + this[method](type, listener); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {Function} listener The listener to remove + * @public + */ + removeEventListener(type, listener) { + const listeners = this.listeners(type); + + for (let i = 0; i < listeners.length; i++) { + if (listeners[i] === listener || listeners[i]._listener === listener) { + this.removeListener(type, listeners[i]); + } + } + } +}; + +var eventTarget = EventTarget; + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse$7(header) { + const offers = Object.create(null); + + if (header === undefined || header === '') return offers; + + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 /* ' ' */ || code === 0x09 /* '\t' */) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format$2(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +var extension = { format: format$2, parse: parse$7 }; + +const EventEmitter$1 = require$$0__default$6; +const https$2 = require$$1__default$3; +const http$3 = require$$1__default$1; +const net = require$$4__default$1; +const tls = require$$4__default$2; +const { randomBytes, createHash: createHash$1 } = require$$1__default$2; +const { URL: URL$2 } = require$$0__default$7; + +const PerMessageDeflate$1 = permessageDeflate; +const Receiver = receiver; +const Sender = sender; +const { + BINARY_TYPES, + EMPTY_BUFFER, + GUID: GUID$1, + kStatusCode, + kWebSocket: kWebSocket$1, + NOOP +} = constants; +const { addEventListener, removeEventListener } = eventTarget; +const { format: format$1, parse: parse$6 } = extension; +const { toBuffer } = bufferUtil$1.exports; + +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const protocolVersions = [8, 13]; +const closeTimeout = 30 * 1000; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket$2 extends EventEmitter$1 { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = ''; + this._closeTimer = null; + this._extensions = {}; + this._protocol = ''; + this._readyState = WebSocket$2.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (Array.isArray(protocols)) { + protocols = protocols.join(', '); + } else if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = undefined; + } + + initAsClient(this, address, protocols, options); + } else { + this._isServer = true; + } + } + + /** + * This deviates from the WHATWG interface since ws doesn't support the + * required default "blob" type (instead we define a custom "nodebuffer" + * type). + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return undefined; + } + + /* istanbul ignore next */ + set onclose(listener) {} + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return undefined; + } + + /* istanbul ignore next */ + set onerror(listener) {} + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return undefined; + } + + /* istanbul ignore next */ + set onopen(listener) {} + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return undefined; + } + + /* istanbul ignore next */ + set onmessage(listener) {} + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Number} [maxPayload=0] The maximum allowed message size + * @private + */ + setSocket(socket, head, maxPayload) { + const receiver = new Receiver( + this.binaryType, + this._extensions, + this._isServer, + maxPayload + ); + + this._sender = new Sender(socket, this._extensions); + this._receiver = receiver; + this._socket = socket; + + receiver[kWebSocket$1] = this; + socket[kWebSocket$1] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + socket.setTimeout(0); + socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError$1); + + this._readyState = WebSocket$2.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket$2.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate$1.extensionName]) { + this._extensions[PerMessageDeflate$1.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket$2.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {String} [data] A string explaining why the connection is closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket$2.CLOSED) return; + if (this.readyState === WebSocket$2.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + return abortHandshake$1(this, this._req, msg); + } + + if (this.readyState === WebSocket$2.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket$2.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + // + // Specify a timeout for the closing handshake to complete. + // + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket$2.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket$2.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket$2.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket$2.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket$2.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket$2.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate$1.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket$2.CLOSED) return; + if (this.readyState === WebSocket$2.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + return abortHandshake$1(this, this._req, msg); + } + + if (this._socket) { + this._readyState = WebSocket$2.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$2, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$2.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$2, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$2.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$2, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$2.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$2, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$2.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket$2.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket$2.prototype, `on${method}`, { + enumerable: true, + get() { + const listeners = this.listeners(method); + for (let i = 0; i < listeners.length; i++) { + if (listeners[i]._listener) return listeners[i]._listener; + } + + return undefined; + }, + set(listener) { + const listeners = this.listeners(method); + for (let i = 0; i < listeners.length; i++) { + // + // Remove only the listeners added via `addEventListener`. + // + if (listeners[i]._listener) this.removeListener(method, listeners[i]); + } + this.addEventListener(method, listener); + } + }); +}); + +WebSocket$2.prototype.addEventListener = addEventListener; +WebSocket$2.prototype.removeEventListener = removeEventListener; + +var websocket = WebSocket$2; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {String} [protocols] The subprotocols + * @param {Object} [options] Connection options + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + createConnection: undefined, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: undefined, + host: undefined, + path: undefined, + port: undefined + }; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL$2) { + parsedUrl = address; + websocket._url = address.href; + } else { + parsedUrl = new URL$2(address); + websocket._url = address; + } + + const isUnixSocket = parsedUrl.protocol === 'ws+unix:'; + + if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) { + throw new Error(`Invalid URL: ${websocket.url}`); + } + + const isSecure = + parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:'; + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const get = isSecure ? https$2.get : http$3.get; + let perMessageDeflate; + + opts.createConnection = isSecure ? tlsConnect : netConnect; + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket', + ...opts.headers + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate$1( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers['Sec-WebSocket-Extensions'] = format$1({ + [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols) { + opts.headers['Sec-WebSocket-Protocol'] = protocols; + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isUnixSocket) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req = (websocket._req = get(opts)); + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake$1(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req.aborted) return; + + req = websocket._req = null; + websocket._readyState = WebSocket$2.CLOSING; + websocket.emit('error', err); + websocket.emitClose(); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake$1(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + const addr = new URL$2(location, address); + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake$1( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the `upgrade` + // event. + // + if (websocket.readyState !== WebSocket$2.CONNECTING) return; + + req = websocket._req = null; + + const digest = createHash$1('sha1') + .update(key + GUID$1) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + const protList = (protocols || '').split(/, */); + let protError; + + if (!protocols && serverProt) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (protocols && !serverProt) { + protError = 'Server sent no subprotocol'; + } else if (serverProt && !protList.includes(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + + if (protError) { + abortHandshake$1(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake$1(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse$6(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake$1(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if (extensionNames.length) { + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate$1.extensionName + ) { + const message = + 'Server indicated an extension that was not requested'; + abortHandshake$1(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake$1(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate$1.extensionName] = + perMessageDeflate; + } + } + + websocket.setSocket(socket, head, opts.maxPayload); + }); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake$1(websocket, stream, message) { + websocket._readyState = WebSocket$2.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake$1); + + if (stream.setHeader) { + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + stream.once('abort', websocket.emitClose.bind(websocket)); + websocket.emit('error', err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + cb(err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {String} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket$1]; + + websocket._socket.removeListener('data', socketOnData); + websocket._socket.resume(); + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + this[kWebSocket$1]._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket$1]; + + websocket._socket.removeListener('data', socketOnData); + websocket._socket.resume(); + + websocket.close(err[kStatusCode]); + websocket.emit('error', err); +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket$1].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message + * @private + */ +function receiverOnMessage(data) { + this[kWebSocket$1].emit('message', data); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket$1]; + + websocket.pong(data, !websocket._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket$1].emit('pong', data); +} + +/** + * The listener of the `net.Socket` `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket$1]; + + this.removeListener('close', socketOnClose); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket$2.CLOSING; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written and `readable.read()` + // will return `null`. If instead, the socket is paused, any possible buffered + // data will be read as a single chunk and emitted synchronously in a single + // `'data'` event. + // + websocket._socket.read(); + websocket._receiver.end(); + + this.removeListener('data', socketOnData); + this[kWebSocket$1] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the `net.Socket` `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket$1]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the `net.Socket` `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket$1]; + + websocket._readyState = WebSocket$2.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the `net.Socket` `'error'` event. + * + * @private + */ +function socketOnError$1() { + const websocket = this[kWebSocket$1]; + + this.removeListener('error', socketOnError$1); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket$2.CLOSING; + this.destroy(); + } +} + +const { Duplex } = require$$0__default$2; + +/** + * Emits the `'close'` event on a stream. + * + * @param {Duplex} stream The stream. + * @private + */ +function emitClose$1(stream) { + stream.emit('close'); +} + +/** + * The listener of the `'end'` event. + * + * @private + */ +function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } +} + +/** + * The listener of the `'error'` event. + * + * @param {Error} err The error + * @private + */ +function duplexOnError(err) { + this.removeListener('error', duplexOnError); + this.destroy(); + if (this.listenerCount('error') === 0) { + // Do not suppress the throwing behavior. + this.emit('error', err); + } +} + +/** + * Wraps a `WebSocket` in a duplex stream. + * + * @param {WebSocket} ws The `WebSocket` to wrap + * @param {Object} [options] The options for the `Duplex` constructor + * @return {Duplex} The duplex stream + * @public + */ +function createWebSocketStream(ws, options) { + let resumeOnReceiverDrain = true; + let terminateOnDestroy = true; + + function receiverOnDrain() { + if (resumeOnReceiverDrain) ws._socket.resume(); + } + + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + ws._receiver.removeAllListeners('drain'); + ws._receiver.on('drain', receiverOnDrain); + }); + } else { + ws._receiver.removeAllListeners('drain'); + ws._receiver.on('drain', receiverOnDrain); + } + + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + + ws.on('message', function message(msg) { + if (!duplex.push(msg)) { + resumeOnReceiverDrain = false; + ws._socket.pause(); + } + }); + + ws.once('error', function error(err) { + if (duplex.destroyed) return; + + // Prevent `ws.terminate()` from being called by `duplex._destroy()`. + // + // - If the `'error'` event is emitted before the `'open'` event, then + // `ws.terminate()` is a noop as no socket is assigned. + // - Otherwise, the error is re-emitted by the listener of the `'error'` + // event of the `Receiver` object. The listener already closes the + // connection by calling `ws.close()`. This allows a close frame to be + // sent to the other peer. If `ws.terminate()` is called right after this, + // then the close frame might not be sent. + terminateOnDestroy = false; + duplex.destroy(err); + }); + + ws.once('close', function close() { + if (duplex.destroyed) return; + + duplex.push(null); + }); + + duplex._destroy = function (err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose$1, duplex); + return; + } + + let called = false; + + ws.once('error', function error(err) { + called = true; + callback(err); + }); + + ws.once('close', function close() { + if (!called) callback(err); + process.nextTick(emitClose$1, duplex); + }); + + if (terminateOnDestroy) ws.terminate(); + }; + + duplex._final = function (callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._final(callback); + }); + return; + } + + // If the value of the `_socket` property is `null` it means that `ws` is a + // client websocket and the handshake failed. In fact, when this happens, a + // socket is never assigned to the websocket. Wait for the `'error'` event + // that will be emitted by the websocket. + if (ws._socket === null) return; + + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once('finish', function finish() { + // `duplex` is not destroyed here because the `'end'` event will be + // emitted on `duplex` after this `'finish'` event. The EOF signaling + // `null` chunk is, in fact, pushed when the websocket emits `'close'`. + callback(); + }); + ws.close(); + } + }; + + duplex._read = function () { + if (ws.readyState === ws.OPEN && !resumeOnReceiverDrain) { + resumeOnReceiverDrain = true; + if (!ws._receiver._writableState.needDrain) ws._socket.resume(); + } + }; + + duplex._write = function (chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + + ws.send(chunk, callback); + }; + + duplex.on('end', duplexOnEnd); + duplex.on('error', duplexOnError); + return duplex; +} + +var stream$2 = createWebSocketStream; + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */ + +const EventEmitter = require$$0__default$6; +const http$2 = require$$1__default$1; +const { createHash } = require$$1__default$2; + +const PerMessageDeflate = permessageDeflate; +const WebSocket$1 = websocket; +const { format, parse: parse$5 } = extension; +const { GUID, kWebSocket } = constants; + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + maxPayload: 100 * 1024 * 1024, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http$2.createServer((req, res) => { + const body = http$2.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) this.clients = new Set(); + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Close the server. + * + * @param {Function} [cb] Callback + * @public + */ + close(cb) { + if (cb) this.once('close', cb); + + if (this._state === CLOSED) { + process.nextTick(emitClose, this); + return; + } + + if (this._state === CLOSING) return; + this._state = CLOSING; + + // + // Terminate all associated clients. + // + if (this.clients) { + for (const client of this.clients) client.terminate(); + } + + const server = this._server; + + if (server) { + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // Close the http server if it was internally created. + // + if (this.options.port != null) { + server.close(emitClose.bind(undefined, this)); + return; + } + } + + process.nextTick(emitClose, this); + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = + req.headers['sec-websocket-key'] !== undefined + ? req.headers['sec-websocket-key'].trim() + : false; + const version = +req.headers['sec-websocket-version']; + const extensions = {}; + + if ( + req.method !== 'GET' || + req.headers.upgrade.toLowerCase() !== 'websocket' || + !key || + !keyRegex.test(key) || + (version !== 8 && version !== 13) || + !this.shouldHandle(req) + ) { + return abortHandshake(socket, 400); + } + + if (this.options.perMessageDeflate) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = parse$5(req.headers['sec-websocket-extensions']); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + return abortHandshake(socket, 400); + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade(key, extensions, req, socket, head, cb); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(key, extensions, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Object} extensions The accepted extensions + * @param {http.IncomingMessage} req The request object + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(key, extensions, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new WebSocket$1(null); + let protocol = req.headers['sec-websocket-protocol']; + + if (protocol) { + protocol = protocol.split(',').map(trim); + + // + // Optionally call external protocol selection handler. + // + if (this.options.handleProtocols) { + protocol = this.options.handleProtocols(protocol, req); + } else { + protocol = protocol[0]; + } + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, this.options.maxPayload); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => this.clients.delete(ws)); + } + + cb(ws, req); + } +} + +var websocketServer = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle premature socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + if (socket.writable) { + message = message || http$2.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.write( + `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); + } + + socket.removeListener('error', socketOnError); + socket.destroy(); +} + +/** + * Remove whitespace characters from both ends of a string. + * + * @param {String} str The string + * @return {String} A new string representing `str` stripped of whitespace + * characters from both its beginning and end + * @private + */ +function trim(str) { + return str.trim(); +} + +const WebSocket = websocket; + +WebSocket.createWebSocketStream = stream$2; +WebSocket.Server = websocketServer; +WebSocket.Receiver = receiver; +WebSocket.Sender = sender; + +var ws = WebSocket; + +const HMR_HEADER = 'vite-hmr'; +function createWebSocketServer(server, config, httpsOptions) { + let wss; + let httpsServer = undefined; + const hmr = isObject$3(config.server.hmr) && config.server.hmr; + const wsServer = (hmr && hmr.server) || server; + if (wsServer) { + wss = new ws.Server({ noServer: true }); + wsServer.on('upgrade', (req, socket, head) => { + if (req.headers['sec-websocket-protocol'] === HMR_HEADER) { + wss.handleUpgrade(req, socket, head, (ws) => { + wss.emit('connection', ws, req); + }); + } + }); + } + else { + const websocketServerOptions = {}; + const port = (hmr && hmr.port) || 24678; + if (httpsOptions) { + // if we're serving the middlewares over https, the ws library doesn't support automatically creating an https server, so we need to do it ourselves + // create an inline https server and mount the websocket server to it + httpsServer = require$$1$4.createServer(httpsOptions, (req, res) => { + const statusCode = 426; + const body = require$$1$3.STATUS_CODES[statusCode]; + if (!body) + throw new Error(`No body text found for the ${statusCode} status code`); + res.writeHead(statusCode, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + httpsServer.listen(port); + websocketServerOptions.server = httpsServer; + } + else { + // we don't need to serve over https, just let ws handle its own server + websocketServerOptions.port = port; + } + // vite dev server in middleware mode + wss = new ws.Server(websocketServerOptions); + } + wss.on('connection', (socket) => { + socket.send(JSON.stringify({ type: 'connected' })); + if (bufferedError) { + socket.send(JSON.stringify(bufferedError)); + bufferedError = null; + } + }); + wss.on('error', (e) => { + if (e.code !== 'EADDRINUSE') { + config.logger.error(source.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e }); + } + }); + // On page reloads, if a file fails to compile and returns 500, the server + // sends the error payload before the client connection is established. + // If we have no open clients, buffer the error and send it to the next + // connected client. + let bufferedError = null; + return { + send(payload) { + if (payload.type === 'error' && !wss.clients.size) { + bufferedError = payload; + return; + } + const stringified = JSON.stringify(payload); + wss.clients.forEach((client) => { + if (client.readyState === ws.OPEN) { + client.send(stringified); + } + }); + }, + close() { + return new Promise((resolve, reject) => { + wss.close((err) => { + if (err) { + reject(err); + } + else { + if (httpsServer) { + httpsServer.close((err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + } + else { + resolve(); + } + } + }); + }); + } + }; +} + +// this middleware is only active when (config.base !== '/') +function baseMiddleware({ config }) { + const base = config.base; + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteBaseMiddleware(req, res, next) { + var _a; + const url = req.url; + const parsed = require$$0$a.parse(url); + const path = parsed.pathname || '/'; + if (path.startsWith(base)) { + // rewrite url to remove base.. this ensures that other middleware does + // not need to consider base being prepended or not + req.url = url.replace(base, '/'); + return next(); + } + // skip redirect and error fallback on middleware mode, #4057 + if (config.server.middlewareMode) { + return next(); + } + if (path === '/' || path === '/index.html') { + // redirect root visit to based url + res.writeHead(302, { + Location: base + }); + res.end(); + return; + } + else if ((_a = req.headers.accept) === null || _a === void 0 ? void 0 : _a.includes('text/html')) { + // non-based page visit + const redirectPath = base + url.slice(1); + res.writeHead(404, { + 'Content-Type': 'text/html' + }); + res.end(`The server is configured with a public base URL of ${base} - ` + + `did you mean to visit ${redirectPath} instead?`); + return; + } + next(); + }; +} + +var httpProxy$2 = {exports: {}}; + +var eventemitter3 = {exports: {}}; + +(function (module) { + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ +function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + + return emitter; +} + +/** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ +function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; +}; + +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); +}; + +/** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; + +/** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +{ + module.exports = EventEmitter; +} +}(eventemitter3)); + +var common$3 = {}; + +/** + * Check if we're required to add a port number. + * + * @see https://url.spec.whatwg.org/#default-port + * @param {Number|String} port Port number we need to check + * @param {String} protocol Protocol we need to check against. + * @returns {Boolean} Is it a default port for the given protocol + * @api private + */ +var requiresPort = function required(port, protocol) { + protocol = protocol.split(':')[0]; + port = +port; + + if (!port) return false; + + switch (protocol) { + case 'http': + case 'ws': + return port !== 80; + + case 'https': + case 'wss': + return port !== 443; + + case 'ftp': + return port !== 21; + + case 'gopher': + return port !== 70; + + case 'file': + return false; + } + + return port !== 0; +}; + +(function (exports) { +var common = exports, + url = require$$0__default$7, + extend = require$$0__default$3._extend, + required = requiresPort; + +var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i, + isSSL = /^https|wss/; + +/** + * Simple Regex for testing if protocol is https + */ +common.isSSL = isSSL; +/** + * Copies the right headers from `options` and `req` to + * `outgoing` which is then used to fire the proxied + * request. + * + * Examples: + * + * common.setupOutgoing(outgoing, options, req) + * // => { host: ..., hostname: ...} + * + * @param {Object} Outgoing Base object to be filled with required properties + * @param {Object} Options Config object passed to the proxy + * @param {ClientRequest} Req Request Object + * @param {String} Forward String to select forward or target + *  + * @return {Object} Outgoing Object with all required properties set + * + * @api private + */ + +common.setupOutgoing = function(outgoing, options, req, forward) { + outgoing.port = options[forward || 'target'].port || + (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80); + + ['host', 'hostname', 'socketPath', 'pfx', 'key', + 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach( + function(e) { outgoing[e] = options[forward || 'target'][e]; } + ); + + outgoing.method = options.method || req.method; + outgoing.headers = extend({}, req.headers); + + if (options.headers){ + extend(outgoing.headers, options.headers); + } + + if (options.auth) { + outgoing.auth = options.auth; + } + + if (options.ca) { + outgoing.ca = options.ca; + } + + if (isSSL.test(options[forward || 'target'].protocol)) { + outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure; + } + + + outgoing.agent = options.agent || false; + outgoing.localAddress = options.localAddress; + + // + // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do + // as node core doesn't handle this COMPLETELY properly yet. + // + if (!outgoing.agent) { + outgoing.headers = outgoing.headers || {}; + if (typeof outgoing.headers.connection !== 'string' + || !upgradeHeader.test(outgoing.headers.connection) + ) { outgoing.headers.connection = 'close'; } + } + + + // the final path is target path + relative path requested by user: + var target = options[forward || 'target']; + var targetPath = target && options.prependPath !== false + ? (target.path || '') + : ''; + + // + // Remark: Can we somehow not use url.parse as a perf optimization? + // + var outgoingPath = !options.toProxy + ? (url.parse(req.url).path || '') + : req.url; + + // + // Remark: ignorePath will just straight up ignore whatever the request's + // path is. This can be labeled as FOOT-GUN material if you do not know what + // you are doing and are using conflicting options. + // + outgoingPath = !options.ignorePath ? outgoingPath : ''; + + outgoing.path = common.urlJoin(targetPath, outgoingPath); + + if (options.changeOrigin) { + outgoing.headers.host = + required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host) + ? outgoing.host + ':' + outgoing.port + : outgoing.host; + } + return outgoing; +}; + +/** + * Set the proper configuration for sockets, + * set no delay and set keep alive, also set + * the timeout to 0. + * + * Examples: + * + * common.setupSocket(socket) + * // => Socket + * + * @param {Socket} Socket instance to setup + *  + * @return {Socket} Return the configured socket. + * + * @api private + */ + +common.setupSocket = function(socket) { + socket.setTimeout(0); + socket.setNoDelay(true); + + socket.setKeepAlive(true, 0); + + return socket; +}; + +/** + * Get the port number from the host. Or guess it based on the connection type. + * + * @param {Request} req Incoming HTTP request. + * + * @return {String} The port number. + * + * @api private + */ +common.getPort = function(req) { + var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : ''; + + return res ? + res[1] : + common.hasEncryptedConnection(req) ? '443' : '80'; +}; + +/** + * Check if the request has an encrypted connection. + * + * @param {Request} req Incoming HTTP request. + * + * @return {Boolean} Whether the connection is encrypted or not. + * + * @api private + */ +common.hasEncryptedConnection = function(req) { + return Boolean(req.connection.encrypted || req.connection.pair); +}; + +/** + * OS-agnostic join (doesn't break on URLs like path.join does on Windows)> + * + * @return {String} The generated path. + * + * @api private + */ + +common.urlJoin = function() { + // + // We do not want to mess with the query string. All we want to touch is the path. + // + var args = Array.prototype.slice.call(arguments), + lastIndex = args.length - 1, + last = args[lastIndex], + lastSegs = last.split('?'), + retSegs; + + args[lastIndex] = lastSegs.shift(); + + // + // Join all strings, but remove empty strings so we don't get extra slashes from + // joining e.g. ['', 'am'] + // + retSegs = [ + args.filter(Boolean).join('/') + .replace(/\/+/g, '/') + .replace('http:/', 'http://') + .replace('https:/', 'https://') + ]; + + // Only join the query string if it exists so we don't have trailing a '?' + // on every request + + // Handle case where there could be multiple ? in the URL. + retSegs.push.apply(retSegs, lastSegs); + + return retSegs.join('?') +}; + +/** + * Rewrites or removes the domain of a cookie header + * + * @param {String|Array} Header + * @param {Object} Config, mapping of domain to rewritten domain. + * '*' key to match any domain, null value to remove the domain. + * + * @api private + */ +common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) { + if (Array.isArray(header)) { + return header.map(function (headerElement) { + return rewriteCookieProperty(headerElement, config, property); + }); + } + return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) { + var newValue; + if (previousValue in config) { + newValue = config[previousValue]; + } else if ('*' in config) { + newValue = config['*']; + } else { + //no match, return previous value + return match; + } + if (newValue) { + //replace value + return prefix + newValue; + } else { + //remove value + return ''; + } + }); +}; + +/** + * Check the host and see if it potentially has a port in it (keep it simple) + * + * @returns {Boolean} Whether we have one or not + * + * @api private + */ +function hasPort(host) { + return !!~host.indexOf(':'); +}}(common$3)); + +var url$2 = require$$0__default$7, + common$2 = common$3; + + +var redirectRegex = /^201|30(1|2|7|8)$/; + +/*! + * Array of passes. + * + * A `pass` is just a function that is executed on `req, res, options` + * so that you can easily add new checks while still keeping the base + * flexible. + */ + +var webOutgoing = { // <-- + + /** + * If is a HTTP 1.0 request, remove chunk headers + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {proxyResponse} Res Response object from the proxy request + * + * @api private + */ + removeChunked: function removeChunked(req, res, proxyRes) { + if (req.httpVersion === '1.0') { + delete proxyRes.headers['transfer-encoding']; + } + }, + + /** + * If is a HTTP 1.0 request, set the correct connection header + * or if connection header not present, then use `keep-alive` + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {proxyResponse} Res Response object from the proxy request + * + * @api private + */ + setConnection: function setConnection(req, res, proxyRes) { + if (req.httpVersion === '1.0') { + proxyRes.headers.connection = req.headers.connection || 'close'; + } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) { + proxyRes.headers.connection = req.headers.connection || 'keep-alive'; + } + }, + + setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) { + if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) + && proxyRes.headers['location'] + && redirectRegex.test(proxyRes.statusCode)) { + var target = url$2.parse(options.target); + var u = url$2.parse(proxyRes.headers['location']); + + // make sure the redirected host matches the target host before rewriting + if (target.host != u.host) { + return; + } + + if (options.hostRewrite) { + u.host = options.hostRewrite; + } else if (options.autoRewrite) { + u.host = req.headers['host']; + } + if (options.protocolRewrite) { + u.protocol = options.protocolRewrite; + } + + proxyRes.headers['location'] = u.format(); + } + }, + /** + * Copy headers from proxyResponse to response + * set each header in response object. + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {proxyResponse} Res Response object from the proxy request + * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain + * + * @api private + */ + writeHeaders: function writeHeaders(req, res, proxyRes, options) { + var rewriteCookieDomainConfig = options.cookieDomainRewrite, + rewriteCookiePathConfig = options.cookiePathRewrite, + preserveHeaderKeyCase = options.preserveHeaderKeyCase, + rawHeaderKeyMap, + setHeader = function(key, header) { + if (header == undefined) return; + if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') { + header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain'); + } + if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') { + header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path'); + } + res.setHeader(String(key).trim(), header); + }; + + if (typeof rewriteCookieDomainConfig === 'string') { //also test for '' + rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig }; + } + + if (typeof rewriteCookiePathConfig === 'string') { //also test for '' + rewriteCookiePathConfig = { '*': rewriteCookiePathConfig }; + } + + // message.rawHeaders is added in: v0.11.6 + // https://nodejs.org/api/http.html#http_message_rawheaders + if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) { + rawHeaderKeyMap = {}; + for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) { + var key = proxyRes.rawHeaders[i]; + rawHeaderKeyMap[key.toLowerCase()] = key; + } + } + + Object.keys(proxyRes.headers).forEach(function(key) { + var header = proxyRes.headers[key]; + if (preserveHeaderKeyCase && rawHeaderKeyMap) { + key = rawHeaderKeyMap[key] || key; + } + setHeader(key, header); + }); + }, + + /** + * Set the statusCode from the proxyResponse + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {proxyResponse} Res Response object from the proxy request + * + * @api private + */ + writeStatusCode: function writeStatusCode(req, res, proxyRes) { + // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers]) + if(proxyRes.statusMessage) { + res.statusCode = proxyRes.statusCode; + res.statusMessage = proxyRes.statusMessage; + } else { + res.statusCode = proxyRes.statusCode; + } + } + +}; + +var followRedirects$1 = {exports: {}}; + +var debug$5; + +var debug_1 = function () { + if (!debug$5) { + try { + /* eslint global-require: off */ + debug$5 = src$3.exports("follow-redirects"); + } + catch (error) { /* */ } + if (typeof debug$5 !== "function") { + debug$5 = function () { /* */ }; + } + } + debug$5.apply(null, arguments); +}; + +var url$1 = require$$0__default$7; +var URL$1 = url$1.URL; +var http$1 = require$$1__default$1; +var https$1 = require$$1__default$3; +var Writable = require$$0__default$2.Writable; +var assert$1 = require$$6__default; +var debug$4 = debug_1; + +// Create handlers that pass events from native requests +var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; +var eventHandlers = Object.create(null); +events.forEach(function (event) { + eventHandlers[event] = function (arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; +}); + +// Error types with codes +var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "" +); +var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded" +); +var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" +); +var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" +); + +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; + + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); + } + + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + self._processResponse(response); + }; + + // Perform the first request + this._performRequest(); +} +RedirectableRequest.prototype = Object.create(Writable.prototype); + +RedirectableRequest.prototype.abort = function () { + abortRequest(this._currentRequest); + this.emit("abort"); +}; + +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Writing is not allowed if end has been called + if (this._ending) { + throw new WriteAfterEndError(); + } + + // Validate input and shift parameters if necessary + if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } + + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); + } + // Error when we exceed the maximum body length + else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } +}; + +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (typeof data === "function") { + callback = data; + data = encoding = null; + } + else if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } + + // Write data if needed and end + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } + else { + var self = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function () { + self._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; + } +}; + +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; + +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; + +// Global timeout for all underlying requests +RedirectableRequest.prototype.setTimeout = function (msecs, callback) { + var self = this; + if (callback) { + this.on("timeout", callback); + } + + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } + + // Sets up a timer to trigger a timeout event + function startTimer(socket) { + if (self._timeout) { + clearTimeout(self._timeout); + } + self._timeout = setTimeout(function () { + self.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } + + // Prevent a timeout from triggering + function clearTimer() { + clearTimeout(this._timeout); + if (callback) { + self.removeListener("timeout", callback); + } + if (!this.socket) { + self._currentRequest.removeListener("socket", startTimer); + } + } + + // Start the timer when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); + } + + this.on("socket", destroyOnTimeout); + this.once("response", clearTimer); + this.once("error", clearTimer); + + return this; +}; + +// Proxy all other public ClientRequest methods +[ + "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; +}); + +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); + +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; + } + + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } + + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } +}; + + +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + this.emit("error", new TypeError("Unsupported protocol " + protocol)); + return; + } + + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.substr(0, protocol.length - 1); + this._options.agent = this._options.agents[scheme]; + } + + // Create the native request + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + this._currentUrl = url$1.format(this._options); + + // Set up event handlers + request._redirectable = this; + for (var e = 0; e < events.length; e++) { + request.on(events[e], eventHandlers[events[e]]); + } + + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end. + var i = 0; + var self = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + // Only write if this request has not been redirected yet + /* istanbul ignore else */ + if (request === self._currentRequest) { + // Report any write errors + /* istanbul ignore if */ + if (error) { + self.emit("error", error); + } + // Write the next buffer if there are still left + else if (i < buffers.length) { + var buffer = buffers[i++]; + /* istanbul ignore else */ + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } + } + // End the request if `end` has been called on us + else if (self._ended) { + request.end(); + } + } + }()); + } +}; + +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: statusCode, + }); + } + + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. + var location = response.headers.location; + if (location && this._options.followRedirects !== false && + statusCode >= 300 && statusCode < 400) { + // Abort the current request + abortRequest(this._currentRequest); + // Discard the remainder of the response to avoid waiting for data + response.destroy(); + + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + this.emit("error", new TooManyRedirectsError()); + return; + } + + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe, […] + // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change + // the request method from POST to GET for the subsequent request. + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || + // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } + + // Drop the Host header, as the redirect might lead to a different host + var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) || + url$1.parse(this._currentUrl).hostname; + + // Create the redirected request + var redirectUrl = url$1.resolve(this._currentUrl, location); + debug$4("redirecting to", redirectUrl); + this._isRedirect = true; + var redirectUrlParts = url$1.parse(redirectUrl); + Object.assign(this._options, redirectUrlParts); + + // Drop the Authorization header if redirecting to another host + if (redirectUrlParts.hostname !== previousHostName) { + removeMatchingHeaders(/^authorization$/i, this._options.headers); + } + + // Evaluate the beforeRedirect callback + if (typeof this._options.beforeRedirect === "function") { + var responseDetails = { headers: response.headers }; + try { + this._options.beforeRedirect.call(null, this._options, responseDetails); + } + catch (err) { + this.emit("error", err); + return; + } + this._sanitizeOptions(this._options); + } + + // Perform the redirected request + try { + this._performRequest(); + } + catch (cause) { + var error = new RedirectionError("Redirected request failed: " + cause.message); + error.cause = cause; + this.emit("error", error); + } + } + else { + // The response is not a redirect; return it as-is + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); + + // Clean up + this._requestBodyBuffers = []; + } +}; + +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; + + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); + + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters + if (typeof input === "string") { + var urlStr = input; + try { + input = urlToOptions(new URL$1(urlStr)); + } + catch (err) { + /* istanbul ignore next */ + input = url$1.parse(urlStr); + } + } + else if (URL$1 && (input instanceof URL$1)) { + input = urlToOptions(input); + } + else { + callback = options; + options = input; + input = { protocol: protocol }; + } + if (typeof options === "function") { + callback = options; + options = null; + } + + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; + + assert$1.equal(options.protocol, protocol, "protocol mismatch"); + debug$4("options", options); + return new RedirectableRequest(options, callback); + } + + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + + // Expose the properties on the wrapped protocol + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true }, + }); + }); + return exports; +} + +/* istanbul ignore next */ +function noop$2() { /* empty */ } + +// from https://github.com/nodejs/node/blob/master/lib/internal/url.js +function urlToOptions(urlObject) { + var options = { + protocol: urlObject.protocol, + hostname: urlObject.hostname.startsWith("[") ? + /* istanbul ignore next */ + urlObject.hostname.slice(1, -1) : + urlObject.hostname, + hash: urlObject.hash, + search: urlObject.search, + pathname: urlObject.pathname, + path: urlObject.pathname + urlObject.search, + href: urlObject.href, + }; + if (urlObject.port !== "") { + options.port = Number(urlObject.port); + } + return options; +} + +function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } + } + return lastValue; +} + +function createErrorType(code, defaultMessage) { + function CustomError(message) { + Error.captureStackTrace(this, this.constructor); + this.message = message || defaultMessage; + } + CustomError.prototype = new Error(); + CustomError.prototype.constructor = CustomError; + CustomError.prototype.name = "Error [" + code + "]"; + CustomError.prototype.code = code; + return CustomError; +} + +function abortRequest(request) { + for (var e = 0; e < events.length; e++) { + request.removeListener(events[e], eventHandlers[events[e]]); + } + request.on("error", noop$2); + request.abort(); +} + +// Exports +followRedirects$1.exports = wrap({ http: http$1, https: https$1 }); +followRedirects$1.exports.wrap = wrap; + +var httpNative = require$$1__default$1, + httpsNative = require$$1__default$3, + web_o = webOutgoing, + common$1 = common$3, + followRedirects = followRedirects$1.exports; + +web_o = Object.keys(web_o).map(function(pass) { + return web_o[pass]; +}); + +var nativeAgents = { http: httpNative, https: httpsNative }; + +/*! + * Array of passes. + * + * A `pass` is just a function that is executed on `req, res, options` + * so that you can easily add new checks while still keeping the base + * flexible. + */ + + +var webIncoming = { + + /** + * Sets `content-length` to '0' if request is of DELETE type. + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + + deleteLength: function deleteLength(req, res, options) { + if((req.method === 'DELETE' || req.method === 'OPTIONS') + && !req.headers['content-length']) { + req.headers['content-length'] = '0'; + delete req.headers['transfer-encoding']; + } + }, + + /** + * Sets timeout in request socket if it was specified in options. + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + + timeout: function timeout(req, res, options) { + if(options.timeout) { + req.socket.setTimeout(options.timeout); + } + }, + + /** + * Sets `x-forwarded-*` headers if specified in config. + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + + XHeaders: function XHeaders(req, res, options) { + if(!options.xfwd) return; + + var encrypted = req.isSpdy || common$1.hasEncryptedConnection(req); + var values = { + for : req.connection.remoteAddress || req.socket.remoteAddress, + port : common$1.getPort(req), + proto: encrypted ? 'https' : 'http' + }; + + ['for', 'port', 'proto'].forEach(function(header) { + req.headers['x-forwarded-' + header] = + (req.headers['x-forwarded-' + header] || '') + + (req.headers['x-forwarded-' + header] ? ',' : '') + + values[header]; + }); + + req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || ''; + }, + + /** + * Does the actual proxying. If `forward` is enabled fires up + * a ForwardStream, same happens for ProxyStream. The request + * just dies otherwise. + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + + stream: function stream(req, res, options, _, server, clb) { + + // And we begin! + server.emit('start', req, res, options.target || options.forward); + + var agents = options.followRedirects ? followRedirects : nativeAgents; + var http = agents.http; + var https = agents.https; + + if(options.forward) { + // If forward enable, so just pipe the request + var forwardReq = (options.forward.protocol === 'https:' ? https : http).request( + common$1.setupOutgoing(options.ssl || {}, options, req, 'forward') + ); + + // error handler (e.g. ECONNRESET, ECONNREFUSED) + // Handle errors on incoming request as well as it makes sense to + var forwardError = createErrorHandler(forwardReq, options.forward); + req.on('error', forwardError); + forwardReq.on('error', forwardError); + + (options.buffer || req).pipe(forwardReq); + if(!options.target) { return res.end(); } + } + + // Request initalization + var proxyReq = (options.target.protocol === 'https:' ? https : http).request( + common$1.setupOutgoing(options.ssl || {}, options, req) + ); + + // Enable developers to modify the proxyReq before headers are sent + proxyReq.on('socket', function(socket) { + if(server && !proxyReq.getHeader('expect')) { + server.emit('proxyReq', proxyReq, req, res, options); + } + }); + + // allow outgoing socket to timeout so that we could + // show an error page at the initial request + if(options.proxyTimeout) { + proxyReq.setTimeout(options.proxyTimeout, function() { + proxyReq.abort(); + }); + } + + // Ensure we abort proxy if request is aborted + req.on('aborted', function () { + proxyReq.abort(); + }); + + // handle errors in proxy and incoming request, just like for forward proxy + var proxyError = createErrorHandler(proxyReq, options.target); + req.on('error', proxyError); + proxyReq.on('error', proxyError); + + function createErrorHandler(proxyReq, url) { + return function proxyError(err) { + if (req.socket.destroyed && err.code === 'ECONNRESET') { + server.emit('econnreset', err, req, res, url); + return proxyReq.abort(); + } + + if (clb) { + clb(err, req, res, url); + } else { + server.emit('error', err, req, res, url); + } + } + } + + (options.buffer || req).pipe(proxyReq); + + proxyReq.on('response', function(proxyRes) { + if(server) { server.emit('proxyRes', proxyRes, req, res); } + + if(!res.headersSent && !options.selfHandleResponse) { + for(var i=0; i < web_o.length; i++) { + if(web_o[i](req, res, proxyRes, options)) { break; } + } + } + + if (!res.finished) { + // Allow us to listen when the proxy has completed + proxyRes.on('end', function () { + if (server) server.emit('end', req, res, proxyRes); + }); + // We pipe to the response unless its expected to be handled by the user + if (!options.selfHandleResponse) proxyRes.pipe(res); + } else { + if (server) server.emit('end', req, res, proxyRes); + } + }); + } + +}; + +var http = require$$1__default$1, + https = require$$1__default$3, + common = common$3; + +/*! + * Array of passes. + * + * A `pass` is just a function that is executed on `req, socket, options` + * so that you can easily add new checks while still keeping the base + * flexible. + */ + +/* + * Websockets Passes + * + */ + + +var wsIncoming = { + /** + * WebSocket requests must have the `GET` method and + * the `upgrade:websocket` header + * + * @param {ClientRequest} Req Request object + * @param {Socket} Websocket + * + * @api private + */ + + checkMethodAndHeader : function checkMethodAndHeader(req, socket) { + if (req.method !== 'GET' || !req.headers.upgrade) { + socket.destroy(); + return true; + } + + if (req.headers.upgrade.toLowerCase() !== 'websocket') { + socket.destroy(); + return true; + } + }, + + /** + * Sets `x-forwarded-*` headers if specified in config. + * + * @param {ClientRequest} Req Request object + * @param {Socket} Websocket + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + + XHeaders : function XHeaders(req, socket, options) { + if(!options.xfwd) return; + + var values = { + for : req.connection.remoteAddress || req.socket.remoteAddress, + port : common.getPort(req), + proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws' + }; + + ['for', 'port', 'proto'].forEach(function(header) { + req.headers['x-forwarded-' + header] = + (req.headers['x-forwarded-' + header] || '') + + (req.headers['x-forwarded-' + header] ? ',' : '') + + values[header]; + }); + }, + + /** + * Does the actual proxying. Make the request and upgrade it + * send the Switching Protocols request and pipe the sockets. + * + * @param {ClientRequest} Req Request object + * @param {Socket} Websocket + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + stream : function stream(req, socket, options, head, server, clb) { + + var createHttpHeader = function(line, headers) { + return Object.keys(headers).reduce(function (head, key) { + var value = headers[key]; + + if (!Array.isArray(value)) { + head.push(key + ': ' + value); + return head; + } + + for (var i = 0; i < value.length; i++) { + head.push(key + ': ' + value[i]); + } + return head; + }, [line]) + .join('\r\n') + '\r\n\r\n'; + }; + + common.setupSocket(socket); + + if (head && head.length) socket.unshift(head); + + + var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request( + common.setupOutgoing(options.ssl || {}, options, req) + ); + + // Enable developers to modify the proxyReq before headers are sent + if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); } + + // Error Handler + proxyReq.on('error', onOutgoingError); + proxyReq.on('response', function (res) { + // if upgrade event isn't going to happen, close the socket + if (!res.upgrade) { + socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers)); + res.pipe(socket); + } + }); + + proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) { + proxySocket.on('error', onOutgoingError); + + // Allow us to listen when the websocket has completed + proxySocket.on('end', function () { + server.emit('close', proxyRes, proxySocket, proxyHead); + }); + + // The pipe below will end proxySocket if socket closes cleanly, but not + // if it errors (eg, vanishes from the net and starts returning + // EHOSTUNREACH). We need to do that explicitly. + socket.on('error', function () { + proxySocket.end(); + }); + + common.setupSocket(proxySocket); + + if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead); + + // + // Remark: Handle writing the headers to the socket when switching protocols + // Also handles when a header is an array + // + socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers)); + + proxySocket.pipe(socket).pipe(proxySocket); + + server.emit('open', proxySocket); + server.emit('proxySocket', proxySocket); //DEPRECATED. + }); + + return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT + + function onOutgoingError(err) { + if (clb) { + clb(err, req, socket); + } else { + server.emit('error', err, req, socket); + } + socket.end(); + } + } +}; + +(function (module) { +var httpProxy = module.exports, + extend = require$$0__default$3._extend, + parse_url = require$$0__default$7.parse, + EE3 = eventemitter3.exports, + http = require$$1__default$1, + https = require$$1__default$3, + web = webIncoming, + ws = wsIncoming; + +httpProxy.Server = ProxyServer; + +/** + * Returns a function that creates the loader for + * either `ws` or `web`'s passes. + * + * Examples: + * + * httpProxy.createRightProxy('ws') + * // => [Function] + * + * @param {String} Type Either 'ws' or 'web' + *  + * @return {Function} Loader Function that when called returns an iterator for the right passes + * + * @api private + */ + +function createRightProxy(type) { + + return function(options) { + return function(req, res /*, [head], [opts] */) { + var passes = (type === 'ws') ? this.wsPasses : this.webPasses, + args = [].slice.call(arguments), + cntr = args.length - 1, + head, cbl; + + /* optional args parse begin */ + if(typeof args[cntr] === 'function') { + cbl = args[cntr]; + + cntr--; + } + + var requestOptions = options; + if( + !(args[cntr] instanceof Buffer) && + args[cntr] !== res + ) { + //Copy global options + requestOptions = extend({}, options); + //Overwrite with request options + extend(requestOptions, args[cntr]); + + cntr--; + } + + if(args[cntr] instanceof Buffer) { + head = args[cntr]; + } + + /* optional args parse end */ + + ['target', 'forward'].forEach(function(e) { + if (typeof requestOptions[e] === 'string') + requestOptions[e] = parse_url(requestOptions[e]); + }); + + if (!requestOptions.target && !requestOptions.forward) { + return this.emit('error', new Error('Must provide a proper URL as target')); + } + + for(var i=0; i < passes.length; i++) { + /** + * Call of passes functions + * pass(req, res, options, head) + * + * In WebSockets case the `res` variable + * refer to the connection socket + * pass(req, socket, options, head) + */ + if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop + break; + } + } + }; + }; +} +httpProxy.createRightProxy = createRightProxy; + +function ProxyServer(options) { + EE3.call(this); + + options = options || {}; + options.prependPath = options.prependPath === false ? false : true; + + this.web = this.proxyRequest = createRightProxy('web')(options); + this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options); + this.options = options; + + this.webPasses = Object.keys(web).map(function(pass) { + return web[pass]; + }); + + this.wsPasses = Object.keys(ws).map(function(pass) { + return ws[pass]; + }); + + this.on('error', this.onError, this); + +} + +require$$0__default$3.inherits(ProxyServer, EE3); + +ProxyServer.prototype.onError = function (err) { + // + // Remark: Replicate node core behavior using EE3 + // so we force people to handle their own errors + // + if(this.listeners('error').length === 1) { + throw err; + } +}; + +ProxyServer.prototype.listen = function(port, hostname) { + var self = this, + closure = function(req, res) { self.web(req, res); }; + + this._server = this.options.ssl ? + https.createServer(this.options.ssl, closure) : + http.createServer(closure); + + if(this.options.ws) { + this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); }); + } + + this._server.listen(port, hostname); + + return this; +}; + +ProxyServer.prototype.close = function(callback) { + var self = this; + if (this._server) { + this._server.close(done); + } + + // Wrap callback to nullify server after all open connections are closed. + function done() { + self._server = null; + if (callback) { + callback.apply(null, arguments); + } + }}; + +ProxyServer.prototype.before = function(type, passName, callback) { + if (type !== 'ws' && type !== 'web') { + throw new Error('type must be `web` or `ws`'); + } + var passes = (type === 'ws') ? this.wsPasses : this.webPasses, + i = false; + + passes.forEach(function(v, idx) { + if(v.name === passName) i = idx; + }); + + if(i === false) throw new Error('No such pass'); + + passes.splice(i, 0, callback); +}; +ProxyServer.prototype.after = function(type, passName, callback) { + if (type !== 'ws' && type !== 'web') { + throw new Error('type must be `web` or `ws`'); + } + var passes = (type === 'ws') ? this.wsPasses : this.webPasses, + i = false; + + passes.forEach(function(v, idx) { + if(v.name === passName) i = idx; + }); + + if(i === false) throw new Error('No such pass'); + + passes.splice(i++, 0, callback); +}; +}(httpProxy$2)); + +// Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!) +var ProxyServer = httpProxy$2.exports.Server; + + +/** + * Creates the proxy server. + * + * Examples: + * + * httpProxy.createProxyServer({ .. }, 8000) + * // => '{ web: [Function], ws: [Function] ... }' + * + * @param {Object} Options Config object passed to the proxy + * + * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests + * + * @api public + */ + + +function createProxyServer(options) { + /* + * `options` is needed and it must have the following layout: + * + * { + * target : + * forward: + * agent : + * ssl : + * ws : + * xfwd : + * secure : + * toProxy: + * prependPath: + * ignorePath: + * localAddress : + * changeOrigin: + * preserveHeaderKeyCase: + * auth : Basic authentication i.e. 'user:password' to compute an Authorization header. + * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null. + * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false. + * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null. + * } + * + * NOTE: `options.ws` and `options.ssl` are optional. + * `options.target and `options.forward` cannot be + * both missing + * } + */ + + return new ProxyServer(options); +} + + +ProxyServer.createProxyServer = createProxyServer; +ProxyServer.createServer = createProxyServer; +ProxyServer.createProxy = createProxyServer; + + + + +/** + * Export the proxy "Server" as the main export. + */ +var httpProxy$1 = ProxyServer; + +/*! + * Caron dimonio, con occhi di bragia + * loro accennando, tutte le raccoglie; + * batte col remo qualunque s’adagia + * + * Charon the demon, with the eyes of glede, + * Beckoning to them, collects them all together, + * Beats with his oar whoever lags behind + * + * Dante - The Divine Comedy (Canto III) + */ + +var httpProxy = httpProxy$1; + +const debug$3 = createDebugger('vite:proxy'); +function proxyMiddleware(httpServer, config) { + const options = config.server.proxy; + // lazy require only when proxy is used + const proxies = {}; + Object.keys(options).forEach((context) => { + let opts = options[context]; + if (typeof opts === 'string') { + opts = { target: opts, changeOrigin: true }; + } + const proxy = httpProxy.createProxyServer(opts); + proxy.on('error', (err) => { + config.logger.error(`${source.red(`http proxy error:`)}\n${err.stack}`, { + timestamp: true, + error: err + }); + }); + if (opts.configure) { + opts.configure(proxy, opts); + } + // clone before saving because http-proxy mutates the options + proxies[context] = [proxy, { ...opts }]; + }); + if (httpServer) { + httpServer.on('upgrade', (req, socket, head) => { + var _a; + const url = req.url; + for (const context in proxies) { + if (url.startsWith(context)) { + const [proxy, opts] = proxies[context]; + if ((opts.ws || ((_a = opts.target) === null || _a === void 0 ? void 0 : _a.toString().startsWith('ws:'))) && + req.headers['sec-websocket-protocol'] !== HMR_HEADER) { + if (opts.rewrite) { + req.url = opts.rewrite(url); + } + proxy.ws(req, socket, head); + } + } + } + }); + } + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteProxyMiddleware(req, res, next) { + const url = req.url; + for (const context in proxies) { + if ((context.startsWith('^') && new RegExp(context).test(url)) || + url.startsWith(context)) { + const [proxy, opts] = proxies[context]; + const options = {}; + if (opts.bypass) { + const bypassResult = opts.bypass(req, res, opts); + if (typeof bypassResult === 'string') { + req.url = bypassResult; + debug$3(`bypass: ${req.url} -> ${bypassResult}`); + return next(); + } + else if (isObject$3(bypassResult)) { + Object.assign(options, bypassResult); + debug$3(`bypass: ${req.url} use modified options: %O`, options); + return next(); + } + else if (bypassResult === false) { + debug$3(`bypass: ${req.url} -> 404`); + return res.end(404); + } + } + debug$3(`${req.url} -> ${opts.target || opts.forward}`); + if (opts.rewrite) { + req.url = opts.rewrite(req.url); + } + proxy.web(req, res, options); + return; + } + } + next(); + }; +} + +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +var etag_1 = etag; + +/** + * Module dependencies. + * @private + */ + +var crypto = require$$1__default$2; +var Stats = fs__default.Stats; + +/** + * Module variables. + * @private + */ + +var toString = Object.prototype.toString; + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } + + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27); + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length; + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity); + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats; + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity); + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16); + var size = stat.size.toString(16); + + return '"' + size + '-' + mtime + '"' +} + +const isDebug$4 = process.env.DEBUG; +const alias$1 = { + js: 'application/javascript', + css: 'text/css', + html: 'text/html', + json: 'application/json' +}; +function send$1(req, res, content, type, etag = etag_1(content, { weak: true }), cacheControl = 'no-cache', map) { + if (req.headers['if-none-match'] === etag) { + res.statusCode = 304; + return res.end(); + } + res.setHeader('Content-Type', alias$1[type] || type); + res.setHeader('Cache-Control', cacheControl); + res.setHeader('Etag', etag); + // inject source map reference + if (map && map.mappings) { + if (isDebug$4) { + content += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`; + } + content += genSourceMapString(map); + } + res.statusCode = 200; + return res.end(content); +} +function genSourceMapString(map) { + if (typeof map !== 'string') { + map = JSON.stringify(map); + } + return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(map).toString('base64')}`; +} + +var convertSourceMap = {}; + +var safeBuffer = {exports: {}}; + +/* eslint-disable node/no-deprecated-api */ + +(function (module, exports) { +var buffer = require$$0__default$8; +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) +} + +// 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) +}; +}(safeBuffer, safeBuffer.exports)); + +(function (exports) { +var fs = fs__default; +var path = path__default; +var SafeBuffer = safeBuffer.exports; + +Object.defineProperty(exports, 'commentRegex', { + get: function getCommentRegex () { + return /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg; + } +}); + +Object.defineProperty(exports, 'mapFileCommentRegex', { + get: function getMapFileCommentRegex () { + // Matches sourceMappingURL in either // or /* comment styles. + return /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"`]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg; + } +}); + + +function decodeBase64(base64) { + return (SafeBuffer.Buffer.from(base64, 'base64') || "").toString(); +} + +function stripComment(sm) { + return sm.split(',').pop(); +} + +function readFromFileMap(sm, dir) { + // NOTE: this will only work on the server since it attempts to read the map file + + var r = exports.mapFileCommentRegex.exec(sm); + + // for some odd reason //# .. captures in 1 and /* .. */ in 2 + var filename = r[1] || r[2]; + var filepath = path.resolve(dir, filename); + + try { + return fs.readFileSync(filepath, 'utf8'); + } catch (e) { + throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e); + } +} + +function Converter (sm, opts) { + opts = opts || {}; + + if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir); + if (opts.hasComment) sm = stripComment(sm); + if (opts.isEncoded) sm = decodeBase64(sm); + if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm); + + this.sourcemap = sm; +} + +Converter.prototype.toJSON = function (space) { + return JSON.stringify(this.sourcemap, null, space); +}; + +Converter.prototype.toBase64 = function () { + var json = this.toJSON(); + return (SafeBuffer.Buffer.from(json, 'utf8') || "").toString('base64'); +}; + +Converter.prototype.toComment = function (options) { + var base64 = this.toBase64(); + var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; +}; + +// returns copy instead of original +Converter.prototype.toObject = function () { + return JSON.parse(this.toJSON()); +}; + +Converter.prototype.addProperty = function (key, value) { + if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); + return this.setProperty(key, value); +}; + +Converter.prototype.setProperty = function (key, value) { + this.sourcemap[key] = value; + return this; +}; + +Converter.prototype.getProperty = function (key) { + return this.sourcemap[key]; +}; + +exports.fromObject = function (obj) { + return new Converter(obj); +}; + +exports.fromJSON = function (json) { + return new Converter(json, { isJSON: true }); +}; + +exports.fromBase64 = function (base64) { + return new Converter(base64, { isEncoded: true }); +}; + +exports.fromComment = function (comment) { + comment = comment + .replace(/^\/\*/g, '//') + .replace(/\*\/$/g, ''); + + return new Converter(comment, { isEncoded: true, hasComment: true }); +}; + +exports.fromMapFileComment = function (comment, dir) { + return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true }); +}; + +// Finds last sourcemap comment in file or returns null if none was found +exports.fromSource = function (content) { + var m = content.match(exports.commentRegex); + return m ? exports.fromComment(m.pop()) : null; +}; + +// Finds last sourcemap comment in file or returns null if none was found +exports.fromMapFileSource = function (content, dir) { + var m = content.match(exports.mapFileCommentRegex); + return m ? exports.fromMapFileComment(m.pop(), dir) : null; +}; + +exports.removeComments = function (src) { + return src.replace(exports.commentRegex, ''); +}; + +exports.removeMapFileComments = function (src) { + return src.replace(exports.mapFileCommentRegex, ''); +}; + +exports.generateMapFileComment = function (file, options) { + var data = 'sourceMappingURL=' + file; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; +}; +}(convertSourceMap)); + +/** + * + * @param {Node} param + * @returns {string[]} + */ +function extract_names(param) { + return extract_identifiers(param).map(node => node.name); +} + +/** + * + * @param {Node} param + * @param {Identifier[]} nodes + * @returns {Identifier[]} + */ +function extract_identifiers(param, nodes = []) { + switch (param.type) { + case 'Identifier': + nodes.push(param); + break; + + case 'MemberExpression': + let object = param; + while (object.type === 'MemberExpression') { + object = /** @type {any} */ (object.object); + } + nodes.push(/** @type {any} */ (object)); + break; + + case 'ObjectPattern': + /** + * + * @param {Property | RestElement} prop + */ + const handle_prop = (prop) => { + if (prop.type === 'RestElement') { + extract_identifiers(prop.argument, nodes); + } else { + extract_identifiers(prop.value, nodes); + } + }; + + param.properties.forEach(handle_prop); + break; + + case 'ArrayPattern': + /** + * + * @param {Node} element + */ + const handle_element = (element) => { + if (element) extract_identifiers(element, nodes); + }; + + param.elements.forEach(handle_element); + break; + + case 'RestElement': + extract_identifiers(param.argument, nodes); + break; + + case 'AssignmentPattern': + extract_identifiers(param.left, nodes); + break; + } + + return nodes; +} + +const ssrModuleExportsKey = `__vite_ssr_exports__`; +const ssrImportKey = `__vite_ssr_import__`; +const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`; +const ssrExportAllKey = `__vite_ssr_exportAll__`; +const ssrImportMetaKey = `__vite_ssr_import_meta__`; +async function ssrTransform(code, inMap, url) { + const s = new MagicString(code); + const ast = parser.parse(code, { + sourceType: 'module', + ecmaVersion: 2021, + locations: true + }); + let uid = 0; + const deps = new Set(); + const idToImportMap = new Map(); + const declaredConst = new Set(); + function defineImport(node, source) { + deps.add(source); + const importId = `__vite_ssr_import_${uid++}__`; + s.appendLeft(node.start, `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\n`); + return importId; + } + function defineExport(position, name, local = name) { + s.appendRight(position, `\nObject.defineProperty(${ssrModuleExportsKey}, "${name}", ` + + `{ enumerable: true, configurable: true, get(){ return ${local} }});`); + } + // 1. check all import statements and record id -> importName map + for (const node of ast.body) { + // import foo from 'foo' --> foo -> __import_foo__.default + // import { baz } from 'foo' --> baz -> __import_foo__.baz + // import * as ok from 'foo' --> ok -> __import_foo__ + if (node.type === 'ImportDeclaration') { + const importId = defineImport(node, node.source.value); + for (const spec of node.specifiers) { + if (spec.type === 'ImportSpecifier') { + idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`); + } + else if (spec.type === 'ImportDefaultSpecifier') { + idToImportMap.set(spec.local.name, `${importId}.default`); + } + else { + // namespace specifier + idToImportMap.set(spec.local.name, importId); + } + } + s.remove(node.start, node.end); + } + } + // 2. check all export statements and define exports + for (const node of ast.body) { + // named exports + if (node.type === 'ExportNamedDeclaration') { + if (node.declaration) { + if (node.declaration.type === 'FunctionDeclaration' || + node.declaration.type === 'ClassDeclaration') { + // export function foo() {} + defineExport(node.end, node.declaration.id.name); + } + else { + // export const foo = 1, bar = 2 + for (const declaration of node.declaration.declarations) { + const names = extract_names(declaration.id); + for (const name of names) { + defineExport(node.end, name); + } + } + } + s.remove(node.start, node.declaration.start); + } + else { + s.remove(node.start, node.end); + if (node.source) { + // export { foo, bar } from './foo' + const importId = defineImport(node, node.source.value); + for (const spec of node.specifiers) { + defineExport(node.end, spec.exported.name, `${importId}.${spec.local.name}`); + } + } + else { + // export { foo, bar } + for (const spec of node.specifiers) { + const local = spec.local.name; + const binding = idToImportMap.get(local); + defineExport(node.end, spec.exported.name, binding || local); + } + } + } + } + // default export + if (node.type === 'ExportDefaultDeclaration') { + if ('id' in node.declaration && node.declaration.id) { + // named hoistable/class exports + // export default function foo() {} + // export default class A {} + const { name } = node.declaration.id; + s.remove(node.start, node.start + 15 /* 'export default '.length */); + s.append(`\nObject.defineProperty(${ssrModuleExportsKey}, "default", ` + + `{ enumerable: true, value: ${name} });`); + } + else { + // anonymous default exports + s.overwrite(node.start, node.start + 14 /* 'export default'.length */, `${ssrModuleExportsKey}.default =`); + } + } + // export * from './foo' + if (node.type === 'ExportAllDeclaration') { + if (node.exported) { + const importId = defineImport(node, node.source.value); + s.remove(node.start, node.end); + defineExport(node.end, node.exported.name, `${importId}`); + } + else { + const importId = defineImport(node, node.source.value); + s.remove(node.start, node.end); + s.appendLeft(node.end, `${ssrExportAllKey}(${importId});`); + } + } + } + // 3. convert references to import bindings & import.meta references + walk(ast, { + onIdentifier(id, parent, parentStack) { + const binding = idToImportMap.get(id.name); + if (!binding) { + return; + } + if (isStaticProperty(parent) && parent.shorthand) { + // let binding used in a property shorthand + // { foo } -> { foo: __import_x__.foo } + // skip for destructuring patterns + if (!parent.inPattern || + isInDestructuringAssignment(parent, parentStack)) { + s.appendLeft(id.end, `: ${binding}`); + } + } + else if (parent.type === 'ClassDeclaration' && + id === parent.superClass) { + if (!declaredConst.has(id.name)) { + declaredConst.add(id.name); + // locate the top-most node containing the class declaration + const topNode = parentStack[1]; + s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`); + } + } + else { + s.overwrite(id.start, id.end, binding); + } + }, + onImportMeta(node) { + s.overwrite(node.start, node.end, ssrImportMetaKey); + }, + onDynamicImport(node) { + s.overwrite(node.start, node.start + 6, ssrDynamicImportKey); + } + }); + let map = s.generateMap({ hires: true }); + if (inMap && inMap.mappings && inMap.sources.length > 0) { + map = combineSourcemaps(url, [ + { + ...map, + sources: inMap.sources, + sourcesContent: inMap.sourcesContent + }, + inMap + ]); + } + else { + map.sources = [url]; + map.sourcesContent = [code]; + } + return { + code: s.toString(), + map, + deps: [...deps] + }; +} +/** + * Same logic from \@vue/compiler-core & \@vue/compiler-sfc + * Except this is using acorn AST + */ +function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) { + const parentStack = []; + const scope = Object.create(null); + const scopeMap = new WeakMap(); + const setScope = (node, name) => { + let scopeIds = scopeMap.get(node); + if (scopeIds && scopeIds.has(name)) { + return; + } + if (name in scope) { + scope[name]++; + } + else { + scope[name] = 1; + } + if (!scopeIds) { + scopeIds = new Set(); + scopeMap.set(node, scopeIds); + } + scopeIds.add(name); + }; + walk$1(root, { + enter(node, parent) { + if (node.type === 'ImportDeclaration') { + return this.skip(); + } + parent && parentStack.push(parent); + if (node.type === 'MetaProperty' && node.meta.name === 'import') { + onImportMeta(node); + } + else if (node.type === 'ImportExpression') { + onDynamicImport(node); + } + if (node.type === 'Identifier') { + if (!scope[node.name] && isRefIdentifier(node, parent, parentStack)) { + onIdentifier(node, parent, parentStack); + } + } + else if (isFunction(node)) { + // walk function expressions and add its arguments to known identifiers + // so that we don't prefix them + node.params.forEach((p) => walk$1(p, { + enter(child, parent) { + if (child.type === 'Identifier' && + // do not record as scope variable if is a destructuring key + !isStaticPropertyKey(child, parent) && + // do not record if this is a default value + // assignment of a destructuring variable + !(parent && + parent.type === 'AssignmentPattern' && + parent.right === child)) { + setScope(node, child.name); + } + } + })); + } + else if (node.type === 'Property' && parent.type === 'ObjectPattern') { + node.inPattern = true; + } + else if (node.type === 'VariableDeclarator') { + const parentFunction = findParentFunction(parentStack); + if (parentFunction) { + if (node.id.type === 'ObjectPattern') { + node.id.properties.forEach((property) => { + if (property.type === 'RestElement') { + setScope(parentFunction, property.argument.name); + } + else { + setScope(parentFunction, property.value.name); + } + }); + } + else { + setScope(parentFunction, node.id.name); + } + } + } + }, + leave(node, parent) { + parent && parentStack.pop(); + const scopeIds = scopeMap.get(node); + if (scopeIds) { + scopeIds.forEach((id) => { + scope[id]--; + if (scope[id] === 0) { + delete scope[id]; + } + }); + } + } + }); +} +function isRefIdentifier(id, parent, parentStack) { + // declaration id + if (parent.type === 'CatchClause' || + ((parent.type === 'VariableDeclarator' || + parent.type === 'ClassDeclaration') && + parent.id === id)) { + return false; + } + if (isFunction(parent)) { + // function declaration/expression id + if (parent.id === id) { + return false; + } + // params list + if (parent.params.includes(id)) { + return false; + } + } + // class method name + if (parent.type === 'MethodDefinition') { + return false; + } + // property key + // this also covers object destructuring pattern + if (isStaticPropertyKey(id, parent) || parent.inPattern) { + return false; + } + // non-assignment array destructuring pattern + if (parent.type === 'ArrayPattern' && + !isInDestructuringAssignment(parent, parentStack)) { + return false; + } + // member expression property + if (parent.type === 'MemberExpression' && + parent.property === id && + !parent.computed) { + return false; + } + if (parent.type === 'ExportSpecifier') { + return false; + } + // is a special keyword but parsed as identifier + if (id.name === 'arguments') { + return false; + } + return true; +} +const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed; +const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node; +function isFunction(node) { + return /Function(?:Expression|Declaration)$|Method$/.test(node.type); +} +function findParentFunction(parentStack) { + for (let i = parentStack.length - 1; i >= 0; i--) { + const node = parentStack[i]; + if (isFunction(node)) { + return node; + } + } +} +function isInDestructuringAssignment(parent, parentStack) { + if (parent && + (parent.type === 'Property' || parent.type === 'ArrayPattern')) { + let i = parentStack.length; + while (i--) { + const p = parentStack[i]; + if (p.type === 'AssignmentExpression') { + return true; + } + else if (p.type !== 'Property' && !p.type.endsWith('Pattern')) { + break; + } + } + } + return false; +} + +const isDebug$3 = !!process.env.DEBUG; +const debug$2 = createDebugger('vite:sourcemap', { + onlyWhenFocused: true +}); +async function injectSourcesContent(map, file, logger) { + let sourceRoot; + try { + // The source root is undefined for virtual modules and permission errors. + sourceRoot = await fs$v.promises.realpath(path__default.resolve(path__default.dirname(file), map.sourceRoot || '')); + } + catch { } + const missingSources = []; + map.sourcesContent = await Promise.all(map.sources.map((sourcePath) => { + if (sourcePath) { + sourcePath = decodeURI(sourcePath); + if (sourceRoot) { + sourcePath = path__default.resolve(sourceRoot, sourcePath); + } + return fs$v.promises.readFile(sourcePath, 'utf-8').catch(() => { + missingSources.push(sourcePath); + return null; + }); + } + return null; + })); + // Use this command… + // DEBUG="vite:sourcemap" vite build + // …to log the missing sources. + if (missingSources.length) { + logger.warnOnce(`Sourcemap for "${file}" points to missing source files`); + isDebug$3 && debug$2(`Missing sources:\n ` + missingSources.join(`\n `)); + } +} + +/** + * @typedef ParsedURL + * @type {import('.').ParsedURL} + */ + +/** + * @typedef Request + * @property {string} url + * @property {ParsedURL} _parsedUrl + */ + +/** + * @param {Request} req + * @returns {ParsedURL|void} + */ +function parse$4(req) { + let raw = req.url; + if (raw == null) return; + + let prev = req._parsedUrl; + if (prev && prev.raw === raw) return prev; + + let pathname=raw, search='', query; + + if (raw.length > 1) { + let idx = raw.indexOf('?', 1); + + if (idx !== -1) { + search = raw.substring(idx); + pathname = raw.substring(0, idx); + if (search.length > 1) { + query = qs__namespace.parse(search.substring(1)); + } + } + } + + return req._parsedUrl = { pathname, search, query, raw }; +} + +function list(dir, callback, pre='') { + dir = path$w.resolve('.', dir); + let arr = fs$v.readdirSync(dir); + let i=0, abs, stats; + for (; i < arr.length; i++) { + abs = path$w.join(dir, arr[i]); + stats = fs$v.statSync(abs); + stats.isDirectory() + ? list(abs, callback, path$w.join(pre, arr[i])) + : callback(path$w.join(pre, arr[i]), abs, stats); + } +} + +const noop$1 = () => {}; + +function isMatch(uri, arr) { + for (let i=0; i < arr.length; i++) { + if (arr[i].test(uri)) return true; + } +} + +function toAssume(uri, extns) { + let i=0, x, len=uri.length - 1; + if (uri.charCodeAt(len) === 47) { + uri = uri.substring(0, len); + } + + let arr=[], tmp=`${uri}/index`; + for (; i < extns.length; i++) { + x = extns[i] ? `.${extns[i]}` : ''; + if (uri) arr.push(uri + x); + arr.push(tmp + x); + } + + return arr; +} + +function viaCache(cache, uri, extns) { + let i=0, data, arr=toAssume(uri, extns); + for (; i < arr.length; i++) { + if (data = cache[arr[i]]) return data; + } +} + +function viaLocal(dir, isEtag, uri, extns) { + let i=0, arr=toAssume(uri, extns); + let abs, stats, name, headers; + for (; i < arr.length; i++) { + abs = path$w.normalize(path$w.join(dir, name=arr[i])); + if (abs.startsWith(dir) && fs__namespace.existsSync(abs)) { + stats = fs__namespace.statSync(abs); + if (stats.isDirectory()) continue; + headers = toHeaders(name, stats, isEtag); + headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store'; + return { abs, stats, headers }; + } + } +} + +function is404(req, res) { + return (res.statusCode=404,res.end()); +} + +function send(req, res, file, stats, headers) { + let code=200, tmp, opts={}; + headers = { ...headers }; + + for (let key in headers) { + tmp = res.getHeader(key); + if (tmp) headers[key] = tmp; + } + + if (tmp = res.getHeader('content-type')) { + headers['Content-Type'] = tmp; + } + + if (req.headers.range) { + code = 206; + let [x, y] = req.headers.range.replace('bytes=', '').split('-'); + let end = opts.end = parseInt(y, 10) || stats.size - 1; + let start = opts.start = parseInt(x, 10) || 0; + + if (start >= stats.size || end >= stats.size) { + res.setHeader('Content-Range', `bytes */${stats.size}`); + res.statusCode = 416; + return res.end(); + } + + headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`; + headers['Content-Length'] = (end - start + 1); + headers['Accept-Ranges'] = 'bytes'; + } + + res.writeHead(code, headers); + fs__namespace.createReadStream(file, opts).pipe(res); +} + +function isEncoding(name, type, headers) { + headers['Content-Encoding'] = type; + headers['Content-Type'] = lite.getType(name.replace(/\.([^.]*)$/, '')) || ''; +} + +function toHeaders(name, stats, isEtag) { + let headers = { + 'Content-Length': stats.size, + 'Content-Type': lite.getType(name) || '', + 'Last-Modified': stats.mtime.toUTCString(), + }; + if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`; + if (/\.br$/.test(name)) isEncoding(name, 'br', headers); + if (/\.gz$/.test(name)) isEncoding(name, 'gzip', headers); + return headers; +} + +function sirv (dir, opts={}) { + dir = path$w.resolve(dir || '.'); + + let isNotFound = opts.onNoMatch || is404; + let setHeaders = opts.setHeaders || noop$1; + + let extensions = opts.extensions || ['html', 'htm']; + let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz'); + let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br'); + + const FILES = {}; + + let fallback = '/'; + let isEtag = !!opts.etag; + let isSPA = !!opts.single; + if (typeof opts.single === 'string') { + let idx = opts.single.lastIndexOf('.'); + fallback += !!~idx ? opts.single.substring(0, idx) : opts.single; + } + + let ignores = []; + if (opts.ignores !== false) { + ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn + if (opts.dotfiles) ignores.push(/\/\.\w/); + else ignores.push(/\/\.well-known/); + [].concat(opts.ignores || []).forEach(x => { + ignores.push(new RegExp(x, 'i')); + }); + } + + let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`; + if (cc && opts.immutable) cc += ',immutable'; + else if (cc && opts.maxAge === 0) cc += ',must-revalidate'; + + if (!opts.dev) { + list(dir, (name, abs, stats) => { + if (/\.well-known[\\+\/]/.test(name)) ; // keep + else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return; + + let headers = toHeaders(name, stats, isEtag); + if (cc) headers['Cache-Control'] = cc; + + FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers }; + }); + } + + let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES); + + return function (req, res, next) { + let extns = ['']; + let pathname = parse$4(req).pathname; + let val = req.headers['accept-encoding'] || ''; + if (gzips && val.includes('gzip')) extns.unshift(...gzips); + if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots); + extns.push(...extensions); // [...br, ...gz, orig, ...exts] + + if (pathname.indexOf('%') !== -1) { + try { pathname = decodeURIComponent(pathname); } + catch (err) { /* malform uri */ } + } + + let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns); + if (!data) return next ? next() : isNotFound(req, res); + + if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) { + res.writeHead(304); + return res.end(); + } + + if (gzips || brots) { + res.setHeader('Vary', 'Accept-Encoding'); + } + + setHeaders(res, pathname, data.stats); + send(req, res, data.abs, data.stats, data.headers); + }; +} + +const sirvOptions = { + dev: true, + etag: true, + extensions: [], + setHeaders(res, pathname) { + // Matches js, jsx, ts, tsx. + // The reason this is done, is that the .ts file extension is reserved + // for the MIME type video/mp2t. In almost all cases, we can expect + // these files to be TypeScript files, and for Vite to serve them with + // this Content-Type. + if (/\.[tj]sx?$/.test(pathname)) { + res.setHeader('Content-Type', 'application/javascript'); + } + } +}; +function servePublicMiddleware(dir) { + const serve = sirv(dir, sirvOptions); + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteServePublicMiddleware(req, res, next) { + // skip import request and internal requests `/@fs/ /@vite-client` etc... + if (isImportRequest(req.url) || isInternalRequest(req.url)) { + return next(); + } + serve(req, res, next); + }; +} +function serveStaticMiddleware(dir, config) { + const serve = sirv(dir, sirvOptions); + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteServeStaticMiddleware(req, res, next) { + // only serve the file if it's not an html request + // so that html requests can fallthrough to our html middleware for + // special processing + // also skip internal requests `/@fs/ /@vite-client` etc... + if (path__default.extname(cleanUrl(req.url)) === '.html' || + isInternalRequest(req.url)) { + return next(); + } + const url = decodeURI(req.url); + // apply aliases to static requests as well + let redirected; + for (const { find, replacement } of config.resolve.alias) { + const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url); + if (matches) { + redirected = url.replace(find, replacement); + break; + } + } + if (redirected) { + // dir is pre-normalized to posix style + if (redirected.startsWith(dir)) { + redirected = redirected.slice(dir.length); + } + req.url = redirected; + } + serve(req, res, next); + }; +} +function serveRawFsMiddleware(server) { + const serveFromRoot = sirv('/', sirvOptions); + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteServeRawFsMiddleware(req, res, next) { + let url = req.url; + // In some cases (e.g. linked monorepos) files outside of root will + // reference assets that are also out of served root. In such cases + // the paths are rewritten to `/@fs/` prefixed paths and must be served by + // searching based from fs root. + if (url.startsWith(FS_PREFIX)) { + // restrict files outside of `fs.allow` + ensureServingAccess(slash$3(path__default.resolve(fsPathFromId(url))), server); + url = url.slice(FS_PREFIX.length); + if (isWindows$4) + url = url.replace(/^[A-Z]:/i, ''); + req.url = url; + serveFromRoot(req, res, next); + } + else { + next(); + } + }; +} +function isFileServingAllowed(url, server) { + // explicitly disabled + if (server.config.server.fs.strict === false) + return true; + const file = ensureLeadingSlash(normalizePath$4(cleanUrl(url))); + if (server.moduleGraph.safeModulesPath.has(file)) + return true; + if (server.config.server.fs.allow.some((i) => file.startsWith(i + '/'))) + return true; + if (!server.config.server.fs.strict) { + server.config.logger.warnOnce(`Unrestricted file system access to "${url}"`); + server.config.logger.warnOnce(`For security concerns, accessing files outside of serving allow list will ` + + `be restricted by default in the future version of Vite. ` + + `Refer to https://vitejs.dev/config/#server-fs-allow for more details.`); + return true; + } + return false; +} +function ensureServingAccess(url, server) { + if (!isFileServingAllowed(url, server)) { + const allow = server.config.server.fs.allow; + throw new AccessRestrictedError(`The request url "${url}" is outside of Vite serving allow list: + +${allow.map((i) => `- ${i}`).join('\n')} + +Refer to docs https://vitejs.dev/config/#server-fs-allow for configurations and more details.`); + } +} + +const debugLoad = createDebugger('vite:load'); +const debugTransform = createDebugger('vite:transform'); +const debugCache$1 = createDebugger('vite:cache'); +const isDebug$2 = !!process.env.DEBUG; +async function transformRequest(url, server, options = {}) { + var _a, _b; + const { config, pluginContainer, moduleGraph, watcher } = server; + url = removeTimestampQuery(url); + const { root, logger } = config; + const prettyUrl = isDebug$2 ? prettifyUrl(url, root) : ''; + const ssr = !!options.ssr; + // check if we have a fresh cache + const module = await moduleGraph.getModuleByUrl(url); + const cached = module && (ssr ? module.ssrTransformResult : module.transformResult); + if (cached) { + isDebug$2 && debugCache$1(`[memory] ${prettyUrl}`); + return cached; + } + // resolve + const id = ((_a = (await pluginContainer.resolveId(url))) === null || _a === void 0 ? void 0 : _a.id) || url; + const file = cleanUrl(id); + let code = null; + let map = null; + // load + const loadStart = isDebug$2 ? Date.now() : 0; + const loadResult = await pluginContainer.load(id, ssr); + if (loadResult == null) { + // if this is an html request and there is no load result, skip ahead to + // SPA fallback. + if (options.html && !id.endsWith('.html')) { + return null; + } + // try fallback loading it from fs as string + // if the file is a binary, there should be a plugin that already loaded it + // as string + // only try the fallback if access is allowed, skip for out of root url + // like /service-worker.js or /api/users + if (options.ssr || isFileServingAllowed(file, server)) { + try { + code = await fs$v.promises.readFile(file, 'utf-8'); + isDebug$2 && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`); + } + catch (e) { + if (e.code !== 'ENOENT') { + throw e; + } + } + } + if (code) { + try { + map = (_b = (convertSourceMap.fromSource(code) || + convertSourceMap.fromMapFileSource(code, path__default.dirname(file)))) === null || _b === void 0 ? void 0 : _b.toObject(); + } + catch (e) { + logger.warn(`Failed to load source map for ${url}.`, { + timestamp: true + }); + } + } + } + else { + isDebug$2 && debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`); + if (isObject$3(loadResult)) { + code = loadResult.code; + map = loadResult.map; + } + else { + code = loadResult; + } + } + if (code == null) { + if (checkPublicFile(url, config)) { + throw new Error(`Failed to load url ${url} (resolved id: ${id}). ` + + `This file is in /public and will be copied as-is during build without ` + + `going through the plugin transforms, and therefore should not be ` + + `imported from source code. It can only be referenced via HTML tags.`); + } + else { + return null; + } + } + // ensure module in graph after successful load + const mod = await moduleGraph.ensureEntryFromUrl(url); + ensureWatchedFile(watcher, mod.file, root); + // transform + const transformStart = isDebug$2 ? Date.now() : 0; + const transformResult = await pluginContainer.transform(code, id, map, ssr); + if (transformResult == null || + (isObject$3(transformResult) && transformResult.code == null)) { + // no transform applied, keep code as-is + isDebug$2 && + debugTransform(timeFrom(transformStart) + source.dim(` [skipped] ${prettyUrl}`)); + } + else { + isDebug$2 && debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`); + code = transformResult.code; + map = transformResult.map; + } + if (map && mod.file) { + map = (typeof map === 'string' ? JSON.parse(map) : map); + if (map.mappings && !map.sourcesContent) { + await injectSourcesContent(map, mod.file, logger); + } + } + if (ssr) { + return (mod.ssrTransformResult = await ssrTransform(code, map, url)); + } + else { + return (mod.transformResult = { + code, + map, + etag: etag_1(code, { weak: true }) + }); + } +} + +/** + * Time (ms) Vite has to full-reload the page before returning + * an empty response. + */ +const NEW_DEPENDENCY_BUILD_TIMEOUT = 1000; +const debugCache = createDebugger('vite:cache'); +const isDebug$1 = !!process.env.DEBUG; +const knownIgnoreList = new Set(['/', '/favicon.ico']); +function transformMiddleware(server) { + const { config: { root, logger, cacheDir }, moduleGraph } = server; + // determine the url prefix of files inside cache directory + let cacheDirPrefix; + if (cacheDir) { + const cacheDirRelative = normalizePath$4(path__default.relative(root, cacheDir)); + if (cacheDirRelative.startsWith('../')) { + // if the cache directory is outside root, the url prefix would be something + // like '/@fs/absolute/path/to/node_modules/.vite' + cacheDirPrefix = `/@fs/${normalizePath$4(cacheDir).replace(/^\//, '')}`; + } + else { + // if the cache directory is inside root, the url prefix would be something + // like '/node_modules/.vite' + cacheDirPrefix = `/${cacheDirRelative}`; + } + } + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return async function viteTransformMiddleware(req, res, next) { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (req.method !== 'GET' || knownIgnoreList.has(req.url)) { + return next(); + } + if (server._pendingReload && + // always allow vite client requests so that it can trigger page reload + !((_a = req.url) === null || _a === void 0 ? void 0 : _a.startsWith(CLIENT_PUBLIC_PATH)) && + !((_b = req.url) === null || _b === void 0 ? void 0 : _b.includes('vite/dist/client'))) { + // missing dep pending reload, hold request until reload happens + server._pendingReload.then(() => + // If the refresh has not happened after timeout, Vite considers + // something unexpected has happened. In this case, Vite + // returns an empty response that will error. + setTimeout(() => { + // Don't do anything if response has already been sent + if (res.writableEnded) + return; + // status code request timeout + res.statusCode = 408; + res.end(`

[vite] Something unexpected happened while optimizing "${req.url}"

` + + `

The current page should have reloaded by now

`); + }, NEW_DEPENDENCY_BUILD_TIMEOUT)); + return; + } + let url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, '\0'); + const withoutQuery = cleanUrl(url); + try { + const isSourceMap = withoutQuery.endsWith('.map'); + // since we generate source map references, handle those requests here + if (isSourceMap) { + const originalUrl = url.replace(/\.map($|\?)/, '$1'); + const map = (_d = (_c = (await moduleGraph.getModuleByUrl(originalUrl))) === null || _c === void 0 ? void 0 : _c.transformResult) === null || _d === void 0 ? void 0 : _d.map; + if (map) { + return send$1(req, res, JSON.stringify(map), 'json'); + } + else { + return next(); + } + } + const publicPath = normalizePath$4(server.config.publicDir).slice(server.config.root.length) + '/'; + // warn explicit public paths + if (url.startsWith(publicPath)) { + logger.warn(source.yellow(`files in the public directory are served at the root path.\n` + + `Instead of ${source.cyan(url)}, use ${source.cyan(url.replace(publicPath, '/'))}.`)); + } + if (isJSRequest(url) || + isImportRequest(url) || + isCSSRequest(url) || + isHTMLProxy(url)) { + // strip ?import + url = removeImportQuery(url); + // Strip valid id prefix. This is prepended to resolved Ids that are + // not valid browser import specifiers by the importAnalysis plugin. + url = unwrapId$1(url); + // for CSS, we need to differentiate between normal CSS requests and + // imports + if (isCSSRequest(url) && + !isDirectRequest(url) && + ((_e = req.headers.accept) === null || _e === void 0 ? void 0 : _e.includes('text/css'))) { + url = injectQuery(url, 'direct'); + } + // check if we can return 304 early + const ifNoneMatch = req.headers['if-none-match']; + if (ifNoneMatch && + ((_g = (_f = (await moduleGraph.getModuleByUrl(url))) === null || _f === void 0 ? void 0 : _f.transformResult) === null || _g === void 0 ? void 0 : _g.etag) === + ifNoneMatch) { + isDebug$1 && debugCache(`[304] ${prettifyUrl(url, root)}`); + res.statusCode = 304; + return res.end(); + } + // resolve, load and transform using the plugin container + const result = await transformRequest(url, server, { + html: (_h = req.headers.accept) === null || _h === void 0 ? void 0 : _h.includes('text/html') + }); + if (result) { + const type = isDirectCSSRequest(url) ? 'css' : 'js'; + const isDep = DEP_VERSION_RE.test(url) || + (cacheDirPrefix && url.startsWith(cacheDirPrefix)); + return send$1(req, res, result.code, type, result.etag, + // allow browser to cache npm deps! + isDep ? 'max-age=31536000,immutable' : 'no-cache', result.map); + } + } + } + catch (e) { + return next(e); + } + next(); + }; +} + +function createDevHtmlTransformFn(server) { + const [preHooks, postHooks] = resolveHtmlTransforms(server.config.plugins); + return (url, html, originalUrl) => { + return applyHtmlTransforms(html, [...preHooks, devHtmlHook, ...postHooks], { + path: url, + filename: getHtmlFilename(url, server), + server, + originalUrl + }); + }; +} +function getHtmlFilename(url, server) { + if (url.startsWith(FS_PREFIX)) { + return fsPathFromId(url); + } + else { + return path__default.join(server.config.root, url.slice(1)); + } +} +const startsWithSingleSlashRE = /^\/(?!\/)/; +const processNodeUrl = (node, s, config, htmlPath, originalUrl) => { + var _a; + const url = ((_a = node.value) === null || _a === void 0 ? void 0 : _a.content) || ''; + if (startsWithSingleSlashRE.test(url)) { + // prefix with base + s.overwrite(node.value.loc.start.offset, node.value.loc.end.offset, `"${config.base + url.slice(1)}"`); + } + else if (url.startsWith('.') && + originalUrl && + originalUrl !== '/' && + htmlPath === '/index.html') { + // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets + // path will add `/a/` prefix, it will caused 404. + // rewrite before `./index.js` -> `localhost:3000/a/index.js`. + // rewrite after `../index.js` -> `localhost:3000/index.js`. + s.overwrite(node.value.loc.start.offset, node.value.loc.end.offset, `"${path__default.posix.join(path__default.posix.relative(originalUrl, '/'), url.slice(1))}"`); + } +}; +const devHtmlHook = async (html, { path: htmlPath, server, originalUrl }) => { + // TODO: solve this design issue + // Optional chain expressions can return undefined by design + // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain + const config = server === null || server === void 0 ? void 0 : server.config; + const base = config.base || '/'; + const s = new MagicString(html); + let scriptModuleIndex = -1; + await traverseHtml(html, htmlPath, (node) => { + if (node.type !== 1 /* ELEMENT */) { + return; + } + // script tags + if (node.tag === 'script') { + const { src, isModule } = getScriptInfo(node); + if (isModule) { + scriptModuleIndex++; + } + if (src) { + processNodeUrl(src, s, config, htmlPath, originalUrl); + } + else if (isModule) { + // inline js module. convert to src="proxy" + s.overwrite(node.loc.start.offset, node.loc.end.offset, ``); + } + } + // elements with [href/src] attrs + const assetAttrs = assetAttrsConfig[node.tag]; + if (assetAttrs) { + for (const p of node.props) { + if (p.type === 6 /* ATTRIBUTE */ && + p.value && + assetAttrs.includes(p.name)) { + processNodeUrl(p, s, config, htmlPath, originalUrl); + } + } + } + }); + html = s.toString(); + return { + html, + tags: [ + { + tag: 'script', + attrs: { + type: 'module', + src: path__default.posix.join(base, CLIENT_PUBLIC_PATH) + }, + injectTo: 'head-prepend' + } + ] + }; +}; +function indexHtmlMiddleware(server) { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return async function viteIndexHtmlMiddleware(req, res, next) { + const url = req.url && cleanUrl(req.url); + // spa-fallback always redirects to /index.html + if ((url === null || url === void 0 ? void 0 : url.endsWith('.html')) && req.headers['sec-fetch-dest'] !== 'script') { + const filename = getHtmlFilename(url, server); + if (fs__default.existsSync(filename)) { + try { + let html = fs__default.readFileSync(filename, 'utf-8'); + html = await server.transformIndexHtml(url, html, req.originalUrl); + return send$1(req, res, html, 'html'); + } + catch (e) { + return next(e); + } + } + } + next(); + }; +} + +var lib = {exports: {}}; + +(function (module, exports) { + +var url = require$$0__default$7; + +module.exports = function historyApiFallback(options) { + options = options || {}; + var logger = getLogger(options); + + return function(req, res, next) { + var headers = req.headers; + if (req.method !== 'GET') { + logger( + 'Not rewriting', + req.method, + req.url, + 'because the method is not GET.' + ); + return next(); + } else if (!headers || typeof headers.accept !== 'string') { + logger( + 'Not rewriting', + req.method, + req.url, + 'because the client did not send an HTTP accept header.' + ); + return next(); + } else if (headers.accept.indexOf('application/json') === 0) { + logger( + 'Not rewriting', + req.method, + req.url, + 'because the client prefers JSON.' + ); + return next(); + } else if (!acceptsHtml(headers.accept, options)) { + logger( + 'Not rewriting', + req.method, + req.url, + 'because the client does not accept HTML.' + ); + return next(); + } + + var parsedUrl = url.parse(req.url); + var rewriteTarget; + options.rewrites = options.rewrites || []; + for (var i = 0; i < options.rewrites.length; i++) { + var rewrite = options.rewrites[i]; + var match = parsedUrl.pathname.match(rewrite.from); + if (match !== null) { + rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req); + + if(rewriteTarget.charAt(0) !== '/') { + logger( + 'We recommend using an absolute path for the rewrite target.', + 'Received a non-absolute rewrite target', + rewriteTarget, + 'for URL', + req.url + ); + } + + logger('Rewriting', req.method, req.url, 'to', rewriteTarget); + req.url = rewriteTarget; + return next(); + } + } + + var pathname = parsedUrl.pathname; + if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') && + options.disableDotRule !== true) { + logger( + 'Not rewriting', + req.method, + req.url, + 'because the path includes a dot (.) character.' + ); + return next(); + } + + rewriteTarget = options.index || '/index.html'; + logger('Rewriting', req.method, req.url, 'to', rewriteTarget); + req.url = rewriteTarget; + next(); + }; +}; + +function evaluateRewriteRule(parsedUrl, match, rule, req) { + if (typeof rule === 'string') { + return rule; + } else if (typeof rule !== 'function') { + throw new Error('Rewrite rule can only be of type string or function.'); + } + + return rule({ + parsedUrl: parsedUrl, + match: match, + request: req + }); +} + +function acceptsHtml(header, options) { + options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*']; + for (var i = 0; i < options.htmlAcceptHeaders.length; i++) { + if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) { + return true; + } + } + return false; +} + +function getLogger(options) { + if (options && options.logger) { + return options.logger; + } else if (options && options.verbose) { + return console.log.bind(console); + } + return function(){}; +} +}(lib)); + +var history = lib.exports; + +const logTime = createDebugger('vite:time'); +function timeMiddleware(root) { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteTimeMiddleware(req, res, next) { + const start = Date.now(); + const end = res.end; + res.end = (...args) => { + logTime(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`); + // @ts-ignore + return end.call(res, ...args); + }; + next(); + }; +} + +class ModuleNode { + constructor(url) { + /** + * Resolved file system path + query + */ + this.id = null; + this.file = null; + this.importers = new Set(); + this.importedModules = new Set(); + this.acceptedHmrDeps = new Set(); + this.isSelfAccepting = false; + this.transformResult = null; + this.ssrTransformResult = null; + this.ssrModule = null; + this.lastHMRTimestamp = 0; + this.url = url; + this.type = isDirectCSSRequest(url) ? 'css' : 'js'; + } +} +function invalidateSSRModule(mod, seen) { + if (seen.has(mod)) { + return; + } + seen.add(mod); + mod.ssrModule = null; + mod.importers.forEach((importer) => invalidateSSRModule(importer, seen)); +} +class ModuleGraph { + constructor(container) { + this.urlToModuleMap = new Map(); + this.idToModuleMap = new Map(); + // a single file may corresponds to multiple modules with different queries + this.fileToModulesMap = new Map(); + this.safeModulesPath = new Set(); + this.container = container; + } + async getModuleByUrl(rawUrl) { + const [url] = await this.resolveUrl(rawUrl); + return this.urlToModuleMap.get(url); + } + getModuleById(id) { + return this.idToModuleMap.get(removeTimestampQuery(id)); + } + getModulesByFile(file) { + return this.fileToModulesMap.get(file); + } + onFileChange(file) { + const mods = this.getModulesByFile(file); + if (mods) { + const seen = new Set(); + mods.forEach((mod) => { + this.invalidateModule(mod, seen); + }); + } + } + invalidateModule(mod, seen = new Set()) { + mod.transformResult = null; + mod.ssrTransformResult = null; + invalidateSSRModule(mod, seen); + } + invalidateAll() { + const seen = new Set(); + this.idToModuleMap.forEach((mod) => { + this.invalidateModule(mod, seen); + }); + } + /** + * Update the module graph based on a module's updated imports information + * If there are dependencies that no longer have any importers, they are + * returned as a Set. + */ + async updateModuleInfo(mod, importedModules, acceptedModules, isSelfAccepting) { + mod.isSelfAccepting = isSelfAccepting; + const prevImports = mod.importedModules; + const nextImports = (mod.importedModules = new Set()); + let noLongerImported; + // update import graph + for (const imported of importedModules) { + const dep = typeof imported === 'string' + ? await this.ensureEntryFromUrl(imported) + : imported; + dep.importers.add(mod); + nextImports.add(dep); + } + // remove the importer from deps that were imported but no longer are. + prevImports.forEach((dep) => { + if (!nextImports.has(dep)) { + dep.importers.delete(mod); + if (!dep.importers.size) { + (noLongerImported || (noLongerImported = new Set())).add(dep); + } + } + }); + // update accepted hmr deps + const deps = (mod.acceptedHmrDeps = new Set()); + for (const accepted of acceptedModules) { + const dep = typeof accepted === 'string' + ? await this.ensureEntryFromUrl(accepted) + : accepted; + deps.add(dep); + } + return noLongerImported; + } + async ensureEntryFromUrl(rawUrl) { + const [url, resolvedId] = await this.resolveUrl(rawUrl); + let mod = this.urlToModuleMap.get(url); + if (!mod) { + mod = new ModuleNode(url); + this.urlToModuleMap.set(url, mod); + mod.id = resolvedId; + this.idToModuleMap.set(resolvedId, mod); + const file = (mod.file = cleanUrl(resolvedId)); + let fileMappedModules = this.fileToModulesMap.get(file); + if (!fileMappedModules) { + fileMappedModules = new Set(); + this.fileToModulesMap.set(file, fileMappedModules); + } + fileMappedModules.add(mod); + } + return mod; + } + // some deps, like a css file referenced via @import, don't have its own + // url because they are inlined into the main css import. But they still + // need to be represented in the module graph so that they can trigger + // hmr in the importing css file. + createFileOnlyEntry(file) { + file = normalizePath$4(file); + let fileMappedModules = this.fileToModulesMap.get(file); + if (!fileMappedModules) { + fileMappedModules = new Set(); + this.fileToModulesMap.set(file, fileMappedModules); + } + const url = `${FS_PREFIX}${file}`; + for (const m of fileMappedModules) { + if (m.url === url || m.id === file) { + return m; + } + } + const mod = new ModuleNode(url); + mod.file = file; + fileMappedModules.add(mod); + return mod; + } + // for incoming urls, it is important to: + // 1. remove the HMR timestamp query (?t=xxxx) + // 2. resolve its extension so that urls with or without extension all map to + // the same module + async resolveUrl(url) { + var _a; + url = removeImportQuery(removeTimestampQuery(url)); + const resolvedId = ((_a = (await this.container.resolveId(url))) === null || _a === void 0 ? void 0 : _a.id) || url; + const ext = path$w.extname(cleanUrl(resolvedId)); + const { pathname, search, hash } = require$$0$a.parse(url); + if (ext && !pathname.endsWith(ext)) { + url = pathname + ext + (search || '') + (hash || ''); + } + return [url, resolvedId]; + } +} + +const debugHmr = createDebugger('vite:hmr'); +const normalizedClientDir = normalizePath$4(CLIENT_DIR); +function getShortName(file, root) { + return file.startsWith(root + '/') ? path__default.posix.relative(root, file) : file; +} +async function handleHMRUpdate(file, server) { + const { ws, config, moduleGraph } = server; + const shortFile = getShortName(file, config.root); + const isConfig = file === config.configFile; + const isConfigDependency = config.configFileDependencies.some((name) => file === path__default.resolve(name)); + const isEnv = config.inlineConfig.envFile !== false && file.endsWith('.env'); + if (isConfig || isConfigDependency || isEnv) { + // auto restart server + debugHmr(`[config change] ${source.dim(shortFile)}`); + config.logger.info(source.green(`${path__default.relative(process.cwd(), file)} changed, restarting server...`), { clear: true, timestamp: true }); + await restartServer(server); + return; + } + debugHmr(`[file change] ${source.dim(shortFile)}`); + // (dev only) the client itself cannot be hot updated. + if (file.startsWith(normalizedClientDir)) { + ws.send({ + type: 'full-reload', + path: '*' + }); + return; + } + const mods = moduleGraph.getModulesByFile(file); + // check if any plugin wants to perform custom HMR handling + const timestamp = Date.now(); + const hmrContext = { + file, + timestamp, + modules: mods ? [...mods] : [], + read: () => readModifiedFile(file), + server + }; + for (const plugin of config.plugins) { + if (plugin.handleHotUpdate) { + const filteredModules = await plugin.handleHotUpdate(hmrContext); + if (filteredModules) { + hmrContext.modules = filteredModules; + } + } + } + if (!hmrContext.modules.length) { + // html file cannot be hot updated + if (file.endsWith('.html')) { + config.logger.info(source.green(`page reload `) + source.dim(shortFile), { + clear: true, + timestamp: true + }); + ws.send({ + type: 'full-reload', + path: config.server.middlewareMode + ? '*' + : '/' + normalizePath$4(path__default.relative(config.root, file)) + }); + } + else { + // loaded but not in the module graph, probably not js + debugHmr(`[no modules matched] ${source.dim(shortFile)}`); + } + return; + } + updateModules(shortFile, hmrContext.modules, timestamp, server); +} +function updateModules(file, modules, timestamp, { config, ws }) { + const updates = []; + const invalidatedModules = new Set(); + let needFullReload = false; + for (const mod of modules) { + invalidate(mod, timestamp, invalidatedModules); + if (needFullReload) { + continue; + } + const boundaries = new Set(); + const hasDeadEnd = propagateUpdate(mod, boundaries); + if (hasDeadEnd) { + needFullReload = true; + continue; + } + updates.push(...[...boundaries].map(({ boundary, acceptedVia }) => ({ + type: `${boundary.type}-update`, + timestamp, + path: boundary.url, + acceptedPath: acceptedVia.url + }))); + } + if (needFullReload) { + config.logger.info(source.green(`page reload `) + source.dim(file), { + clear: true, + timestamp: true + }); + ws.send({ + type: 'full-reload' + }); + } + else { + config.logger.info(updates + .map(({ path }) => source.green(`hmr update `) + source.dim(path)) + .join('\n'), { clear: true, timestamp: true }); + ws.send({ + type: 'update', + updates + }); + } +} +async function handleFileAddUnlink(file, server, isUnlink = false) { + var _a; + const modules = [...((_a = server.moduleGraph.getModulesByFile(file)) !== null && _a !== void 0 ? _a : [])]; + if (isUnlink && file in server._globImporters) { + delete server._globImporters[file]; + } + else { + for (const i in server._globImporters) { + const { module, importGlobs } = server._globImporters[i]; + for (const { base, pattern } of importGlobs) { + if (minimatch_1(file, pattern) || minimatch_1(path__default.relative(base, file), pattern)) { + modules.push(module); + // We use `onFileChange` to invalidate `module.file` so that subsequent `ssrLoadModule()` + // calls get fresh glob import results with(out) the newly added(/removed) `file`. + server.moduleGraph.onFileChange(module.file); + break; + } + } + } + } + if (modules.length > 0) { + updateModules(getShortName(file, server.config.root), modules, Date.now(), server); + } +} +function propagateUpdate(node, boundaries, currentChain = [node]) { + if (node.isSelfAccepting) { + boundaries.add({ + boundary: node, + acceptedVia: node + }); + // additionally check for CSS importers, since a PostCSS plugin like + // Tailwind JIT may register any file as a dependency to a CSS file. + for (const importer of node.importers) { + if (isCSSRequest(importer.url) && !currentChain.includes(importer)) { + propagateUpdate(importer, boundaries, currentChain.concat(importer)); + } + } + return false; + } + if (!node.importers.size) { + return true; + } + // #3716, #3913 + // For a non-CSS file, if all of its importers are CSS files (registered via + // PostCSS plugins) it should be considered a dead end and force full reload. + if (!isCSSRequest(node.url) && + [...node.importers].every((i) => isCSSRequest(i.url))) { + return true; + } + for (const importer of node.importers) { + const subChain = currentChain.concat(importer); + if (importer.acceptedHmrDeps.has(node)) { + boundaries.add({ + boundary: importer, + acceptedVia: node + }); + continue; + } + if (currentChain.includes(importer)) { + // circular deps is considered dead end + return true; + } + if (propagateUpdate(importer, boundaries, subChain)) { + return true; + } + } + return false; +} +function invalidate(mod, timestamp, seen) { + if (seen.has(mod)) { + return; + } + seen.add(mod); + mod.lastHMRTimestamp = timestamp; + mod.transformResult = null; + mod.ssrModule = null; + mod.ssrTransformResult = null; + mod.importers.forEach((importer) => { + if (!importer.acceptedHmrDeps.has(mod)) { + invalidate(importer, timestamp, seen); + } + }); +} +function handlePrunedModules(mods, { ws }) { + // update the disposed modules' hmr timestamp + // since if it's re-imported, it should re-apply side effects + // and without the timestamp the browser will not re-import it! + const t = Date.now(); + mods.forEach((mod) => { + mod.lastHMRTimestamp = t; + debugHmr(`[dispose] ${source.dim(mod.file)}`); + }); + ws.send({ + type: 'prune', + paths: [...mods].map((m) => m.url) + }); +} +/** + * Lex import.meta.hot.accept() for accepted deps. + * Since hot.accept() can only accept string literals or array of string + * literals, we don't really need a heavy @babel/parse call on the entire source. + * + * @returns selfAccepts + */ +function lexAcceptedHmrDeps(code, start, urls) { + let state = 0 /* inCall */; + // the state can only be 2 levels deep so no need for a stack + let prevState = 0 /* inCall */; + let currentDep = ''; + function addDep(index) { + urls.add({ + url: currentDep, + start: index - currentDep.length - 1, + end: index + 1 + }); + currentDep = ''; + } + for (let i = start; i < code.length; i++) { + const char = code.charAt(i); + switch (state) { + case 0 /* inCall */: + case 4 /* inArray */: + if (char === `'`) { + prevState = state; + state = 1 /* inSingleQuoteString */; + } + else if (char === `"`) { + prevState = state; + state = 2 /* inDoubleQuoteString */; + } + else if (char === '`') { + prevState = state; + state = 3 /* inTemplateString */; + } + else if (/\s/.test(char)) { + continue; + } + else { + if (state === 0 /* inCall */) { + if (char === `[`) { + state = 4 /* inArray */; + } + else { + // reaching here means the first arg is neither a string literal + // nor an Array literal (direct callback) or there is no arg + // in both case this indicates a self-accepting module + return true; // done + } + } + else if (state === 4 /* inArray */) { + if (char === `]`) { + return false; // done + } + else if (char === ',') { + continue; + } + else { + error$1(i); + } + } + } + break; + case 1 /* inSingleQuoteString */: + if (char === `'`) { + addDep(i); + if (prevState === 0 /* inCall */) { + // accept('foo', ...) + return false; + } + else { + state = prevState; + } + } + else { + currentDep += char; + } + break; + case 2 /* inDoubleQuoteString */: + if (char === `"`) { + addDep(i); + if (prevState === 0 /* inCall */) { + // accept('foo', ...) + return false; + } + else { + state = prevState; + } + } + else { + currentDep += char; + } + break; + case 3 /* inTemplateString */: + if (char === '`') { + addDep(i); + if (prevState === 0 /* inCall */) { + // accept('foo', ...) + return false; + } + else { + state = prevState; + } + } + else if (char === '$' && code.charAt(i + 1) === '{') { + error$1(i); + } + else { + currentDep += char; + } + break; + default: + throw new Error('unknown import.meta.hot lexer state'); + } + } + return false; +} +function error$1(pos) { + const err = new Error(`import.meta.accept() can only accept string literals or an ` + + `Array of string literals.`); + err.pos = pos; + throw err; +} +// vitejs/vite#610 when hot-reloading Vue files, we read immediately on file +// change event and sometimes this can be too early and get an empty buffer. +// Poll until the file's modified time has changed before reading again. +async function readModifiedFile(file) { + const content = fs__default.readFileSync(file, 'utf-8'); + if (!content) { + const mtime = fs__default.statSync(file).mtimeMs; + await new Promise((r) => { + let n = 0; + const poll = async () => { + n++; + const newMtime = fs__default.statSync(file).mtimeMs; + if (newMtime !== mtime || n > 10) { + r(0); + } + else { + setTimeout(poll, 10); + } + }; + setTimeout(poll, 10); + }); + return fs__default.readFileSync(file, 'utf-8'); + } + else { + return content; + } +} +async function restartServer(server) { + // @ts-ignore + global.__vite_start_time = Date.now(); + const { port } = server.config.server; + await server.close(); + let newServer = null; + try { + newServer = await createServer(server.config.inlineConfig); + } + catch (err) { + server.config.logger.error(err.message, { + timestamp: true, + }); + return; + } + for (const key in newServer) { + if (key !== 'app') { + // @ts-ignore + server[key] = newServer[key]; + } + } + if (!server.config.server.middlewareMode) { + await server.listen(port, true); + } + else { + server.config.logger.info('server restarted.', { timestamp: true }); + } +} + +var isWsl$2 = {exports: {}}; + +const fs$7 = fs__default; + +let isDocker$2; + +function hasDockerEnv() { + try { + fs$7.statSync('/.dockerenv'); + return true; + } catch (_) { + return false; + } +} + +function hasDockerCGroup() { + try { + return fs$7.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); + } catch (_) { + return false; + } +} + +var isDocker_1 = () => { + if (isDocker$2 === undefined) { + isDocker$2 = hasDockerEnv() || hasDockerCGroup(); + } + + return isDocker$2; +}; + +const os$4 = require$$0__default$1; +const fs$6 = fs__default; +const isDocker$1 = isDocker_1; + +const isWsl$1 = () => { + if (process.platform !== 'linux') { + return false; + } + + if (os$4.release().toLowerCase().includes('microsoft')) { + if (isDocker$1()) { + return false; + } + + return true; + } + + try { + return fs$6.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? + !isDocker$1() : false; + } catch (_) { + return false; + } +}; + +if (process.env.__IS_WSL_TEST__) { + isWsl$2.exports = isWsl$1; +} else { + isWsl$2.exports = isWsl$1(); +} + +var defineLazyProp = (object, propertyName, fn) => { + const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true}); + + Object.defineProperty(object, propertyName, { + configurable: true, + enumerable: true, + get() { + const result = fn(); + define(result); + return result; + }, + set(value) { + define(value); + } + }); + + return object; +}; + +const path$9 = path__default; +const childProcess$3 = require$$1__default$4; +const {promises: fs$5, constants: fsConstants} = fs__default; +const isWsl = isWsl$2.exports; +const isDocker = isDocker_1; +const defineLazyProperty = defineLazyProp; + +// Path to included `xdg-open`. +const localXdgOpenPath = path$9.join(__dirname, 'xdg-open'); + +const {platform, arch} = process; + +/** +Get the mount point for fixed drives in WSL. + +@inner +@returns {string} The mount point. +*/ +const getWslDrivesMountPoint = (() => { + // Default value for "root" param + // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config + const defaultMountPoint = '/mnt/'; + + let mountPoint; + + return async function () { + if (mountPoint) { + // Return memoized mount point value + return mountPoint; + } + + const configFilePath = '/etc/wsl.conf'; + + let isConfigFileExists = false; + try { + await fs$5.access(configFilePath, fsConstants.F_OK); + isConfigFileExists = true; + } catch {} + + if (!isConfigFileExists) { + return defaultMountPoint; + } + + const configContent = await fs$5.readFile(configFilePath, {encoding: 'utf8'}); + const configMountPoint = /(?.*)/g.exec(configContent); + + if (!configMountPoint) { + return defaultMountPoint; + } + + mountPoint = configMountPoint.groups.mountPoint.trim(); + mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`; + + return mountPoint; + }; +})(); + +const pTryEach = async (array, mapper) => { + let latestError; + + for (const item of array) { + try { + return await mapper(item); // eslint-disable-line no-await-in-loop + } catch (error) { + latestError = error; + } + } + + throw latestError; +}; + +const open = async (target, options) => { + if (typeof target !== 'string') { + throw new TypeError('Expected a `target`'); + } + + options = { + wait: false, + background: false, + newInstance: false, + allowNonzeroExitCode: false, + ...options + }; + + if (Array.isArray(options.app)) { + return pTryEach(options.app, singleApp => open(target, { + ...options, + app: singleApp + })); + } + + let {name: app, arguments: appArguments = []} = options.app || {}; + appArguments = [...appArguments]; + + if (Array.isArray(app)) { + return pTryEach(app, appName => open(target, { + ...options, + app: { + name: appName, + arguments: appArguments + } + })); + } + + let command; + const cliArguments = []; + const childProcessOptions = {}; + + if (platform === 'darwin') { + command = 'open'; + + if (options.wait) { + cliArguments.push('--wait-apps'); + } + + if (options.background) { + cliArguments.push('--background'); + } + + if (options.newInstance) { + cliArguments.push('--new'); + } + + if (app) { + cliArguments.push('-a', app); + } + } else if (platform === 'win32' || (isWsl && !isDocker())) { + const mountPoint = await getWslDrivesMountPoint(); + + command = isWsl ? + `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : + `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; + + cliArguments.push( + '-NoProfile', + '-NonInteractive', + '–ExecutionPolicy', + 'Bypass', + '-EncodedCommand' + ); + + if (!isWsl) { + childProcessOptions.windowsVerbatimArguments = true; + } + + const encodedArguments = ['Start']; + + if (options.wait) { + encodedArguments.push('-Wait'); + } + + if (app) { + // Double quote with double quotes to ensure the inner quotes are passed through. + // Inner quotes are delimited for PowerShell interpretation with backticks. + encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList'); + appArguments.unshift(target); + } else { + encodedArguments.push(`"${target}"`); + } + + if (appArguments.length > 0) { + appArguments = appArguments.map(arg => `"\`"${arg}\`""`); + encodedArguments.push(appArguments.join(',')); + } + + // Using Base64-encoded command, accepted by PowerShell, to allow special characters. + target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); + } else { + if (app) { + command = app; + } else { + // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. + const isBundled = !__dirname || __dirname === '/'; + + // Check if local `xdg-open` exists and is executable. + let exeLocalXdgOpen = false; + try { + await fs$5.access(localXdgOpenPath, fsConstants.X_OK); + exeLocalXdgOpen = true; + } catch {} + + const useSystemXdgOpen = process.versions.electron || + platform === 'android' || isBundled || !exeLocalXdgOpen; + command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath; + } + + if (appArguments.length > 0) { + cliArguments.push(...appArguments); + } + + if (!options.wait) { + // `xdg-open` will block the process unless stdio is ignored + // and it's detached from the parent even if it's unref'd. + childProcessOptions.stdio = 'ignore'; + childProcessOptions.detached = true; + } + } + + cliArguments.push(target); + + if (platform === 'darwin' && appArguments.length > 0) { + cliArguments.push('--args', ...appArguments); + } + + const subprocess = childProcess$3.spawn(command, cliArguments, childProcessOptions); + + if (options.wait) { + return new Promise((resolve, reject) => { + subprocess.once('error', reject); + + subprocess.once('close', exitCode => { + if (options.allowNonzeroExitCode && exitCode > 0) { + reject(new Error(`Exited with code ${exitCode}`)); + return; + } + + resolve(subprocess); + }); + }); + } + + subprocess.unref(); + + return subprocess; +}; + +function detectArchBinary(binary) { + if (typeof binary === 'string' || Array.isArray(binary)) { + return binary; + } + + const {[arch]: archBinary} = binary; + + if (!archBinary) { + throw new Error(`${arch} is not supported`); + } + + return archBinary; +} + +function detectPlatformBinary({[platform]: platformBinary}, {wsl}) { + if (wsl && isWsl) { + return detectArchBinary(wsl); + } + + if (!platformBinary) { + throw new Error(`${platform} is not supported`); + } + + return detectArchBinary(platformBinary); +} + +const apps = {}; + +defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({ + darwin: 'google chrome', + win32: 'chrome', + linux: ['google-chrome', 'google-chrome-stable'] +}, { + wsl: { + ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe', + x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'] + } +})); + +defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({ + darwin: 'firefox', + win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', + linux: 'firefox' +}, { + wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe' +})); + +defineLazyProperty(apps, 'edge', () => detectPlatformBinary({ + darwin: 'microsoft edge', + win32: 'msedge', + linux: 'microsoft-edge' +}, { + wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' +})); + +open.apps = apps; + +var open_1 = open; + +var execa$2 = {exports: {}}; + +var crossSpawn$1 = {exports: {}}; + +var windows$1 = isexe$3; +isexe$3.sync = sync$2; + +var fs$4 = fs__default; + +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$1 (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe$3 (path, options, cb) { + fs$4.stat(path, function (er, stat) { + cb(er, er ? false : checkStat$1(stat, path, options)); + }); +} + +function sync$2 (path, options) { + return checkStat$1(fs$4.statSync(path), path, options) +} + +var mode = isexe$2; +isexe$2.sync = sync$1; + +var fs$3 = fs__default; + +function isexe$2 (path, options, cb) { + fs$3.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)); + }); +} + +function sync$1 (path, options) { + return checkStat(fs$3.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 +} + +var core$1; +if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { + core$1 = windows$1; +} else { + core$1 = mode; +} + +var isexe_1 = isexe$1; +isexe$1.sync = sync; + +function isexe$1 (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$1(path, options || {}, function (er, is) { + if (er) { + reject(er); + } else { + resolve(is); + } + }); + }) + } + + core$1(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$1.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} + +const isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys'; + +const path$8 = path__default; +const COLON = isWindows ? ';' : ':'; +const isexe = isexe_1; + +const getNotFoundError = (cmd) => + Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); + +const getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON; + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] + : ( + [ + // windows always checks the cwd first + ...(isWindows ? [process.cwd()] : []), + ...(opt.path || process.env.PATH || + /* istanbul ignore next: very unusual */ '').split(colon), + ] + ); + const pathExtExe = isWindows + ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' + : ''; + const pathExt = isWindows ? pathExtExe.split(colon) : ['']; + + if (isWindows) { + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift(''); + } + + return { + pathEnv, + pathExt, + pathExtExe, + } +}; + +const which$1 = (cmd, opt, cb) => { + if (typeof opt === 'function') { + cb = opt; + opt = {}; + } + if (!opt) + opt = {}; + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + + const step = i => new Promise((resolve, reject) => { + if (i === pathEnv.length) + return opt.all && found.length ? resolve(found) + : reject(getNotFoundError(cmd)) + + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + + const pCmd = path$8.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd; + + resolve(subStep(p, i, 0)); + }); + + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i + 1)) + const ext = pathExt[ii]; + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext); + else + return resolve(p + ext) + } + return resolve(subStep(p, i, ii + 1)) + }); + }); + + return cb ? step(0).then(res => cb(null, res), cb) : step(0) +}; + +const whichSync = (cmd, opt) => { + opt = opt || {}; + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + + for (let i = 0; i < pathEnv.length; i ++) { + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + + const pCmd = path$8.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd; + + for (let j = 0; j < pathExt.length; j ++) { + const cur = p + pathExt[j]; + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }); + if (is) { + if (opt.all) + found.push(cur); + else + return cur + } + } catch (ex) {} + } + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) +}; + +var which_1 = which$1; +which$1.sync = whichSync; + +var pathKey$3 = {exports: {}}; + +const pathKey$2 = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +pathKey$3.exports = pathKey$2; +// TODO: Remove this for the next major release +pathKey$3.exports.default = pathKey$2; + +const path$7 = path__default; +const which = which_1; +const getPathKey = pathKey$3.exports; + +function resolveCommandAttempt(parsed, withoutPathExt) { + const env = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + // Worker threads do not have process.chdir() + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: env[getPathKey({ env })], + pathExt: withoutPathExt ? path$7.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + if (shouldSwitchCwd) { + process.chdir(cwd); + } + } + + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path$7.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } + + return resolved; +} + +function resolveCommand$1(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} + +var resolveCommand_1 = resolveCommand$1; + +var _escape = {}; + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; +} + +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; + + // Algorithm below is based on https://qntm.org/cmd + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); + + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } + + return arg; +} + +_escape.command = escapeCommand; +_escape.argument = escapeArgument; + +var shebangRegex$1 = /^#!(.*)/; + +const shebangRegex = shebangRegex$1; + +var shebangCommand$1 = (string = '') => { + const match = string.match(shebangRegex); + + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; +}; + +const fs$2 = fs__default; +const shebangCommand = shebangCommand$1; + +function readShebang$1(command) { + // Read the first 150 bytes from the file + const size = 150; + const buffer = Buffer.alloc(size); + + let fd; + + try { + fd = fs$2.openSync(command, 'r'); + fs$2.readSync(fd, buffer, 0, size, 0); + fs$2.closeSync(fd); + } catch (e) { /* Empty */ } + + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} + +var readShebang_1 = readShebang$1; + +const path$6 = path__default; +const resolveCommand = resolveCommand_1; +const escape = _escape; +const readShebang = readShebang_1; + +const isWin$2 = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; +} + +function parseNonShell(parsed) { + if (!isWin$2) { + return parsed; + } + + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); + + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); + + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path$6.normalize(parsed.command); + + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } + + return parsed; +} + +function parse$3(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; + + // Delegate further parsing to shell or non-shell + return options.shell ? parsed : parseNonShell(parsed); +} + +var parse_1 = parse$3; + +const isWin$1 = process.platform === 'win32'; + +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); +} + +function hookChildProcess(cp, parsed) { + if (!isWin$1) { + return; + } + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed); + + if (err) { + return originalEmit.call(cp, 'error', err); + } + } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; +} + +function verifyENOENT(status, parsed) { + if (isWin$1 && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; +} + +function verifyENOENTSync(status, parsed) { + if (isWin$1 && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } + + return null; +} + +var enoent$1 = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; + +const cp = require$$1__default$4; +const parse$2 = parse_1; +const enoent = enoent$1; + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse$2(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; +} + +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse$2(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; +} + +crossSpawn$1.exports = spawn; +crossSpawn$1.exports.spawn = spawn; +crossSpawn$1.exports.sync = spawnSync; + +crossSpawn$1.exports._parse = parse$2; +crossSpawn$1.exports._enoent = enoent; + +var stripFinalNewline$1 = input => { + const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); + const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); + + if (input[input.length - 1] === LF) { + input = input.slice(0, input.length - 1); + } + + if (input[input.length - 1] === CR) { + input = input.slice(0, input.length - 1); + } + + return input; +}; + +var npmRunPath$1 = {exports: {}}; + +var pathKey$1 = {exports: {}}; + +const pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +pathKey$1.exports = pathKey; +// TODO: Remove this for the next major release +pathKey$1.exports.default = pathKey; + +(function (module) { +const path = path__default; +const pathKey = pathKey$1.exports; + +const npmRunPath = options => { + options = { + cwd: process.cwd(), + path: process.env[pathKey()], + execPath: process.execPath, + ...options + }; + + let previous; + let cwdPath = path.resolve(options.cwd); + const result = []; + + while (previous !== cwdPath) { + result.push(path.join(cwdPath, 'node_modules/.bin')); + previous = cwdPath; + cwdPath = path.resolve(cwdPath, '..'); + } + + // Ensure the running `node` binary is used + const execPathDir = path.resolve(options.cwd, options.execPath, '..'); + result.push(execPathDir); + + return result.concat(options.path).join(path.delimiter); +}; + +module.exports = npmRunPath; +// TODO: Remove this for the next major release +module.exports.default = npmRunPath; + +module.exports.env = options => { + options = { + env: process.env, + ...options + }; + + const env = {...options.env}; + const path = pathKey({env}); + + options.path = env[path]; + env[path] = module.exports(options); + + return env; +}; +}(npmRunPath$1)); + +var onetime$2 = {exports: {}}; + +var mimicFn$2 = {exports: {}}; + +const mimicFn$1 = (to, from) => { + for (const prop of Reflect.ownKeys(from)) { + Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); + } + + return to; +}; + +mimicFn$2.exports = mimicFn$1; +// TODO: Remove this for the next major release +mimicFn$2.exports.default = mimicFn$1; + +const mimicFn = mimicFn$2.exports; + +const calledFunctions = new WeakMap(); + +const onetime$1 = (function_, options = {}) => { + if (typeof function_ !== 'function') { + throw new TypeError('Expected a function'); + } + + let returnValue; + let callCount = 0; + const functionName = function_.displayName || function_.name || ''; + + const onetime = function (...arguments_) { + calledFunctions.set(onetime, ++callCount); + + if (callCount === 1) { + returnValue = function_.apply(this, arguments_); + function_ = null; + } else if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } + + return returnValue; + }; + + mimicFn(onetime, function_); + calledFunctions.set(onetime, callCount); + + return onetime; +}; + +onetime$2.exports = onetime$1; +// TODO: Remove this for the next major release +onetime$2.exports.default = onetime$1; + +onetime$2.exports.callCount = function_ => { + if (!calledFunctions.has(function_)) { + throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); + } + + return calledFunctions.get(function_); +}; + +var main$2 = {}; + +var signals$2 = {}; + +var core = {}; + +Object.defineProperty(core,"__esModule",{value:true});core.SIGNALS=void 0; + +const SIGNALS=[ +{ +name:"SIGHUP", +number:1, +action:"terminate", +description:"Terminal closed", +standard:"posix"}, + +{ +name:"SIGINT", +number:2, +action:"terminate", +description:"User interruption with CTRL-C", +standard:"ansi"}, + +{ +name:"SIGQUIT", +number:3, +action:"core", +description:"User interruption with CTRL-\\", +standard:"posix"}, + +{ +name:"SIGILL", +number:4, +action:"core", +description:"Invalid machine instruction", +standard:"ansi"}, + +{ +name:"SIGTRAP", +number:5, +action:"core", +description:"Debugger breakpoint", +standard:"posix"}, + +{ +name:"SIGABRT", +number:6, +action:"core", +description:"Aborted", +standard:"ansi"}, + +{ +name:"SIGIOT", +number:6, +action:"core", +description:"Aborted", +standard:"bsd"}, + +{ +name:"SIGBUS", +number:7, +action:"core", +description: +"Bus error due to misaligned, non-existing address or paging error", +standard:"bsd"}, + +{ +name:"SIGEMT", +number:7, +action:"terminate", +description:"Command should be emulated but is not implemented", +standard:"other"}, + +{ +name:"SIGFPE", +number:8, +action:"core", +description:"Floating point arithmetic error", +standard:"ansi"}, + +{ +name:"SIGKILL", +number:9, +action:"terminate", +description:"Forced termination", +standard:"posix", +forced:true}, + +{ +name:"SIGUSR1", +number:10, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, + +{ +name:"SIGSEGV", +number:11, +action:"core", +description:"Segmentation fault", +standard:"ansi"}, + +{ +name:"SIGUSR2", +number:12, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, + +{ +name:"SIGPIPE", +number:13, +action:"terminate", +description:"Broken pipe or socket", +standard:"posix"}, + +{ +name:"SIGALRM", +number:14, +action:"terminate", +description:"Timeout or timer", +standard:"posix"}, + +{ +name:"SIGTERM", +number:15, +action:"terminate", +description:"Termination", +standard:"ansi"}, + +{ +name:"SIGSTKFLT", +number:16, +action:"terminate", +description:"Stack is empty or overflowed", +standard:"other"}, + +{ +name:"SIGCHLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"posix"}, + +{ +name:"SIGCLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"other"}, + +{ +name:"SIGCONT", +number:18, +action:"unpause", +description:"Unpaused", +standard:"posix", +forced:true}, + +{ +name:"SIGSTOP", +number:19, +action:"pause", +description:"Paused", +standard:"posix", +forced:true}, + +{ +name:"SIGTSTP", +number:20, +action:"pause", +description:"Paused using CTRL-Z or \"suspend\"", +standard:"posix"}, + +{ +name:"SIGTTIN", +number:21, +action:"pause", +description:"Background process cannot read terminal input", +standard:"posix"}, + +{ +name:"SIGBREAK", +number:21, +action:"terminate", +description:"User interruption with CTRL-BREAK", +standard:"other"}, + +{ +name:"SIGTTOU", +number:22, +action:"pause", +description:"Background process cannot write to terminal output", +standard:"posix"}, + +{ +name:"SIGURG", +number:23, +action:"ignore", +description:"Socket received out-of-band data", +standard:"bsd"}, + +{ +name:"SIGXCPU", +number:24, +action:"core", +description:"Process timed out", +standard:"bsd"}, + +{ +name:"SIGXFSZ", +number:25, +action:"core", +description:"File too big", +standard:"bsd"}, + +{ +name:"SIGVTALRM", +number:26, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, + +{ +name:"SIGPROF", +number:27, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, + +{ +name:"SIGWINCH", +number:28, +action:"ignore", +description:"Terminal window size changed", +standard:"bsd"}, + +{ +name:"SIGIO", +number:29, +action:"terminate", +description:"I/O is available", +standard:"other"}, + +{ +name:"SIGPOLL", +number:29, +action:"terminate", +description:"Watched event", +standard:"other"}, + +{ +name:"SIGINFO", +number:29, +action:"ignore", +description:"Request for process information", +standard:"other"}, + +{ +name:"SIGPWR", +number:30, +action:"terminate", +description:"Device running out of power", +standard:"systemv"}, + +{ +name:"SIGSYS", +number:31, +action:"core", +description:"Invalid system call", +standard:"other"}, + +{ +name:"SIGUNUSED", +number:31, +action:"terminate", +description:"Invalid system call", +standard:"other"}];core.SIGNALS=SIGNALS; + +var realtime = {}; + +Object.defineProperty(realtime,"__esModule",{value:true});realtime.SIGRTMAX=realtime.getRealtimeSignals=void 0; +const getRealtimeSignals=function(){ +const length=SIGRTMAX-SIGRTMIN+1; +return Array.from({length},getRealtimeSignal); +};realtime.getRealtimeSignals=getRealtimeSignals; + +const getRealtimeSignal=function(value,index){ +return { +name:`SIGRT${index+1}`, +number:SIGRTMIN+index, +action:"terminate", +description:"Application-specific signal (realtime)", +standard:"posix"}; + +}; + +const SIGRTMIN=34; +const SIGRTMAX=64;realtime.SIGRTMAX=SIGRTMAX; + +Object.defineProperty(signals$2,"__esModule",{value:true});signals$2.getSignals=void 0;var _os$1=require$$0__default$1; + +var _core=core; +var _realtime$1=realtime; + + + +const getSignals=function(){ +const realtimeSignals=(0, _realtime$1.getRealtimeSignals)(); +const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); +return signals; +};signals$2.getSignals=getSignals; + + + + + + + +const normalizeSignal=function({ +name, +number:defaultNumber, +description, +action, +forced=false, +standard}) +{ +const{ +signals:{[name]:constantSignal}}= +_os$1.constants; +const supported=constantSignal!==undefined; +const number=supported?constantSignal:defaultNumber; +return {name,number,description,supported,action,forced,standard}; +}; + +Object.defineProperty(main$2,"__esModule",{value:true});main$2.signalsByNumber=main$2.signalsByName=void 0;var _os=require$$0__default$1; + +var _signals=signals$2; +var _realtime=realtime; + + + +const getSignalsByName=function(){ +const signals=(0, _signals.getSignals)(); +return signals.reduce(getSignalByName,{}); +}; + +const getSignalByName=function( +signalByNameMemo, +{name,number,description,supported,action,forced,standard}) +{ +return { +...signalByNameMemo, +[name]:{name,number,description,supported,action,forced,standard}}; + +}; + +const signalsByName$1=getSignalsByName();main$2.signalsByName=signalsByName$1; + + + + +const getSignalsByNumber=function(){ +const signals=(0, _signals.getSignals)(); +const length=_realtime.SIGRTMAX+1; +const signalsA=Array.from({length},(value,number)=> +getSignalByNumber(number,signals)); + +return Object.assign({},...signalsA); +}; + +const getSignalByNumber=function(number,signals){ +const signal=findSignalByNumber(number,signals); + +if(signal===undefined){ +return {}; +} + +const{name,description,supported,action,forced,standard}=signal; +return { +[number]:{ +name, +number, +description, +supported, +action, +forced, +standard}}; + + +}; + + + +const findSignalByNumber=function(number,signals){ +const signal=signals.find(({name})=>_os.constants.signals[name]===number); + +if(signal!==undefined){ +return signal; +} + +return signals.find(signalA=>signalA.number===number); +}; + +const signalsByNumber=getSignalsByNumber();main$2.signalsByNumber=signalsByNumber; + +const {signalsByName} = main$2; + +const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { + if (timedOut) { + return `timed out after ${timeout} milliseconds`; + } + + if (isCanceled) { + return 'was canceled'; + } + + if (errorCode !== undefined) { + return `failed with ${errorCode}`; + } + + if (signal !== undefined) { + return `was killed with ${signal} (${signalDescription})`; + } + + if (exitCode !== undefined) { + return `failed with exit code ${exitCode}`; + } + + return 'failed'; +}; + +const makeError$1 = ({ + stdout, + stderr, + all, + error, + signal, + exitCode, + command, + escapedCommand, + timedOut, + isCanceled, + killed, + parsed: {options: {timeout}} +}) => { + // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. + // We normalize them to `undefined` + exitCode = exitCode === null ? undefined : exitCode; + signal = signal === null ? undefined : signal; + const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; + + const errorCode = error && error.code; + + const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); + const execaMessage = `Command ${prefix}: ${command}`; + const isError = Object.prototype.toString.call(error) === '[object Error]'; + const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; + const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); + + if (isError) { + error.originalMessage = error.message; + error.message = message; + } else { + error = new Error(message); + } + + error.shortMessage = shortMessage; + error.command = command; + error.escapedCommand = escapedCommand; + error.exitCode = exitCode; + error.signal = signal; + error.signalDescription = signalDescription; + error.stdout = stdout; + error.stderr = stderr; + + if (all !== undefined) { + error.all = all; + } + + if ('bufferedData' in error) { + delete error.bufferedData; + } + + error.failed = true; + error.timedOut = Boolean(timedOut); + error.isCanceled = isCanceled; + error.killed = killed && !timedOut; + + return error; +}; + +var error = makeError$1; + +var stdio = {exports: {}}; + +const aliases = ['stdin', 'stdout', 'stderr']; + +const hasAlias = options => aliases.some(alias => options[alias] !== undefined); + +const normalizeStdio$1 = options => { + if (!options) { + return; + } + + const {stdio} = options; + + if (stdio === undefined) { + return aliases.map(alias => options[alias]); + } + + if (hasAlias(options)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); + } + + if (typeof stdio === 'string') { + return stdio; + } + + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } + + const length = Math.max(stdio.length, aliases.length); + return Array.from({length}, (value, index) => stdio[index]); +}; + +stdio.exports = normalizeStdio$1; + +// `ipc` is pushed unless it is already present +stdio.exports.node = options => { + const stdio = normalizeStdio$1(options); + + if (stdio === 'ipc') { + return 'ipc'; + } + + if (stdio === undefined || typeof stdio === 'string') { + return [stdio, stdio, stdio, 'ipc']; + } + + if (stdio.includes('ipc')) { + return stdio; + } + + return [...stdio, 'ipc']; +}; + +var signalExit = {exports: {}}; + +var signals$1 = {exports: {}}; + +(function (module) { +// This is not the set of all possible signals. +// +// It IS, however, the set of all signals that trigger +// an exit on either Linux or BSD systems. Linux is a +// superset of the signal names supported on BSD, and +// the unknown signals just fail to register, so we can +// catch that easily enough. +// +// Don't bother with SIGKILL. It's uncatchable, which +// means that we can't fire any callbacks anyway. +// +// If a user does happen to register a handler on a non- +// fatal signal like SIGWINCH or something, and then +// exit, it'll end up firing `process.emit('exit')`, so +// the handler will be fired anyway. +// +// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised +// artificially, inherently leave the process in a +// state from which it is not safe to try and enter JS +// listeners. +module.exports = [ + 'SIGABRT', + 'SIGALRM', + 'SIGHUP', + 'SIGINT', + 'SIGTERM' +]; + +if (process.platform !== 'win32') { + module.exports.push( + 'SIGVTALRM', + 'SIGXCPU', + 'SIGXFSZ', + 'SIGUSR2', + 'SIGTRAP', + 'SIGSYS', + 'SIGQUIT', + 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ); +} + +if (process.platform === 'linux') { + module.exports.push( + 'SIGIO', + 'SIGPOLL', + 'SIGPWR', + 'SIGSTKFLT', + 'SIGUNUSED' + ); +} +}(signals$1)); + +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +var assert = require$$6__default; +var signals = signals$1.exports; +var isWin = /^win/i.test(process.platform); + +var EE = require$$0__default$6; +/* istanbul ignore if */ +if (typeof EE !== 'function') { + EE = EE.EventEmitter; +} + +var emitter; +if (process.__signal_exit_emitter__) { + emitter = process.__signal_exit_emitter__; +} else { + emitter = process.__signal_exit_emitter__ = new EE(); + emitter.count = 0; + emitter.emitted = {}; +} + +// Because this emitter is a global, we have to check to see if a +// previous version of this library failed to enable infinite listeners. +// I know what you're about to say. But literally everything about +// signal-exit is a compromise with evil. Get used to it. +if (!emitter.infinite) { + emitter.setMaxListeners(Infinity); + emitter.infinite = true; +} + +signalExit.exports = function (cb, opts) { + assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler'); + + if (loaded === false) { + load(); + } + + var ev = 'exit'; + if (opts && opts.alwaysLast) { + ev = 'afterexit'; + } + + var remove = function () { + emitter.removeListener(ev, cb); + if (emitter.listeners('exit').length === 0 && + emitter.listeners('afterexit').length === 0) { + unload(); + } + }; + emitter.on(ev, cb); + + return remove +}; + +signalExit.exports.unload = unload; +function unload () { + if (!loaded) { + return + } + loaded = false; + + signals.forEach(function (sig) { + try { + process.removeListener(sig, sigListeners[sig]); + } catch (er) {} + }); + process.emit = originalProcessEmit; + process.reallyExit = originalProcessReallyExit; + emitter.count -= 1; +} + +function emit (event, code, signal) { + if (emitter.emitted[event]) { + return + } + emitter.emitted[event] = true; + emitter.emit(event, code, signal); +} + +// { : , ... } +var sigListeners = {}; +signals.forEach(function (sig) { + sigListeners[sig] = function listener () { + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + var listeners = process.listeners(sig); + if (listeners.length === emitter.count) { + unload(); + emit('exit', null, sig); + /* istanbul ignore next */ + emit('afterexit', null, sig); + /* istanbul ignore next */ + if (isWin && sig === 'SIGHUP') { + // "SIGHUP" throws an `ENOSYS` error on Windows, + // so use a supported signal instead + sig = 'SIGINT'; + } + process.kill(process.pid, sig); + } + }; +}); + +signalExit.exports.signals = function () { + return signals +}; + +signalExit.exports.load = load; + +var loaded = false; + +function load () { + if (loaded) { + return + } + loaded = true; + + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + emitter.count += 1; + + signals = signals.filter(function (sig) { + try { + process.on(sig, sigListeners[sig]); + return true + } catch (er) { + return false + } + }); + + process.emit = processEmit; + process.reallyExit = processReallyExit; +} + +var originalProcessReallyExit = process.reallyExit; +function processReallyExit (code) { + process.exitCode = code || 0; + emit('exit', process.exitCode, null); + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null); + /* istanbul ignore next */ + originalProcessReallyExit.call(process, process.exitCode); +} + +var originalProcessEmit = process.emit; +function processEmit (ev, arg) { + if (ev === 'exit') { + if (arg !== undefined) { + process.exitCode = arg; + } + var ret = originalProcessEmit.apply(this, arguments); + emit('exit', process.exitCode, null); + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null); + return ret + } else { + return originalProcessEmit.apply(this, arguments) + } +} + +const os$3 = require$$0__default$1; +const onExit = signalExit.exports; + +const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; + +// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior +const spawnedKill$1 = (kill, signal = 'SIGTERM', options = {}) => { + const killResult = kill(signal); + setKillTimeout(kill, signal, options, killResult); + return killResult; +}; + +const setKillTimeout = (kill, signal, options, killResult) => { + if (!shouldForceKill(signal, options, killResult)) { + return; + } + + const timeout = getForceKillAfterTimeout(options); + const t = setTimeout(() => { + kill('SIGKILL'); + }, timeout); + + // Guarded because there's no `.unref()` when `execa` is used in the renderer + // process in Electron. This cannot be tested since we don't run tests in + // Electron. + // istanbul ignore else + if (t.unref) { + t.unref(); + } +}; + +const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => { + return isSigterm(signal) && forceKillAfterTimeout !== false && killResult; +}; + +const isSigterm = signal => { + return signal === os$3.constants.signals.SIGTERM || + (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); +}; + +const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { + if (forceKillAfterTimeout === true) { + return DEFAULT_FORCE_KILL_TIMEOUT; + } + + if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { + throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); + } + + return forceKillAfterTimeout; +}; + +// `childProcess.cancel()` +const spawnedCancel$1 = (spawned, context) => { + const killResult = spawned.kill(); + + if (killResult) { + context.isCanceled = true; + } +}; + +const timeoutKill = (spawned, signal, reject) => { + spawned.kill(signal); + reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); +}; + +// `timeout` option handling +const setupTimeout$1 = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { + if (timeout === 0 || timeout === undefined) { + return spawnedPromise; + } + + let timeoutId; + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + timeoutKill(spawned, killSignal, reject); + }, timeout); + }); + + const safeSpawnedPromise = spawnedPromise.finally(() => { + clearTimeout(timeoutId); + }); + + return Promise.race([timeoutPromise, safeSpawnedPromise]); +}; + +const validateTimeout$1 = ({timeout}) => { + if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { + throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); + } +}; + +// `cleanup` option handling +const setExitHandler$1 = async (spawned, {cleanup, detached}, timedPromise) => { + if (!cleanup || detached) { + return timedPromise; + } + + const removeExitHandler = onExit(() => { + spawned.kill(); + }); + + return timedPromise.finally(() => { + removeExitHandler(); + }); +}; + +var kill = { + spawnedKill: spawnedKill$1, + spawnedCancel: spawnedCancel$1, + setupTimeout: setupTimeout$1, + validateTimeout: validateTimeout$1, + setExitHandler: setExitHandler$1 +}; + +const isStream$1 = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; + +isStream$1.writable = stream => + isStream$1(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; + +isStream$1.readable = stream => + isStream$1(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; + +isStream$1.duplex = stream => + isStream$1.writable(stream) && + isStream$1.readable(stream); + +isStream$1.transform = stream => + isStream$1.duplex(stream) && + typeof stream._transform === 'function'; + +var isStream_1 = isStream$1; + +var getStream$2 = {exports: {}}; + +const {PassThrough: PassThroughStream} = require$$0__default$2; + +var bufferStream$1 = options => { + options = {...options}; + + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; + + if (array) { + objectMode = !(encoding || isBuffer); + } else { + encoding = encoding || 'utf8'; + } + + if (isBuffer) { + encoding = null; + } + + const stream = new PassThroughStream({objectMode}); + + if (encoding) { + stream.setEncoding(encoding); + } + + let length = 0; + const chunks = []; + + stream.on('data', chunk => { + chunks.push(chunk); + + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); + + stream.getBufferedValue = () => { + if (array) { + return chunks; + } + + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; + + stream.getBufferedLength = () => length; + + return stream; +}; + +const {constants: BufferConstants} = require$$0__default$8; +const stream$1 = require$$0__default$2; +const {promisify} = require$$0__default$3; +const bufferStream = bufferStream$1; + +const streamPipelinePromisified = promisify(stream$1.pipeline); + +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} + +async function getStream$1(inputStream, options) { + if (!inputStream) { + throw new Error('Expected a stream'); + } + + options = { + maxBuffer: Infinity, + ...options + }; + + const {maxBuffer} = options; + const stream = bufferStream(options); + + await new Promise((resolve, reject) => { + const rejectPromise = error => { + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { + error.bufferedData = stream.getBufferedValue(); + } + + reject(error); + }; + + (async () => { + try { + await streamPipelinePromisified(inputStream, stream); + resolve(); + } catch (error) { + rejectPromise(error); + } + })(); + + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); + + return stream.getBufferedValue(); +} + +getStream$2.exports = getStream$1; +getStream$2.exports.buffer = (stream, options) => getStream$1(stream, {...options, encoding: 'buffer'}); +getStream$2.exports.array = (stream, options) => getStream$1(stream, {...options, array: true}); +getStream$2.exports.MaxBufferError = MaxBufferError; + +const { PassThrough } = require$$0__default$2; + +var mergeStream$1 = function (/*streams...*/) { + var sources = []; + var output = new PassThrough({objectMode: true}); + + output.setMaxListeners(0); + + output.add = add; + output.isEmpty = isEmpty; + + output.on('unpipe', remove); + + Array.prototype.slice.call(arguments).forEach(add); + + return output + + function add (source) { + if (Array.isArray(source)) { + source.forEach(add); + return this + } + + sources.push(source); + source.once('end', remove.bind(null, source)); + source.once('error', output.emit.bind(output, 'error')); + source.pipe(output, {end: false}); + return this + } + + function isEmpty () { + return sources.length == 0; + } + + function remove (source) { + sources = sources.filter(function (it) { return it !== source }); + if (!sources.length && output.readable) { output.end(); } + } +}; + +const isStream = isStream_1; +const getStream = getStream$2.exports; +const mergeStream = mergeStream$1; + +// `input` option +const handleInput$1 = (spawned, input) => { + // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 + // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 + if (input === undefined || spawned.stdin === undefined) { + return; + } + + if (isStream(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } +}; + +// `all` interleaves `stdout` and `stderr` +const makeAllStream$1 = (spawned, {all}) => { + if (!all || (!spawned.stdout && !spawned.stderr)) { + return; + } + + const mixed = mergeStream(); + + if (spawned.stdout) { + mixed.add(spawned.stdout); + } + + if (spawned.stderr) { + mixed.add(spawned.stderr); + } + + return mixed; +}; + +// On failure, `result.stdout|stderr|all` should contain the currently buffered stream +const getBufferedData = async (stream, streamPromise) => { + if (!stream) { + return; + } + + stream.destroy(); + + try { + return await streamPromise; + } catch (error) { + return error.bufferedData; + } +}; + +const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { + if (!stream || !buffer) { + return; + } + + if (encoding) { + return getStream(stream, {encoding, maxBuffer}); + } + + return getStream.buffer(stream, {maxBuffer}); +}; + +// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) +const getSpawnedResult$1 = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { + const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); + const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); + const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); + + try { + return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); + } catch (error) { + return Promise.all([ + {error, signal: error.signal, timedOut: error.timedOut}, + getBufferedData(stdout, stdoutPromise), + getBufferedData(stderr, stderrPromise), + getBufferedData(all, allPromise) + ]); + } +}; + +const validateInputSync$1 = ({input}) => { + if (isStream(input)) { + throw new TypeError('The `input` option cannot be a stream in sync mode'); + } +}; + +var stream = { + handleInput: handleInput$1, + makeAllStream: makeAllStream$1, + getSpawnedResult: getSpawnedResult$1, + validateInputSync: validateInputSync$1 +}; + +const nativePromisePrototype = (async () => {})().constructor.prototype; +const descriptors = ['then', 'catch', 'finally'].map(property => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property) +]); + +// The return value is a mixin of `childProcess` and `Promise` +const mergePromise$1 = (spawned, promise) => { + for (const [property, descriptor] of descriptors) { + // Starting the main `promise` is deferred to avoid consuming streams + const value = typeof promise === 'function' ? + (...args) => Reflect.apply(descriptor.value, promise(), args) : + descriptor.value.bind(promise); + + Reflect.defineProperty(spawned, property, {...descriptor, value}); + } + + return spawned; +}; + +// Use promises instead of `child_process` events +const getSpawnedPromise$1 = spawned => { + return new Promise((resolve, reject) => { + spawned.on('exit', (exitCode, signal) => { + resolve({exitCode, signal}); + }); + + spawned.on('error', error => { + reject(error); + }); + + if (spawned.stdin) { + spawned.stdin.on('error', error => { + reject(error); + }); + } + }); +}; + +var promise = { + mergePromise: mergePromise$1, + getSpawnedPromise: getSpawnedPromise$1 +}; + +const normalizeArgs = (file, args = []) => { + if (!Array.isArray(args)) { + return [file]; + } + + return [file, ...args]; +}; + +const NO_ESCAPE_REGEXP = /^[\w.-]+$/; +const DOUBLE_QUOTES_REGEXP = /"/g; + +const escapeArg = arg => { + if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) { + return arg; + } + + return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`; +}; + +const joinCommand$1 = (file, args) => { + return normalizeArgs(file, args).join(' '); +}; + +const getEscapedCommand$1 = (file, args) => { + return normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' '); +}; + +const SPACES_REGEXP = / +/g; + +// Handle `execa.command()` +const parseCommand$1 = command => { + const tokens = []; + for (const token of command.trim().split(SPACES_REGEXP)) { + // Allow spaces to be escaped by a backslash if not meant as a delimiter + const previousToken = tokens[tokens.length - 1]; + if (previousToken && previousToken.endsWith('\\')) { + // Merge previous token with current one + tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; + } else { + tokens.push(token); + } + } + + return tokens; +}; + +var command = { + joinCommand: joinCommand$1, + getEscapedCommand: getEscapedCommand$1, + parseCommand: parseCommand$1 +}; + +const path$5 = path__default; +const childProcess$2 = require$$1__default$4; +const crossSpawn = crossSpawn$1.exports; +const stripFinalNewline = stripFinalNewline$1; +const npmRunPath = npmRunPath$1.exports; +const onetime = onetime$2.exports; +const makeError = error; +const normalizeStdio = stdio.exports; +const {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = kill; +const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = stream; +const {mergePromise, getSpawnedPromise} = promise; +const {joinCommand, parseCommand, getEscapedCommand} = command; + +const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; + +const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { + const env = extendEnv ? {...process.env, ...envOption} : envOption; + + if (preferLocal) { + return npmRunPath.env({env, cwd: localDir, execPath}); + } + + return env; +}; + +const handleArguments = (file, args, options = {}) => { + const parsed = crossSpawn._parse(file, args, options); + file = parsed.command; + args = parsed.args; + options = parsed.options; + + options = { + maxBuffer: DEFAULT_MAX_BUFFER, + buffer: true, + stripFinalNewline: true, + extendEnv: true, + preferLocal: false, + localDir: options.cwd || process.cwd(), + execPath: process.execPath, + encoding: 'utf8', + reject: true, + cleanup: true, + all: false, + windowsHide: true, + ...options + }; + + options.env = getEnv(options); + + options.stdio = normalizeStdio(options); + + if (process.platform === 'win32' && path$5.basename(file, '.exe') === 'cmd') { + // #116 + args.unshift('/q'); + } + + return {file, args, options, parsed}; +}; + +const handleOutput = (options, value, error) => { + if (typeof value !== 'string' && !Buffer.isBuffer(value)) { + // When `execa.sync()` errors, we normalize it to '' to mimic `execa()` + return error === undefined ? undefined : ''; + } + + if (options.stripFinalNewline) { + return stripFinalNewline(value); + } + + return value; +}; + +const execa = (file, args, options) => { + const parsed = handleArguments(file, args, options); + const command = joinCommand(file, args); + const escapedCommand = getEscapedCommand(file, args); + + validateTimeout(parsed.options); + + let spawned; + try { + spawned = childProcess$2.spawn(parsed.file, parsed.args, parsed.options); + } catch (error) { + // Ensure the returned error is always both a promise and a child process + const dummySpawned = new childProcess$2.ChildProcess(); + const errorPromise = Promise.reject(makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + escapedCommand, + parsed, + timedOut: false, + isCanceled: false, + killed: false + })); + return mergePromise(dummySpawned, errorPromise); + } + + const spawnedPromise = getSpawnedPromise(spawned); + const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); + const processDone = setExitHandler(spawned, parsed.options, timedPromise); + + const context = {isCanceled: false}; + + spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); + spawned.cancel = spawnedCancel.bind(null, spawned, context); + + const handlePromise = async () => { + const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); + const stdout = handleOutput(parsed.options, stdoutResult); + const stderr = handleOutput(parsed.options, stderrResult); + const all = handleOutput(parsed.options, allResult); + + if (error || exitCode !== 0 || signal !== null) { + const returnedError = makeError({ + error, + exitCode, + signal, + stdout, + stderr, + all, + command, + escapedCommand, + parsed, + timedOut, + isCanceled: context.isCanceled, + killed: spawned.killed + }); + + if (!parsed.options.reject) { + return returnedError; + } + + throw returnedError; + } + + return { + command, + escapedCommand, + exitCode: 0, + stdout, + stderr, + all, + failed: false, + timedOut: false, + isCanceled: false, + killed: false + }; + }; + + const handlePromiseOnce = onetime(handlePromise); + + handleInput(spawned, parsed.options.input); + + spawned.all = makeAllStream(spawned, parsed.options); + + return mergePromise(spawned, handlePromiseOnce); +}; + +execa$2.exports = execa; + +execa$2.exports.sync = (file, args, options) => { + const parsed = handleArguments(file, args, options); + const command = joinCommand(file, args); + const escapedCommand = getEscapedCommand(file, args); + + validateInputSync(parsed.options); + + let result; + try { + result = childProcess$2.spawnSync(parsed.file, parsed.args, parsed.options); + } catch (error) { + throw makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + escapedCommand, + parsed, + timedOut: false, + isCanceled: false, + killed: false + }); + } + + const stdout = handleOutput(parsed.options, result.stdout, result.error); + const stderr = handleOutput(parsed.options, result.stderr, result.error); + + if (result.error || result.status !== 0 || result.signal !== null) { + const error = makeError({ + stdout, + stderr, + error: result.error, + signal: result.signal, + exitCode: result.status, + command, + escapedCommand, + parsed, + timedOut: result.error && result.error.code === 'ETIMEDOUT', + isCanceled: false, + killed: result.signal !== null + }); + + if (!parsed.options.reject) { + return error; + } + + throw error; + } + + return { + command, + escapedCommand, + exitCode: 0, + stdout, + stderr, + failed: false, + timedOut: false, + isCanceled: false, + killed: false + }; +}; + +execa$2.exports.command = (command, options) => { + const [file, ...args] = parseCommand(command); + return execa(file, args, options); +}; + +execa$2.exports.commandSync = (command, options) => { + const [file, ...args] = parseCommand(command); + return execa.sync(file, args, options); +}; + +execa$2.exports.node = (scriptPath, args, options = {}) => { + if (args && !Array.isArray(args) && typeof args === 'object') { + options = args; + args = []; + } + + const stdio = normalizeStdio.node(options); + const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect')); + + const { + nodePath = process.execPath, + nodeOptions = defaultExecArgv + } = options; + + return execa( + nodePath, + [ + ...nodeOptions, + scriptPath, + ...(Array.isArray(args) ? args : []) + ], + { + ...options, + stdin: undefined, + stdout: undefined, + stderr: undefined, + stdio, + shell: false + } + ); +}; + +var execa$1 = execa$2.exports; + +/** + * The following is modified based on source found in + * https://github.com/facebook/create-react-app + * + * MIT Licensed + * Copyright (c) 2015-present, Facebook, Inc. + * https://github.com/facebook/create-react-app/blob/master/LICENSE + * + */ +// https://github.com/sindresorhus/open#app +const OSX_CHROME = 'google chrome'; +/** + * Reads the BROWSER environment variable and decides what to do with it. + * Returns true if it opened a browser or ran a node.js script, otherwise false. + */ +function openBrowser(url, opt, logger) { + // The browser executable to open. + // See https://github.com/sindresorhus/open#app for documentation. + const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''; + if (browser.toLowerCase().endsWith('.js')) { + return executeNodeScript(browser, url, logger); + } + else if (browser.toLowerCase() !== 'none') { + return startBrowserProcess(browser, url); + } + return false; +} +function executeNodeScript(scriptPath, url, logger) { + const extraArgs = process.argv.slice(2); + const child = execa$1('node', [scriptPath, ...extraArgs, url], { + stdio: 'inherit' + }); + child.on('close', (code) => { + if (code !== 0) { + logger.error(source.red(`\nThe script specified as BROWSER environment variable failed.\n\n${source.cyan(scriptPath)} exited with code ${code}.`), { error: null }); + } + }); + return true; +} +function startBrowserProcess(browser, url) { + // If we're on OS X, the user hasn't specifically + // requested a different browser, we can try opening + // Chrome with AppleScript. This lets us reuse an + // existing tab when possible instead of creating a new one. + const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && (browser === '' || browser === OSX_CHROME); + if (shouldTryOpenChromeWithAppleScript) { + try { + // Try our best to reuse existing tab + // on OS X Google Chrome with AppleScript + require$$1$5.execSync('ps cax | grep "Google Chrome"'); + require$$1$5.execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', { + cwd: path__default.dirname(require.resolve('vite/bin/openChrome.applescript')), + stdio: 'ignore' + }); + return true; + } + catch (err) { + // Ignore errors + } + } + // Another special case: on OS X, check if BROWSER has been set to "open". + // In this case, instead of passing the string `open` to `open` function (which won't work), + // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser): + // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768 + if (process.platform === 'darwin' && browser === 'open') { + browser = undefined; + } + // Fallback to open + // (It will always open new tab) + try { + const options = browser ? { app: { name: browser } } : {}; + open_1(url, options).catch(() => { }); // Prevent `unhandledRejection` error. + return true; + } + catch (err) { + return false; + } +} + +var chalk$1 = {exports: {}}; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +var escapeStringRegexp = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + +var ansiStyles = {exports: {}}; + +var conversions$2 = {exports: {}}; + +var colorName = { + "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] +}; + +/* MIT license */ + +var cssKeywords = colorName; + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } +} + +var convert$1 = conversions$2.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +// hide .channels and .labels properties +for (var model in convert$1) { + if (convert$1.hasOwnProperty(model)) { + if (!('channels' in convert$1[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert$1[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert$1[model].labels.length !== convert$1[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert$1[model].channels; + var labels = convert$1[model].labels; + delete convert$1[model].channels; + delete convert$1[model].labels; + Object.defineProperty(convert$1[model], 'channels', {value: channels}); + Object.defineProperty(convert$1[model], 'labels', {value: labels}); + } +} + +convert$1.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert$1.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert$1.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert$1.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert$1.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); +} + +convert$1.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; +}; + +convert$1.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; + +convert$1.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert$1.rgb.lab = function (rgb) { + var xyz = convert$1.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert$1.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert$1.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert$1.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert$1.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert$1.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; +}; + +convert$1.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert$1.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert$1.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert$1.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert$1.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert$1.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert$1.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert$1.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert$1.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]); +}; + +convert$1.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert$1.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert$1.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert$1.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert$1.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; +}; + +convert$1.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert$1.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert$1.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert$1.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert$1.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert$1.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert$1.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert$1.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert$1.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert$1.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert$1.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert$1.gray.hsl = convert$1.gray.hsv = function (args) { + return [0, 0, args[0]]; +}; + +convert$1.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert$1.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert$1.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert$1.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert$1.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; + +var conversions$1 = conversions$2.exports; + +/* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions$1); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions$1[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions$1[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions$1[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +var route$1 = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + +var conversions = conversions$2.exports; +var route = route$1; + +var convert = {}; + +var models = Object.keys(conversions); + +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +var colorConvert = convert; + +(function (module) { +const colorConvert$1 = colorConvert; + +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert$1, arguments); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert$1, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert$1, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert$1)) { + if (typeof colorConvert$1[key] !== 'object') { + continue; + } + + const suite = colorConvert$1[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); +}(ansiStyles)); + +var hasFlag$1 = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; + +const os$2 = require$$0__default$1; +const hasFlag = hasFlag$1; + +const env = process.env; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os$2.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +var supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; + +const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); + +function unescape$1(c) { + if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES.get(c) || c; +} + +function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape$1(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; +} + +var templates = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape$1(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } + + return chunks.join(''); +}; + +(function (module) { +const escapeStringRegexp$1 = escapeStringRegexp; +const ansiStyles$1 = ansiStyles.exports; +const stdoutColor = supportsColor_1.stdout; + +const template = templates; + +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); + +const styles = Object.create(null); + +function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} + +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); +} + +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles$1.blue.open = '\u001B[94m'; +} + +for (const key of Object.keys(ansiStyles$1)) { + ansiStyles$1[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles$1[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} + +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; + +ansiStyles$1.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1.color.close), 'g'); +for (const model of Object.keys(ansiStyles$1.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles$1.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles$1.color.close, + closeRe: ansiStyles$1.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +ansiStyles$1.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles$1.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles$1.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles$1.bgColor.close, + closeRe: ansiStyles$1.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, styles); + +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} + +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles$1.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles$1.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles$1.dim.open = originalDim; + + return str; +} + +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return template(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript +}(chalk$1)); + +var shellQuote$1 = {}; + +shellQuote$1.quote = function (xs) { + return xs.map(function (s) { + if (s && typeof s === 'object') { + return s.op.replace(/(.)/g, '\\$1'); + } + else if (/["\s]/.test(s) && !/'/.test(s)) { + return "'" + s.replace(/(['\\])/g, '\\$1') + "'"; + } + else if (/["'\s]/.test(s)) { + return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"'; + } + else { + return String(s).replace(/([A-z]:)?([#!"$&'()*,:;<=>?@\[\\\]^`{|}])/g, '$1\\$2'); + } + }).join(' '); +}; + +// '<(' is process substitution operator and +// can be parsed the same as control operator +var CONTROL = '(?:' + [ + '\\|\\|', '\\&\\&', ';;', '\\|\\&', '\\<\\(', '>>', '>\\&', '[&;()|<>]' +].join('|') + ')'; +var META = '|&;()<> \\t'; +var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+'; +var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"'; +var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\''; + +var TOKEN = ''; +for (var i = 0; i < 4; i++) { + TOKEN += (Math.pow(16,8)*Math.random()).toString(16); +} + +shellQuote$1.parse = function (s, env, opts) { + var mapped = parse$1(s, env, opts); + if (typeof env !== 'function') return mapped; + return mapped.reduce(function (acc, s) { + if (typeof s === 'object') return acc.concat(s); + var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g')); + if (xs.length === 1) return acc.concat(xs[0]); + return acc.concat(xs.filter(Boolean).map(function (x) { + if (RegExp('^' + TOKEN).test(x)) { + return JSON.parse(x.split(TOKEN)[1]); + } + else return x; + })); + }, []); +}; + +function parse$1 (s, env, opts) { + var chunker = new RegExp([ + '(' + CONTROL + ')', // control chars + '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*' + ].join('|'), 'g'); + var match = s.match(chunker).filter(Boolean); + var commented = false; + + if (!match) return []; + if (!env) env = {}; + if (!opts) opts = {}; + return match.map(function (s, j) { + if (commented) { + return; + } + if (RegExp('^' + CONTROL + '$').test(s)) { + return { op: s }; + } + + // Hand-written scanner/parser for Bash quoting rules: + // + // 1. inside single quotes, all characters are printed literally. + // 2. inside double quotes, all characters are printed literally + // except variables prefixed by '$' and backslashes followed by + // either a double quote or another backslash. + // 3. outside of any quotes, backslashes are treated as escape + // characters and not printed (unless they are themselves escaped) + // 4. quote context can switch mid-token if there is no whitespace + // between the two quote contexts (e.g. all'one'"token" parses as + // "allonetoken") + var SQ = "'"; + var DQ = '"'; + var DS = '$'; + var BS = opts.escape || '\\'; + var quote = false; + var esc = false; + var out = ''; + var isGlob = false; + + for (var i = 0, len = s.length; i < len; i++) { + var c = s.charAt(i); + isGlob = isGlob || (!quote && (c === '*' || c === '?')); + if (esc) { + out += c; + esc = false; + } + else if (quote) { + if (c === quote) { + quote = false; + } + else if (quote == SQ) { + out += c; + } + else { // Double quote + if (c === BS) { + i += 1; + c = s.charAt(i); + if (c === DQ || c === BS || c === DS) { + out += c; + } else { + out += BS + c; + } + } + else if (c === DS) { + out += parseEnvVar(); + } + else { + out += c; + } + } + } + else if (c === DQ || c === SQ) { + quote = c; + } + else if (RegExp('^' + CONTROL + '$').test(c)) { + return { op: s }; + } + else if (RegExp('^#$').test(c)) { + commented = true; + if (out.length){ + return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }]; + } + return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }]; + } + else if (c === BS) { + esc = true; + } + else if (c === DS) { + out += parseEnvVar(); + } + else out += c; + } + + if (isGlob) return {op: 'glob', pattern: out}; + + return out; + + function parseEnvVar() { + i += 1; + var varend, varname; + //debugger + if (s.charAt(i) === '{') { + i += 1; + if (s.charAt(i) === '}') { + throw new Error("Bad substitution: " + s.substr(i - 2, 3)); + } + varend = s.indexOf('}', i); + if (varend < 0) { + throw new Error("Bad substitution: " + s.substr(i)); + } + varname = s.substr(i, varend - i); + i = varend; + } + else if (/[*@#?$!_\-]/.test(s.charAt(i))) { + varname = s.charAt(i); + i += 1; + } + else { + varend = s.substr(i).match(/[^\w\d_]/); + if (!varend) { + varname = s.substr(i); + i = s.length; + } else { + varname = s.substr(i, varend.index); + i += varend.index - 1; + } + } + return getVar(null, '', varname); + } + }) + // finalize parsed aruments + .reduce(function(prev, arg){ + if (arg === undefined){ + return prev; + } + return prev.concat(arg); + },[]); + + function getVar (_, pre, key) { + var r = typeof env === 'function' ? env(key) : env[key]; + if (r === undefined && key != '') + r = ''; + else if (r === undefined) + r = '$'; + + if (typeof r === 'object') { + return pre + TOKEN + JSON.stringify(r) + TOKEN; + } + else return pre + r; + } +} + +var osx = { + '/Applications/Atom.app/Contents/MacOS/Atom': 'atom', + '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta': + '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta', + '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets', + '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text': + '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl', + '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2': + '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl', + '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text': + '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl', + '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code', + '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron': + 'code-insiders', + '/Applications/AppCode.app/Contents/MacOS/appcode': + '/Applications/AppCode.app/Contents/MacOS/appcode', + '/Applications/CLion.app/Contents/MacOS/clion': + '/Applications/CLion.app/Contents/MacOS/clion', + '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea': + '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea', + '/Applications/PhpStorm.app/Contents/MacOS/phpstorm': + '/Applications/PhpStorm.app/Contents/MacOS/phpstorm', + '/Applications/PyCharm.app/Contents/MacOS/pycharm': + '/Applications/PyCharm.app/Contents/MacOS/pycharm', + '/Applications/PyCharm CE.app/Contents/MacOS/pycharm': + '/Applications/PyCharm CE.app/Contents/MacOS/pycharm', + '/Applications/RubyMine.app/Contents/MacOS/rubymine': + '/Applications/RubyMine.app/Contents/MacOS/rubymine', + '/Applications/WebStorm.app/Contents/MacOS/webstorm': + '/Applications/WebStorm.app/Contents/MacOS/webstorm' +}; + +var linux = { + atom: 'atom', + Brackets: 'brackets', + code: 'code', + emacs: 'emacs', + 'idea.sh': 'idea', + 'phpstorm.sh': 'phpstorm', + 'pycharm.sh': 'pycharm', + 'rubymine.sh': 'rubymine', + sublime_text: 'subl', + vim: 'vim', + 'webstorm.sh': 'webstorm' +}; + +var windows = [ + 'Brackets.exe', + 'Code.exe', + 'atom.exe', + 'sublime_text.exe', + 'notepad++.exe', + 'clion.exe', + 'clion64.exe', + 'idea.exe', + 'idea64.exe', + 'phpstorm.exe', + 'phpstorm64.exe', + 'pycharm.exe', + 'pycharm64.exe', + 'rubymine.exe', + 'rubymine64.exe', + 'webstorm.exe', + 'webstorm64.exe' +]; + +const path$4 = path__default; +const shellQuote = shellQuote$1; +const childProcess$1 = require$$1__default$4; + +// Map from full process name to binary that starts the process +// We can't just re-use full process name, because it will spawn a new instance +// of the app every time +const COMMON_EDITORS_OSX = osx; +const COMMON_EDITORS_LINUX = linux; +const COMMON_EDITORS_WIN = windows; + +var guess = function guessEditor (specifiedEditor) { + if (specifiedEditor) { + return shellQuote.parse(specifiedEditor) + } + // We can find out which editor is currently running by: + // `ps x` on macOS and Linux + // `Get-Process` on Windows + try { + if (process.platform === 'darwin') { + const output = childProcess$1.execSync('ps x').toString(); + const processNames = Object.keys(COMMON_EDITORS_OSX); + for (let i = 0; i < processNames.length; i++) { + const processName = processNames[i]; + if (output.indexOf(processName) !== -1) { + return [COMMON_EDITORS_OSX[processName]] + } + } + } else if (process.platform === 'win32') { + const output = childProcess$1 + .execSync('powershell -Command "Get-Process | Select-Object Path"', { + stdio: ['pipe', 'pipe', 'ignore'] + }) + .toString(); + const runningProcesses = output.split('\r\n'); + for (let i = 0; i < runningProcesses.length; i++) { + // `Get-Process` sometimes returns empty lines + if (!runningProcesses[i]) { + continue + } + + const fullProcessPath = runningProcesses[i].trim(); + const shortProcessName = path$4.basename(fullProcessPath); + + if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) { + return [fullProcessPath] + } + } + } else if (process.platform === 'linux') { + // --no-heading No header line + // x List all processes owned by you + // -o comm Need only names column + const output = childProcess$1 + .execSync('ps x --no-heading -o comm --sort=comm') + .toString(); + const processNames = Object.keys(COMMON_EDITORS_LINUX); + for (let i = 0; i < processNames.length; i++) { + const processName = processNames[i]; + if (output.indexOf(processName) !== -1) { + return [COMMON_EDITORS_LINUX[processName]] + } + } + } + } catch (error) { + // Ignore... + } + + // Last resort, use old skool env vars + if (process.env.VISUAL) { + return [process.env.VISUAL] + } else if (process.env.EDITOR) { + return [process.env.EDITOR] + } + + return [null] +}; + +const path$3 = path__default; + +// normalize file/line numbers into command line args for specific editors +var getArgs = function getArgumentsForPosition ( + editor, + fileName, + lineNumber, + columnNumber = 1 +) { + const editorBasename = path$3.basename(editor).replace(/\.(exe|cmd|bat)$/i, ''); + switch (editorBasename) { + case 'atom': + case 'Atom': + case 'Atom Beta': + case 'subl': + case 'sublime': + case 'sublime_text': + case 'wstorm': + case 'charm': + return [`${fileName}:${lineNumber}:${columnNumber}`] + case 'notepad++': + return ['-n' + lineNumber, fileName] + case 'vim': + case 'mvim': + return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName] + case 'joe': + return ['+' + `${lineNumber}`, fileName] + case 'emacs': + case 'emacsclient': + return [`+${lineNumber}:${columnNumber}`, fileName] + case 'rmate': + case 'mate': + case 'mine': + return ['--line', lineNumber, fileName] + case 'code': + case 'code-insiders': + case 'Code': + return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`] + case 'appcode': + case 'clion': + case 'clion64': + case 'idea': + case 'idea64': + case 'phpstorm': + case 'phpstorm64': + case 'pycharm': + case 'pycharm64': + case 'rubymine': + case 'rubymine64': + case 'webstorm': + case 'webstorm64': + return ['--line', lineNumber, fileName] + } + + // For all others, drop the lineNumber until we have + // a mapping above, since providing the lineNumber incorrectly + // can result in errors or confusing behavior. + return [fileName] +}; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file at + * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE + * + * Modified by Yuxi Evan You + */ + +const fs$1 = fs__default; +const os$1 = require$$0__default$1; +const path$2 = path__default; +const chalk = chalk$1.exports; +const childProcess = require$$1__default$4; + +const guessEditor = guess; +const getArgumentsForPosition = getArgs; + +function wrapErrorCallback (cb) { + return (fileName, errorMessage) => { + console.log(); + console.log( + chalk.red('Could not open ' + path$2.basename(fileName) + ' in the editor.') + ); + if (errorMessage) { + if (errorMessage[errorMessage.length - 1] !== '.') { + errorMessage += '.'; + } + console.log( + chalk.red('The editor process exited with an error: ' + errorMessage) + ); + } + console.log(); + if (cb) cb(fileName, errorMessage); + } +} + +function isTerminalEditor (editor) { + switch (editor) { + case 'vim': + case 'emacs': + case 'nano': + return true + } + return false +} + +const positionRE = /:(\d+)(:(\d+))?$/; +function parseFile (file) { + const fileName = file.replace(positionRE, ''); + const match = file.match(positionRE); + const lineNumber = match && match[1]; + const columnNumber = match && match[3]; + return { + fileName, + lineNumber, + columnNumber + } +} + +let _childProcess = null; + +function launchEditor (file, specifiedEditor, onErrorCallback) { + const parsed = parseFile(file); + let { fileName } = parsed; + const { lineNumber, columnNumber } = parsed; + + if (!fs$1.existsSync(fileName)) { + return + } + + if (typeof specifiedEditor === 'function') { + onErrorCallback = specifiedEditor; + specifiedEditor = undefined; + } + + onErrorCallback = wrapErrorCallback(onErrorCallback); + + const [editor, ...args] = guessEditor(specifiedEditor); + if (!editor) { + onErrorCallback(fileName, null); + return + } + + if ( + process.platform === 'linux' && + fileName.startsWith('/mnt/') && + /Microsoft/i.test(os$1.release()) + ) { + // Assume WSL / "Bash on Ubuntu on Windows" is being used, and + // that the file exists on the Windows file system. + // `os.release()` is "4.4.0-43-Microsoft" in the current release + // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364 + // When a Windows editor is specified, interop functionality can + // handle the path translation, but only if a relative path is used. + fileName = path$2.relative('', fileName); + } + + if (lineNumber) { + const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber); + args.push.apply(args, extraArgs); + } else { + args.push(fileName); + } + + if (_childProcess && isTerminalEditor(editor)) { + // There's an existing editor process already and it's attached + // to the terminal, so go kill it. Otherwise two separate editor + // instances attach to the stdin/stdout which gets confusing. + _childProcess.kill('SIGKILL'); + } + + if (process.platform === 'win32') { + // On Windows, launch the editor in a shell because spawn can only + // launch .exe files. + _childProcess = childProcess.spawn( + 'cmd.exe', + ['/C', editor].concat(args), + { stdio: 'inherit' } + ); + } else { + _childProcess = childProcess.spawn(editor, args, { stdio: 'inherit' }); + } + _childProcess.on('exit', function (errorCode) { + _childProcess = null; + + if (errorCode) { + onErrorCallback(fileName, '(code ' + errorCode + ')'); + } + }); + + _childProcess.on('error', function (error) { + onErrorCallback(fileName, error.message); + }); +} + +var launchEditor_1 = launchEditor; + +const url = require$$0__default$7; +const path$1 = path__default; +const launch = launchEditor_1; + +var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => { + if (typeof specifiedEditor === 'function') { + onErrorCallback = specifiedEditor; + specifiedEditor = undefined; + } + + if (typeof srcRoot === 'function') { + onErrorCallback = srcRoot; + srcRoot = undefined; + } + + srcRoot = srcRoot || process.cwd(); + + return function launchEditorMiddleware (req, res, next) { + const { file } = url.parse(req.url, true).query || {}; + if (!file) { + res.statusCode = 500; + res.end(`launch-editor-middleware: required query param "file" is missing.`); + } else { + launch(path$1.resolve(srcRoot, file), specifiedEditor, onErrorCallback); + res.end(); + } + } +}; + +const externalTypes = [ + 'css', + // supported pre-processor types + 'less', + 'sass', + 'scss', + 'styl', + 'stylus', + 'pcss', + 'postcss', + // known SFC types + 'vue', + 'svelte', + 'marko', + // JSX/TSX may be configured to be compiled differently from how esbuild + // handles it by default, so exclude them as well + 'jsx', + 'tsx', + ...KNOWN_ASSET_TYPES +]; +function esbuildDepPlugin(qualified, exportsData, config, ssr) { + // default resolver which prefers ESM + const _resolve = config.createResolver({ asSrc: false }); + // cjs resolver that prefers Node + const _resolveRequire = config.createResolver({ + asSrc: false, + isRequire: true + }); + const resolve = (id, importer, kind, resolveDir) => { + let _importer; + // explicit resolveDir - this is passed only during yarn pnp resolve for + // entries + if (resolveDir) { + _importer = normalizePath$4(path__default.join(resolveDir, '*')); + } + else { + // map importer ids to file paths for correct resolution + _importer = importer in qualified ? qualified[importer] : importer; + } + const resolver = kind.startsWith('require') ? _resolveRequire : _resolve; + return resolver(id, _importer, undefined, ssr); + }; + return { + name: 'vite:dep-pre-bundle', + setup(build) { + // externalize assets and commonly known non-js file types + build.onResolve({ + filter: new RegExp(`\\.(` + externalTypes.join('|') + `)(\\?.*)?$`) + }, async ({ path: id, importer, kind }) => { + const resolved = await resolve(id, importer, kind); + if (resolved) { + return { + path: resolved, + external: true + }; + } + }); + function resolveEntry(id) { + const flatId = flattenId(id); + if (flatId in qualified) { + return { + path: flatId, + namespace: 'dep' + }; + } + } + build.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => { + // ensure esbuild uses our resolved entries + let entry; + // if this is an entry, return entry namespace resolve result + if (!importer) { + if ((entry = resolveEntry(id))) + return entry; + // check if this is aliased to an entry - also return entry namespace + const aliased = await _resolve(id, undefined, true); + if (aliased && (entry = resolveEntry(aliased))) { + return entry; + } + } + // use vite's own resolver + const resolved = await resolve(id, importer, kind); + if (resolved) { + if (resolved.startsWith(browserExternalId)) { + return { + path: id, + namespace: 'browser-external' + }; + } + if (isExternalUrl(resolved)) { + return { + path: resolved, + external: true + }; + } + return { + path: path__default.resolve(resolved) + }; + } + }); + // For entry files, we'll read it ourselves and construct a proxy module + // to retain the entry's raw id instead of file path so that esbuild + // outputs desired output file structure. + // It is necessary to do the re-exporting to separate the virtual proxy + // module from the actual module since the actual module may get + // referenced via relative imports - if we don't separate the proxy and + // the actual module, esbuild will create duplicated copies of the same + // module! + const root = path__default.resolve(config.root); + build.onLoad({ filter: /.*/, namespace: 'dep' }, ({ path: id }) => { + const entryFile = qualified[id]; + let relativePath = normalizePath$4(path__default.relative(root, entryFile)); + if (!relativePath.startsWith('./') && + !relativePath.startsWith('../') && + relativePath !== '.') { + relativePath = `./${relativePath}`; + } + let contents = ''; + const data = exportsData[id]; + const [imports, exports] = data; + if (!imports.length && !exports.length) { + // cjs + contents += `export default require("${relativePath}");`; + } + else { + if (exports.includes('default')) { + contents += `import d from "${relativePath}";export default d;`; + } + if (data.hasReExports || + exports.length > 1 || + exports[0] !== 'default') { + contents += `\nexport * from "${relativePath}"`; + } + } + let ext = path__default.extname(entryFile).slice(1); + if (ext === 'mjs') + ext = 'js'; + return { + loader: ext, + contents, + resolveDir: root + }; + }); + build.onLoad({ filter: /.*/, namespace: 'browser-external' }, ({ path: id }) => { + return { + contents: `export default new Proxy({}, { + get() { + throw new Error('Module "${id}" has been externalized for ` + + `browser compatibility and cannot be accessed in client code.') + } +})` + }; + }); + // yarn 2 pnp compat + if (isRunningWithYarnPnp) { + build.onResolve({ filter: /.*/ }, async ({ path, importer, kind, resolveDir }) => ({ + // pass along resolveDir for entries + path: await resolve(path, importer, kind, resolveDir) + })); + build.onLoad({ filter: /.*/ }, async (args) => ({ + contents: await require('fs').promises.readFile(args.path), + loader: 'default' + })); + } + } + }; +} + +const debug$1 = createDebugger('vite:deps'); +async function optimizeDeps(config, force = config.server.force, asCommand = false, newDeps, // missing imports encountered after server has started +ssr) { + var _a, _b, _c, _d; + config = { + ...config, + command: 'build' + }; + const { root, logger, cacheDir } = config; + const log = asCommand ? logger.info : debug$1; + if (!cacheDir) { + log(`No cache directory. Skipping.`); + return null; + } + const dataPath = path__default.join(cacheDir, '_metadata.json'); + const mainHash = getDepHash(root, config); + const data = { + hash: mainHash, + browserHash: mainHash, + optimized: {} + }; + if (!force) { + let prevData; + try { + prevData = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8')); + } + catch (e) { } + // hash is consistent, no need to re-bundle + if (prevData && prevData.hash === data.hash) { + log('Hash is consistent. Skipping. Use --force to override.'); + return prevData; + } + } + if (fs__default.existsSync(cacheDir)) { + emptyDir(cacheDir); + } + else { + fs__default.mkdirSync(cacheDir, { recursive: true }); + } + // a hint for Node.js + // all files in the cache directory should be recognized as ES modules + writeFile(path__default.resolve(cacheDir, 'package.json'), JSON.stringify({ type: 'module' })); + let deps, missing; + if (!newDeps) { + ({ deps, missing } = await scanImports(config)); + } + else { + deps = newDeps; + missing = {}; + } + // update browser hash + data.browserHash = require$$1$1.createHash('sha256') + .update(data.hash + JSON.stringify(deps)) + .digest('hex') + .substr(0, 8); + const missingIds = Object.keys(missing); + if (missingIds.length) { + throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds + .map((id) => `${source.cyan(id)} ${source.white.dim(`(imported by ${missing[id]})`)}`) + .join(`\n `)}\n\nAre they installed?`); + } + const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include; + if (include) { + const resolve = config.createResolver({ asSrc: false }); + for (const id of include) { + // normalize 'foo >bar` as 'foo > bar' to prevent same id being added + // and for pretty printing + const normalizedId = normalizeId$1(id); + if (!deps[normalizedId]) { + const entry = await resolve(id); + if (entry) { + deps[normalizedId] = entry; + } + else { + throw new Error(`Failed to resolve force included dependency: ${source.cyan(id)}`); + } + } + } + } + const qualifiedIds = Object.keys(deps); + if (!qualifiedIds.length) { + writeFile(dataPath, JSON.stringify(data, null, 2)); + log(`No dependencies to bundle. Skipping.\n\n\n`); + return data; + } + const total = qualifiedIds.length; + const maxListed = 5; + const listed = Math.min(total, maxListed); + const extra = Math.max(0, total - maxListed); + const depsString = source.yellow(qualifiedIds.slice(0, listed).join(`\n `) + + (extra > 0 ? `\n (...and ${extra} more)` : ``)); + if (!asCommand) { + if (!newDeps) { + // This is auto run on server start - let the user know that we are + // pre-optimizing deps + logger.info(source.greenBright(`Pre-bundling dependencies:\n ${depsString}`)); + logger.info(`(this will be run only when your dependencies or config have changed)`); + } + } + else { + logger.info(source.greenBright(`Optimizing dependencies:\n ${depsString}`)); + } + // esbuild generates nested directory output with lowest common ancestor base + // this is unpredictable and makes it difficult to analyze entry / output + // mapping. So what we do here is: + // 1. flatten all ids to eliminate slash + // 2. in the plugin, read the entry ourselves as virtual files to retain the + // path. + const flatIdDeps = {}; + const idToExports = {}; + const flatIdToExports = {}; + const { plugins = [], ...esbuildOptions } = (_c = (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.esbuildOptions) !== null && _c !== void 0 ? _c : {}; + await init; + for (const id in deps) { + const flatId = flattenId(id); + const filePath = (flatIdDeps[flatId] = deps[id]); + const entryContent = fs__default.readFileSync(filePath, 'utf-8'); + let exportsData; + try { + exportsData = parse$d(entryContent); + } + catch { + debug$1(`Unable to parse dependency: ${id}. Trying again with a JSX transform.`); + const transformed = await transformWithEsbuild(entryContent, filePath, { + loader: 'jsx' + }); + // Ensure that optimization won't fail by defaulting '.js' to the JSX parser. + // This is useful for packages such as Gatsby. + esbuildOptions.loader = { + '.js': 'jsx', + ...esbuildOptions.loader + }; + exportsData = parse$d(transformed.code); + } + for (const { ss, se } of exportsData[0]) { + const exp = entryContent.slice(ss, se); + if (/export\s+\*\s+from/.test(exp)) { + exportsData.hasReExports = true; + } + } + idToExports[id] = exportsData; + flatIdToExports[flatId] = exportsData; + } + const define = { + 'process.env.NODE_ENV': JSON.stringify(config.mode) + }; + for (const key in config.define) { + const value = config.define[key]; + define[key] = typeof value === 'string' ? value : JSON.stringify(value); + } + const start = Date.now(); + const result = await esbuild.build({ + absWorkingDir: process.cwd(), + entryPoints: Object.keys(flatIdDeps), + bundle: true, + format: 'esm', + external: (_d = config.optimizeDeps) === null || _d === void 0 ? void 0 : _d.exclude, + logLevel: 'error', + splitting: true, + sourcemap: true, + outdir: cacheDir, + treeShaking: 'ignore-annotations', + metafile: true, + define, + plugins: [ + ...plugins, + esbuildDepPlugin(flatIdDeps, flatIdToExports, config, ssr) + ], + ...esbuildOptions + }); + const meta = result.metafile; + // the paths in `meta.outputs` are relative to `process.cwd()` + const cacheDirOutputPath = path__default.relative(process.cwd(), cacheDir); + for (const id in deps) { + const entry = deps[id]; + data.optimized[id] = { + file: normalizePath$4(path__default.resolve(cacheDir, flattenId(id) + '.js')), + src: entry, + needsInterop: needsInterop(id, idToExports[id], meta.outputs, cacheDirOutputPath) + }; + } + writeFile(dataPath, JSON.stringify(data, null, 2)); + debug$1(`deps bundled in ${Date.now() - start}ms`); + return data; +} +// https://github.com/vitejs/vite/issues/1724#issuecomment-767619642 +// a list of modules that pretends to be ESM but still uses `require`. +// this causes esbuild to wrap them as CJS even when its entry appears to be ESM. +const KNOWN_INTEROP_IDS = new Set(['moment']); +function needsInterop(id, exportsData, outputs, cacheDirOutputPath) { + if (KNOWN_INTEROP_IDS.has(id)) { + return true; + } + const [imports, exports] = exportsData; + // entry has no ESM syntax - likely CJS or UMD + if (!exports.length && !imports.length) { + return true; + } + // if a peer dependency used require() on a ESM dependency, esbuild turns the + // ESM dependency's entry chunk into a single default export... detect + // such cases by checking exports mismatch, and force interop. + const flatId = flattenId(id) + '.js'; + let generatedExports; + for (const output in outputs) { + if (normalizePath$4(output) === + normalizePath$4(path__default.join(cacheDirOutputPath, flatId))) { + generatedExports = outputs[output].exports; + break; + } + } + if (!generatedExports || + (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))) { + return true; + } + return false; +} +function isSingleDefaultExport(exports) { + return exports.length === 1 && exports[0] === 'default'; +} +const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']; +function getDepHash(root, config) { + var _a, _b; + let content = lookupFile(root, lockfileFormats) || ''; + // also take config into account + // only a subset of config options that can affect dep optimization + content += JSON.stringify({ + mode: config.mode, + root: config.root, + resolve: config.resolve, + assetsInclude: config.assetsInclude, + plugins: config.plugins.map((p) => p.name), + optimizeDeps: { + include: (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include, + exclude: (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude + } + }, (_, value) => { + if (typeof value === 'function' || value instanceof RegExp) { + return value.toString(); + } + return value; + }); + return require$$1$1.createHash('sha256').update(content).digest('hex').substr(0, 8); +} + +var index$1 = { + __proto__: null, + optimizeDeps: optimizeDeps +}; + +var sourceMapGenerator = {}; + +var base64Vlq = {}; + +var base64$1 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +base64$1.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +base64$1.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = base64$1; + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +base64Vlq.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; + +var util$5 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +(function (exports) { +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port; + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; +}(util$5)); + +var arraySet = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util$4 = util$5; +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet$2() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet$2(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet$2.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet$2.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util$4.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util$4.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet$2.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet$2.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +arraySet.ArraySet = ArraySet$2; + +var mappingList = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util$3 = util$5; + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList$1() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList$1.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList$1.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList$1.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util$3.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +mappingList.MappingList = MappingList$1; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ$1 = base64Vlq; +var util$2 = util$5; +var ArraySet$1 = arraySet.ArraySet; +var MappingList = mappingList.MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator$1(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util$2.getArg(aArgs, 'file', null); + this._sourceRoot = util$2.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util$2.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet$1(); + this._names = new ArraySet$1(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator$1.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator$1.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator$1({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util$2.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util$2.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator$1.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util$2.getArg(aArgs, 'generated'); + var original = util$2.getArg(aArgs, 'original', null); + var source = util$2.getArg(aArgs, 'source', null); + var name = util$2.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator$1.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util$2.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util$2.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util$2.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator$1.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util$2.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet$1(); + var newNames = new ArraySet$1(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util$2.join(aSourceMapPath, mapping.source); + } + if (sourceRoot != null) { + mapping.source = util$2.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util$2.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util$2.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator$1.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator$1.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = ''; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ$1.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ$1.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ$1.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ$1.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ$1.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator$1.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util$2.relative(aSourceRoot, source); + } + var key = util$2.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator$1.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator$1.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$1; + +var sourceMapConsumer = {}; + +var binarySearch$1 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +(function (exports) { +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; +}(binarySearch$1)); + +var quickSort$1 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +quickSort$1.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util$1 = util$5; +var binarySearch = binarySearch$1; +var ArraySet = arraySet.ArraySet; +var base64VLQ = base64Vlq; +var quickSort = quickSort$1.quickSort; + +function SourceMapConsumer$1(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util$1.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +}; + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer$1.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer$1.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer$1.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer$1.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer$1.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer$1.GENERATED_ORDER = 1; +SourceMapConsumer$1.ORIGINAL_ORDER = 2; + +SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer$1.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer$1.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer$1.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer$1.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer$1.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util$1.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util$1.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util$1.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util$1.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util$1.getArg(mapping, 'generatedLine', null), + column: util$1.getArg(mapping, 'generatedColumn', null), + lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util$1.getArg(mapping, 'generatedLine', null), + column: util$1.getArg(mapping, 'generatedColumn', null), + lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util$1.parseSourceMapInput(aSourceMap); + } + + var version = util$1.getArg(sourceMap, 'version'); + var sources = util$1.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util$1.getArg(sourceMap, 'names', []); + var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null); + var mappings = util$1.getArg(sourceMap, 'mappings'); + var file = util$1.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util$1.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util$1.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source) + ? util$1.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util$1.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util$1.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util$1.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util$1.getArg(aArgs, 'line'), + generatedColumn: util$1.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util$1.compareByGeneratedPositionsDeflated, + util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util$1.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util$1.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util$1.getArg(mapping, 'originalLine', null), + column: util$1.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util$1.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util$1.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util$1.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util$1.getArg(aArgs, 'line'), + originalColumn: util$1.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util$1.compareByOriginalPositions, + util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util$1.getArg(mapping, 'generatedLine', null), + column: util$1.getArg(mapping, 'generatedColumn', null), + lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util$1.parseSourceMapInput(aSourceMap); + } + + var version = util$1.getArg(sourceMap, 'version'); + var sections = util$1.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util$1.getArg(s, 'offset'); + var offsetLine = util$1.getArg(offset, 'line'); + var offsetColumn = util$1.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer$1(util$1.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util$1.getArg(aArgs, 'line'), + generatedColumn: util$1.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util$1.compareByOriginalPositions); + }; + +sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = sourceMapGenerator.SourceMapGenerator; +var util = util$5; + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +var SourceMapConsumer = sourceMapConsumer.SourceMapConsumer; + +let offset; +try { + new Function('throw new Error(1)')(); +} +catch (e) { + // in Node 12, stack traces account for the function wrapper. + // in Node 13 and later, the function wrapper adds two lines, + // which must be subtracted to generate a valid mapping + const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]); + offset = match ? +match[1] - 1 : 0; +} +function ssrRewriteStacktrace(stack, moduleGraph) { + return stack + .split('\n') + .map((line) => { + return line.replace(/^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/, (input, varName, url, line, column) => { + var _a; + if (!url) + return input; + const mod = moduleGraph.urlToModuleMap.get(url); + const rawSourceMap = (_a = mod === null || mod === void 0 ? void 0 : mod.ssrTransformResult) === null || _a === void 0 ? void 0 : _a.map; + if (!rawSourceMap) { + return input; + } + const consumer = new SourceMapConsumer(rawSourceMap); + const pos = consumer.originalPositionFor({ + line: Number(line) - offset, + column: Number(column), + bias: SourceMapConsumer.LEAST_UPPER_BOUND + }); + if (!pos.source) { + return input; + } + const source = `${pos.source}:${pos.line || 0}:${pos.column || 0}`; + if (!varName || varName === 'eval') { + return ` at ${source}`; + } + else { + return ` at ${varName} (${source})`; + } + }); + }) + .join('\n'); +} +function rebindErrorStacktrace(e, stacktrace) { + const { configurable, writable } = Object.getOwnPropertyDescriptor(e, 'stack'); + if (configurable) { + Object.defineProperty(e, 'stack', { + value: stacktrace, + enumerable: true, + configurable: true, + writable: true + }); + } + else if (writable) { + e.stack = stacktrace; + } +} + +const pendingModules = new Map(); +const pendingImports = new Map(); +async function ssrLoadModule(url, server, context = { global }, urlStack = []) { + url = unwrapId$1(url); + // when we instantiate multiple dependency modules in parallel, they may + // point to shared modules. We need to avoid duplicate instantiation attempts + // by register every module as pending synchronously so that all subsequent + // request to that module are simply waiting on the same promise. + const pending = pendingModules.get(url); + if (pending) { + return pending; + } + const modulePromise = instantiateModule(url, server, context, urlStack); + pendingModules.set(url, modulePromise); + modulePromise + .catch(() => { + pendingImports.delete(url); + }) + .finally(() => { + pendingModules.delete(url); + }); + return modulePromise; +} +async function instantiateModule(url, server, context = { global }, urlStack = []) { + const { moduleGraph } = server; + const mod = await moduleGraph.ensureEntryFromUrl(url); + if (mod.ssrModule) { + return mod.ssrModule; + } + const result = mod.ssrTransformResult || + (await transformRequest(url, server, { ssr: true })); + if (!result) { + // TODO more info? is this even necessary? + throw new Error(`failed to load module for ssr: ${url}`); + } + const ssrModule = { + [Symbol.toStringTag]: 'Module' + }; + Object.defineProperty(ssrModule, '__esModule', { value: true }); + // Tolerate circular imports by ensuring the module can be + // referenced before it's been instantiated. + mod.ssrModule = ssrModule; + const ssrImportMeta = { url }; + urlStack = urlStack.concat(url); + const isCircular = (url) => urlStack.includes(url); + // Since dynamic imports can happen in parallel, we need to + // account for multiple pending deps and duplicate imports. + const pendingDeps = []; + const ssrImport = async (dep) => { + var _a, _b; + if (dep[0] !== '.' && dep[0] !== '/') { + return nodeRequire(dep, mod.file, server.config.root); + } + dep = unwrapId$1(dep); + if (!isCircular(dep) && !((_a = pendingImports.get(dep)) === null || _a === void 0 ? void 0 : _a.some(isCircular))) { + pendingDeps.push(dep); + if (pendingDeps.length === 1) { + pendingImports.set(url, pendingDeps); + } + await ssrLoadModule(dep, server, context, urlStack); + if (pendingDeps.length === 1) { + pendingImports.delete(url); + } + else { + pendingDeps.splice(pendingDeps.indexOf(dep), 1); + } + } + return (_b = moduleGraph.urlToModuleMap.get(dep)) === null || _b === void 0 ? void 0 : _b.ssrModule; + }; + const ssrDynamicImport = (dep) => { + // #3087 dynamic import vars is ignored at rewrite import path, + // so here need process relative path + if (dep[0] === '.') { + dep = path__default.posix.resolve(path__default.dirname(url), dep); + } + return ssrImport(dep); + }; + function ssrExportAll(sourceModule) { + for (const key in sourceModule) { + if (key !== 'default') { + Object.defineProperty(ssrModule, key, { + enumerable: true, + configurable: true, + get() { + return sourceModule[key]; + } + }); + } + } + } + try { + // eslint-disable-next-line @typescript-eslint/no-empty-function + const AsyncFunction = async function () { }.constructor; + const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, result.code + `\n//# sourceURL=${mod.url}`); + await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll); + } + catch (e) { + const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph); + rebindErrorStacktrace(e, stacktrace); + server.config.logger.error(`Error when evaluating SSR module ${url}:\n${stacktrace}`, { + timestamp: true, + clear: server.config.clearScreen, + error: e + }); + throw e; + } + return Object.freeze(ssrModule); +} +function nodeRequire(id, importer, root) { + const mod = require(resolve(id, importer, root)); + const defaultExport = mod.__esModule ? mod.default : mod; + // rollup-style default import interop for cjs + return new Proxy(mod, { + get(mod, prop) { + if (prop === 'default') + return defaultExport; + return mod[prop]; + } + }); +} +const resolveCache = new Map(); +function resolve(id, importer, root) { + const key = id + importer + root; + const cached = resolveCache.get(key); + if (cached) { + return cached; + } + const resolveDir = importer && fs__default.existsSync(cleanUrl(importer)) + ? path__default.dirname(importer) + : root; + const resolved = resolveFrom$3(id, resolveDir, true); + resolveCache.set(key, resolved); + return resolved; +} + +/** + * The amount to wait for requests to register newly found dependencies before triggering + * a re-bundle + page reload + */ +const debounceMs = 100; +function createMissingImporterRegisterFn(server) { + const { logger } = server.config; + let knownOptimized = server._optimizeDepsMetadata.optimized; + let currentMissing = {}; + let handle; + let pendingResolve = null; + async function rerun(ssr) { + const newDeps = currentMissing; + currentMissing = {}; + logger.info(source.yellow(`new dependencies found: ${Object.keys(newDeps).join(', ')}, updating...`), { + timestamp: true + }); + for (const id in knownOptimized) { + newDeps[id] = knownOptimized[id].src; + } + try { + // Nullify previous metadata so that the resolver won't + // resolve to optimized files during the optimizer re-run + server._isRunningOptimizer = true; + server._optimizeDepsMetadata = null; + const newData = (server._optimizeDepsMetadata = await optimizeDeps(server.config, true, false, newDeps, ssr)); + knownOptimized = newData.optimized; + // update ssr externals + server._ssrExternals = resolveSSRExternal(server.config, Object.keys(knownOptimized)); + logger.info(source.greenBright(`✨ dependencies updated, reloading page...`), { timestamp: true }); + } + catch (e) { + logger.error(source.red(`error while updating dependencies:\n${e.stack}`), { timestamp: true, error: e }); + } + finally { + server._isRunningOptimizer = false; + pendingResolve && pendingResolve(); + server._pendingReload = pendingResolve = null; + } + // Cached transform results have stale imports (resolved to + // old locations) so they need to be invalidated before the page is + // reloaded. + server.moduleGraph.invalidateAll(); + server.ws.send({ + type: 'full-reload', + path: '*' + }); + } + return function registerMissingImport(id, resolved, ssr) { + if (!knownOptimized[id]) { + currentMissing[id] = resolved; + if (handle) + clearTimeout(handle); + handle = setTimeout(() => rerun(ssr), debounceMs); + server._pendingReload = new Promise((r) => { + pendingResolve = r; + }); + } + }; +} + +// https://github.com/vitejs/vite/issues/2820#issuecomment-812495079 +const ROOT_FILES = [ + // '.git', + // https://pnpm.js.org/workspaces/ + 'pnpm-workspace.yaml' + // https://rushjs.io/pages/advanced/config_files/ + // 'rush.json', + // https://nx.dev/latest/react/getting-started/nx-setup + // 'workspace.json', + // 'nx.json' +]; +// npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces +// yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it +function hasWorkspacePackageJSON(root) { + const path = path$w.join(root, 'package.json'); + try { + fs__default.accessSync(path, fs__default.constants.R_OK); + } + catch { + return false; + } + const content = JSON.parse(fs__default.readFileSync(path, 'utf-8')) || {}; + return !!content.workspaces; +} +function hasRootFile(root) { + return ROOT_FILES.some((file) => fs__default.existsSync(path$w.join(root, file))); +} +function hasPackageJSON(root) { + const path = path$w.join(root, 'package.json'); + return fs__default.existsSync(path); +} +/** + * Search up for the nearest `package.json` + */ +function searchForPackageRoot(current, root = current) { + if (hasPackageJSON(current)) + return current; + const dir = path$w.dirname(current); + // reach the fs root + if (!dir || dir === current) + return root; + return searchForPackageRoot(dir, root); +} +/** + * Search up for the nearest workspace root + */ +function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) { + if (hasRootFile(current)) + return current; + if (hasWorkspacePackageJSON(current)) + return current; + const dir = path$w.dirname(current); + // reach the fs root + if (!dir || dir === current) + return root; + return searchForWorkspaceRoot(dir, root); +} + +async function createServer(inlineConfig = {}) { + const config = await resolveConfig(inlineConfig, 'serve', 'development'); + const root = config.root; + const serverConfig = config.server; + const httpsOptions = await resolveHttpsConfig(config); + let { middlewareMode } = serverConfig; + if (middlewareMode === true) { + middlewareMode = 'ssr'; + } + const middlewares = connect(); + const httpServer = middlewareMode + ? null + : await resolveHttpServer(serverConfig, middlewares, httpsOptions); + const ws = createWebSocketServer(httpServer, config, httpsOptions); + const { ignored = [], ...watchOptions } = serverConfig.watch || {}; + const watcher = chokidar.watch(path__default.resolve(root), { + ignored: [ + '**/node_modules/**', + '**/.git/**', + ...(Array.isArray(ignored) ? ignored : [ignored]) + ], + ignoreInitial: true, + ignorePermissionErrors: true, + disableGlobbing: true, + ...watchOptions + }); + const plugins = config.plugins; + const container = await createPluginContainer(config, watcher); + const moduleGraph = new ModuleGraph(container); + const closeHttpServer = createServerCloseFn(httpServer); + // eslint-disable-next-line prefer-const + let exitProcess; + const server = { + config: config, + middlewares, + get app() { + config.logger.warn(`ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`); + return middlewares; + }, + httpServer, + watcher, + pluginContainer: container, + ws, + moduleGraph, + transformWithEsbuild, + transformRequest(url, options) { + return transformRequest(url, server, options); + }, + transformIndexHtml: null, + ssrLoadModule(url) { + if (!server._ssrExternals) { + server._ssrExternals = resolveSSRExternal(config, server._optimizeDepsMetadata + ? Object.keys(server._optimizeDepsMetadata.optimized) + : []); + } + return ssrLoadModule(url, server); + }, + ssrFixStacktrace(e) { + if (e.stack) { + const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph); + rebindErrorStacktrace(e, stacktrace); + } + }, + listen(port, isRestart) { + return startServer(server, port, isRestart); + }, + async close() { + process.off('SIGTERM', exitProcess); + if (!middlewareMode && process.env.CI !== 'true') { + process.stdin.off('end', exitProcess); + } + await Promise.all([ + watcher.close(), + ws.close(), + container.close(), + closeHttpServer() + ]); + }, + _optimizeDepsMetadata: null, + _ssrExternals: null, + _globImporters: {}, + _isRunningOptimizer: false, + _registerMissingImport: null, + _pendingReload: null + }; + server.transformIndexHtml = createDevHtmlTransformFn(server); + exitProcess = async () => { + try { + await server.close(); + } + finally { + process.exit(0); + } + }; + process.once('SIGTERM', exitProcess); + if (!middlewareMode && process.env.CI !== 'true') { + process.stdin.on('end', exitProcess); + } + watcher.on('change', async (file) => { + file = normalizePath$4(file); + // invalidate module graph cache on file change + moduleGraph.onFileChange(file); + if (serverConfig.hmr !== false) { + try { + await handleHMRUpdate(file, server); + } + catch (err) { + ws.send({ + type: 'error', + err: prepareError(err) + }); + } + } + }); + watcher.on('add', (file) => { + handleFileAddUnlink(normalizePath$4(file), server); + }); + watcher.on('unlink', (file) => { + handleFileAddUnlink(normalizePath$4(file), server, true); + }); + if (!middlewareMode && httpServer) { + httpServer.once('listening', () => { + // update actual port since this may be different from initial value + serverConfig.port = httpServer.address().port; + }); + } + // apply server configuration hooks from plugins + const postHooks = []; + for (const plugin of plugins) { + if (plugin.configureServer) { + postHooks.push(await plugin.configureServer(server)); + } + } + // Internal middlewares ------------------------------------------------------ + // request timer + if (process.env.DEBUG) { + middlewares.use(timeMiddleware(root)); + } + // cors (enabled by default) + const { cors } = serverConfig; + if (cors !== false) { + middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors)); + } + // proxy + const { proxy } = serverConfig; + if (proxy) { + middlewares.use(proxyMiddleware(httpServer, config)); + } + // base + if (config.base !== '/') { + middlewares.use(baseMiddleware(server)); + } + // open in editor support + middlewares.use('/__open-in-editor', launchEditorMiddleware()); + // hmr reconnect ping + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + middlewares.use('/__vite_ping', function viteHMRPingMiddleware(_, res) { + res.end('pong'); + }); + // serve static files under /public + // this applies before the transform middleware so that these files are served + // as-is without transforms. + if (config.publicDir) { + middlewares.use(servePublicMiddleware(config.publicDir)); + } + // main transform middleware + middlewares.use(transformMiddleware(server)); + // serve static files + middlewares.use(serveRawFsMiddleware(server)); + middlewares.use(serveStaticMiddleware(root, config)); + // spa fallback + if (!middlewareMode || middlewareMode === 'html') { + middlewares.use(history({ + logger: createDebugger('vite:spa-fallback'), + // support /dir/ without explicit index.html + rewrites: [ + { + from: /\/$/, + to({ parsedUrl }) { + const rewritten = parsedUrl.pathname + 'index.html'; + if (fs__default.existsSync(path__default.join(root, rewritten))) { + return rewritten; + } + else { + return `/index.html`; + } + } + } + ] + })); + } + // run post config hooks + // This is applied before the html middleware so that user middleware can + // serve custom content instead of index.html. + postHooks.forEach((fn) => fn && fn()); + if (!middlewareMode || middlewareMode === 'html') { + // transform index.html + middlewares.use(indexHtmlMiddleware(server)); + // handle 404s + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + middlewares.use(function vite404Middleware(_, res) { + res.statusCode = 404; + res.end(); + }); + } + // error handler + middlewares.use(errorMiddleware(server, !!middlewareMode)); + const runOptimize = async () => { + if (config.cacheDir) { + server._isRunningOptimizer = true; + try { + server._optimizeDepsMetadata = await optimizeDeps(config); + } + finally { + server._isRunningOptimizer = false; + } + server._registerMissingImport = createMissingImporterRegisterFn(server); + } + }; + if (!middlewareMode && httpServer) { + let isOptimized = false; + // overwrite listen to run optimizer before server start + const listen = httpServer.listen.bind(httpServer); + httpServer.listen = (async (port, ...args) => { + if (!isOptimized) { + try { + await container.buildStart({}); + await runOptimize(); + isOptimized = true; + } + catch (e) { + httpServer.emit('error', e); + return; + } + } + return listen(port, ...args); + }); + } + else { + await container.buildStart({}); + await runOptimize(); + } + return server; +} +async function startServer(server, inlinePort, isRestart = false) { + const httpServer = server.httpServer; + if (!httpServer) { + throw new Error('Cannot call server.listen in middleware mode.'); + } + const options = server.config.server; + const port = inlinePort || options.port || 3000; + const hostname = resolveHostname(options.host); + const protocol = options.https ? 'https' : 'http'; + const info = server.config.logger.info; + const base = server.config.base; + const serverPort = await httpServerStart(httpServer, { + port, + strictPort: options.strictPort, + host: hostname.host, + logger: server.config.logger + }); + info(source.cyan(`\n vite v${require('vite/package.json').version}`) + + source.green(` dev server running at:\n`), { + clear: !server.config.logger.hasWarned + }); + printServerUrls(hostname, protocol, serverPort, base, info); + // @ts-ignore + if (global.__vite_start_time) { + info(source.cyan( + // @ts-ignore + `\n ready in ${Date.now() - global.__vite_start_time}ms.\n`)); + } + // @ts-ignore + const profileSession = global.__vite_profile_session; + if (profileSession) { + profileSession.post('Profiler.stop', (err, { profile }) => { + // Write profile to disk, upload, etc. + if (!err) { + const outPath = path__default.resolve('./vite-profile.cpuprofile'); + fs__default.writeFileSync(outPath, JSON.stringify(profile)); + info(source.yellow(` CPU profile written to ${source.white.dim(outPath)}\n`)); + } + else { + throw err; + } + }); + } + if (options.open && !isRestart) { + const path = typeof options.open === 'string' ? options.open : base; + openBrowser(`${protocol}://${hostname.name}:${serverPort}${path}`, true, server.config.logger); + } + return server; +} +function createServerCloseFn(server) { + if (!server) { + return () => { }; + } + let hasListened = false; + const openSockets = new Set(); + server.on('connection', (socket) => { + openSockets.add(socket); + socket.on('close', () => { + openSockets.delete(socket); + }); + }); + server.once('listening', () => { + hasListened = true; + }); + return () => new Promise((resolve, reject) => { + openSockets.forEach((s) => s.destroy()); + if (hasListened) { + server.close((err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + } + else { + resolve(); + } + }); +} +function resolvedAllowDir(root, dir) { + return ensureLeadingSlash(normalizePath$4(path__default.resolve(root, dir))); +} +function resolveServerOptions(root, raw) { + var _a, _b; + const server = raw || {}; + let allowDirs = (_a = server.fs) === null || _a === void 0 ? void 0 : _a.allow; + if (!allowDirs) { + allowDirs = [searchForWorkspaceRoot(root)]; + } + allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i)); + // only push client dir when vite itself is outside-of-root + const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR); + if (!allowDirs.some((i) => resolvedClientDir.startsWith(i))) { + allowDirs.push(resolvedClientDir); + } + server.fs = { + // TODO: make strict by default + strict: (_b = server.fs) === null || _b === void 0 ? void 0 : _b.strict, + allow: allowDirs + }; + return server; +} + +var index = { + __proto__: null, + createServer: createServer, + resolveServerOptions: resolveServerOptions +}; + +const noop = () => null; +function matches(pattern, importee) { + if (pattern instanceof RegExp) { + return pattern.test(importee); + } + if (importee.length < pattern.length) { + return false; + } + if (importee === pattern) { + return true; + } + const importeeStartsWithKey = importee.indexOf(pattern) === 0; + const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/'; + return importeeStartsWithKey && importeeHasSlashAfterKey; +} +function normalizeId(id) { + return id; +} +function getEntries({ entries }) { + if (!entries) { + return []; + } + if (Array.isArray(entries)) { + return entries; + } + return Object.entries(entries).map(([key, value]) => { + return { find: key, replacement: value }; + }); +} +function getCustomResolver({ customResolver }, options) { + if (typeof customResolver === 'function') { + return customResolver; + } + if (customResolver && typeof customResolver.resolveId === 'function') { + return customResolver.resolveId; + } + if (typeof options.customResolver === 'function') { + return options.customResolver; + } + if (options.customResolver && typeof options.customResolver.resolveId === 'function') { + return options.customResolver.resolveId; + } + return null; +} +function alias(options = {}) { + const entries = getEntries(options); + if (entries.length === 0) { + return { + name: 'alias', + resolveId: noop + }; + } + return { + name: 'alias', + buildStart(inputOptions) { + return Promise.all([...entries, options].map(({ customResolver }) => customResolver && + typeof customResolver === 'object' && + typeof customResolver.buildStart === 'function' && + customResolver.buildStart.call(this, inputOptions))).then(() => { + // enforce void return value + }); + }, + resolveId(importee, importer) { + const importeeId = normalizeId(importee); + const importerId = normalizeId(importer); + // First match is supposed to be the correct one + const matchedEntry = entries.find((entry) => matches(entry.find, importeeId)); + if (!matchedEntry || !importerId) { + return null; + } + const updatedId = normalizeId(importeeId.replace(matchedEntry.find, matchedEntry.replacement)); + const customResolver = getCustomResolver(matchedEntry, options); + if (customResolver) { + return customResolver.call(this, updatedId, importerId, {}); + } + return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => { + let finalResult = resolved; + if (!finalResult) { + finalResult = { id: updatedId }; + } + return finalResult; + }); + } + }; +} + +/** + * https://github.com/rollup/plugins/blob/master/packages/json/src/index.js + * + * This source code is licensed under the MIT license found in the + * LICENSE file at + * https://github.com/rollup/plugins/blob/master/LICENSE + */ +// Custom json filter for vite +const jsonExtRE = /\.json($|\?)(?!commonjs-proxy)/; +function jsonPlugin(options = {}, isBuild) { + return { + name: 'vite:json', + transform(json, id) { + if (!jsonExtRE.test(id)) + return null; + if (SPECIAL_QUERY_RE.test(id)) + return null; + try { + if (options.stringify) { + if (isBuild) { + return { + // during build, parse then double-stringify to remove all + // unnecessary whitespaces to reduce bundle size. + code: `export default JSON.parse(${JSON.stringify(JSON.stringify(JSON.parse(json)))})`, + map: { mappings: '' } + }; + } + else { + return `export default JSON.parse(${JSON.stringify(json)})`; + } + } + const parsed = JSON.parse(json); + return { + code: dataToEsm(parsed, { + preferConst: true, + namedExports: options.namedExports + }), + map: { mappings: '' } + }; + } + catch (e) { + const errorMessageList = /[\d]+/.exec(e.message); + const position = errorMessageList && parseInt(errorMessageList[0], 10); + const msg = position + ? `, invalid JSON syntax found at line ${position}` + : `.`; + this.error(`Failed to parse JSON file` + msg, e.idx); + } + } + }; +} + +const isDebug = !!process.env.DEBUG; +const debugRewrite = createDebugger('vite:rewrite'); +const clientDir = normalizePath$4(CLIENT_DIR); +const skipRE = /\.(map|json)$/; +const canSkip = (id) => skipRE.test(id) || isDirectCSSRequest(id); +function isExplicitImportRequired(url) { + return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url); +} +function markExplicitImport(url) { + if (isExplicitImportRequired(url)) { + return injectQuery(url, 'import'); + } + return url; +} +/** + * Server-only plugin that lexes, resolves, rewrites and analyzes url imports. + * + * - Imports are resolved to ensure they exist on disk + * + * - Lexes HMR accept calls and updates import relationships in the module graph + * + * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to + * absolute file paths, e.g. + * + * ```js + * import 'foo' + * ``` + * is rewritten to + * ```js + * import '/@fs//project/node_modules/foo/dist/foo.js' + * ``` + * + * - CSS imports are appended with `.js` since both the js module and the actual + * css (referenced via ) may go through the transform pipeline: + * + * ```js + * import './style.css' + * ``` + * is rewritten to + * ```js + * import './style.css.js' + * ``` + */ +function importAnalysisPlugin(config) { + const { root, base } = config; + const clientPublicPath = path__default.posix.join(base, CLIENT_PUBLIC_PATH); + let server; + return { + name: 'vite:import-analysis', + configureServer(_server) { + server = _server; + }, + async transform(source$1, importer, ssr) { + const prettyImporter = prettifyUrl(importer, root); + if (canSkip(importer)) { + isDebug && debugRewrite(source.dim(`[skipped] ${prettyImporter}`)); + return null; + } + const rewriteStart = Date.now(); + await init; + let imports = []; + // strip UTF-8 BOM + if (source$1.charCodeAt(0) === 0xfeff) { + source$1 = source$1.slice(1); + } + try { + imports = parse$d(source$1)[0]; + } + catch (e) { + const isVue = importer.endsWith('.vue'); + const maybeJSX = !isVue && isJSRequest(importer); + const msg = isVue + ? `Install @vitejs/plugin-vue to handle .vue files.` + : maybeJSX + ? `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.` + : `You may need to install appropriate plugins to handle the ${path__default.extname(importer)} file format.`; + this.error(`Failed to parse source for import analysis because the content ` + + `contains invalid JS syntax. ` + + msg, e.idx); + } + if (!imports.length) { + isDebug && + debugRewrite(`${timeFrom(rewriteStart)} ${source.dim(`[no imports] ${prettyImporter}`)}`); + return source$1; + } + let hasHMR = false; + let isSelfAccepting = false; + let hasEnv = false; + let needQueryInjectHelper = false; + let s; + const str = () => s || (s = new MagicString(source$1)); + // vite-only server context + const { moduleGraph } = server; + // since we are already in the transform phase of the importer, it must + // have been loaded so its entry is guaranteed in the module graph. + const importerModule = moduleGraph.getModuleById(importer); + const importedUrls = new Set(); + const acceptedUrls = new Set(); + const toAbsoluteUrl = (url) => path__default.posix.resolve(path__default.posix.dirname(importerModule.url), url); + const normalizeUrl = async (url, pos) => { + if (base !== '/' && url.startsWith(base)) { + url = url.replace(base, '/'); + } + const resolved = await this.resolve(url, importer); + if (!resolved) { + this.error(`Failed to resolve import "${url}" from "${path__default.relative(process.cwd(), importer)}". Does the file exist?`, pos); + } + const isRelative = url.startsWith('.'); + // normalize all imports into resolved URLs + // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js` + if (resolved.id.startsWith(root + '/')) { + // in root: infer short absolute path from root + url = resolved.id.slice(root.length); + } + else if (fs__default.existsSync(cleanUrl(resolved.id))) { + // exists but out of root: rewrite to absolute /@fs/ paths + url = path__default.posix.join(FS_PREFIX + resolved.id); + } + else { + url = resolved.id; + } + if (isExternalUrl(url)) { + return [url, url]; + } + // if the resolved id is not a valid browser import specifier, + // prefix it to make it valid. We will strip this before feeding it + // back into the transform pipeline + if (!url.startsWith('.') && !url.startsWith('/')) { + url = + VALID_ID_PREFIX + resolved.id.replace('\0', NULL_BYTE_PLACEHOLDER); + } + // make the URL browser-valid if not SSR + if (!ssr) { + // mark non-js/css imports with `?import` + url = markExplicitImport(url); + // for relative js/css imports, inherit importer's version query + // do not do this for unknown type imports, otherwise the appended + // query can break 3rd party plugin's extension checks. + if (isRelative && !/[\?&]import=?\b/.test(url)) { + const versionMatch = importer.match(DEP_VERSION_RE); + if (versionMatch) { + url = injectQuery(url, versionMatch[1]); + } + } + // check if the dep has been hmr updated. If yes, we need to attach + // its last updated timestamp to force the browser to fetch the most + // up-to-date version of this module. + try { + const depModule = await moduleGraph.ensureEntryFromUrl(url); + if (depModule.lastHMRTimestamp > 0) { + url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`); + } + } + catch (e) { + // it's possible that the dep fails to resolve (non-existent import) + // attach location to the missing import + e.pos = pos; + throw e; + } + // prepend base (dev base is guaranteed to have ending slash) + url = base + url.replace(/^\//, ''); + } + return [url, resolved.id]; + }; + for (let index = 0; index < imports.length; index++) { + const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, + // #2083 User may use escape path, + // so use imports[index].n to get the unescaped string + // @ts-ignore + n: specifier } = imports[index]; + const rawUrl = source$1.slice(start, end); + // check import.meta usage + if (rawUrl === 'import.meta') { + const prop = source$1.slice(end, end + 4); + if (prop === '.hot') { + hasHMR = true; + if (source$1.slice(end + 4, end + 11) === '.accept') { + // further analyze accepted modules + if (lexAcceptedHmrDeps(source$1, source$1.indexOf('(', end + 11) + 1, acceptedUrls)) { + isSelfAccepting = true; + } + } + } + else if (prop === '.env') { + hasEnv = true; + } + else if (prop === '.glo' && source$1[end + 4] === 'b') { + // transform import.meta.glob() + // e.g. `import.meta.glob('glob:./dir/*.js')` + const { imports, importsString, exp, endIndex, base, pattern } = await transformImportGlob(source$1, start, importer, index, root, normalizeUrl); + str().prepend(importsString); + str().overwrite(expStart, endIndex, exp); + imports.forEach((url) => importedUrls.add(url.replace(base, '/'))); + if (!(importerModule.file in server._globImporters)) { + server._globImporters[importerModule.file] = { + module: importerModule, + importGlobs: [] + }; + } + server._globImporters[importerModule.file].importGlobs.push({ + base, + pattern + }); + } + continue; + } + const isDynamicImport = dynamicIndex >= 0; + // static import or valid string in dynamic import + // If resolvable, let's resolve it + if (specifier) { + // skip external / data uri + if (isExternalUrl(specifier) || isDataUrl(specifier)) { + continue; + } + // skip ssr external + if (ssr) { + if (server._ssrExternals && + shouldExternalizeForSSR(specifier, server._ssrExternals)) { + continue; + } + if (isBuiltin(specifier)) { + continue; + } + } + // skip client + if (specifier === clientPublicPath) { + continue; + } + // warn imports to non-asset /public files + if (specifier.startsWith('/') && + !config.assetsInclude(cleanUrl(specifier)) && + !specifier.endsWith('.json') && + checkPublicFile(specifier, config)) { + throw new Error(`Cannot import non-asset file ${specifier} which is inside /public.` + + `JS/CSS files inside /public are copied as-is on build and ` + + `can only be referenced via \n js += `\\nimport \"${id}?html-proxy&index=${inlineModuleIndex}.js\"`\n shouldRemove = true\n }\n }\n }\n\n // For asset references in index.html, also generate an import\n // statement for each - this will be handled by the asset plugin\n const assetAttrs = assetAttrsConfig[node.tag]\n if (assetAttrs) {\n for (const p of node.props) {\n if (\n p.type === NodeTypes.ATTRIBUTE &&\n p.value &&\n assetAttrs.includes(p.name)\n ) {\n const url = p.value.content\n if (!isExcludedUrl(url)) {\n if (node.tag === 'link' && isCSSRequest(url)) {\n // CSS references, convert to import\n js += `\\nimport ${JSON.stringify(url)}`\n shouldRemove = true\n } else {\n assetUrls.push(p)\n }\n } else if (checkPublicFile(url, config)) {\n s.overwrite(\n p.value.loc.start.offset,\n p.value.loc.end.offset,\n `\"${config.base + url.slice(1)}\"`\n )\n }\n }\n }\n }\n\n if (shouldRemove) {\n // remove the script tag from the html. we are going to inject new\n // ones in the end.\n s.remove(node.loc.start.offset, node.loc.end.offset)\n }\n })\n\n // for each encountered asset url, rewrite original html so that it\n // references the post-build location.\n for (const attr of assetUrls) {\n const value = attr.value!\n try {\n const url =\n attr.name === 'srcset'\n ? await processSrcSet(value.content, ({ url }) =>\n urlToBuiltUrl(url, id, config, this)\n )\n : await urlToBuiltUrl(value.content, id, config, this)\n\n s.overwrite(\n value.loc.start.offset,\n value.loc.end.offset,\n `\"${url}\"`\n )\n } catch (e) {\n // #1885 preload may be pointing to urls that do not exist\n // locally on disk\n if (e.code !== 'ENOENT') {\n throw e\n }\n }\n }\n\n processedHtml.set(id, s.toString())\n\n // inject module preload polyfill\n if (config.build.polyfillModulePreload) {\n js = `import \"${modulePreloadPolyfillId}\";\\n${js}`\n }\n\n return js\n }\n },\n\n async generateBundle(_, bundle) {\n const analyzedChunk: Map = new Map()\n const getPreloadLinksForChunk = (\n chunk: OutputChunk,\n seen: Set = new Set()\n ): HtmlTagDescriptor[] => {\n const tags: HtmlTagDescriptor[] = []\n chunk.imports.forEach((file) => {\n const importee = bundle[file]\n if (importee?.type === 'chunk' && !seen.has(file)) {\n seen.add(file)\n tags.push({\n tag: 'link',\n attrs: {\n rel: 'modulepreload',\n href: toPublicPath(file, config)\n }\n })\n tags.push(...getPreloadLinksForChunk(importee, seen))\n }\n })\n return tags\n }\n\n const getCssTagsForChunk = (\n chunk: OutputChunk,\n seen: Set = new Set()\n ): HtmlTagDescriptor[] => {\n const tags: HtmlTagDescriptor[] = []\n if (!analyzedChunk.has(chunk)) {\n analyzedChunk.set(chunk, 1)\n chunk.imports.forEach((file) => {\n const importee = bundle[file]\n if (importee?.type === 'chunk') {\n tags.push(...getCssTagsForChunk(importee, seen))\n }\n })\n }\n\n const cssFiles = chunkToEmittedCssFileMap.get(chunk)\n if (cssFiles) {\n cssFiles.forEach((file) => {\n if (!seen.has(file)) {\n seen.add(file)\n tags.push({\n tag: 'link',\n attrs: {\n rel: 'stylesheet',\n href: toPublicPath(file, config)\n }\n })\n }\n })\n }\n return tags\n }\n\n for (const [id, html] of processedHtml) {\n // resolve asset url references\n let result = html.replace(assetUrlRE, (_, fileHash, postfix = '') => {\n return config.base + getAssetFilename(fileHash, config) + postfix\n })\n\n // find corresponding entry chunk\n const chunk = Object.values(bundle).find(\n (chunk) =>\n chunk.type === 'chunk' &&\n chunk.isEntry &&\n chunk.facadeModuleId === id\n ) as OutputChunk | undefined\n\n // inject chunk asset links\n if (chunk) {\n const assetTags = [\n // js entry chunk for this page\n {\n tag: 'script',\n attrs: {\n type: 'module',\n crossorigin: true,\n src: toPublicPath(chunk.fileName, config)\n }\n },\n // preload for imports\n ...getPreloadLinksForChunk(chunk),\n ...getCssTagsForChunk(chunk)\n ]\n\n result = injectToHead(result, assetTags)\n }\n\n // inject css link when cssCodeSplit is false\n if (!config.build.cssCodeSplit) {\n const cssChunk = Object.values(bundle).find(\n (chunk) => chunk.type === 'asset' && chunk.name === 'style.css'\n ) as OutputAsset | undefined\n if (cssChunk) {\n result = injectToHead(result, [\n {\n tag: 'link',\n attrs: {\n rel: 'stylesheet',\n href: toPublicPath(cssChunk.fileName, config)\n }\n }\n ])\n }\n }\n\n const shortEmitName = path.posix.relative(config.root, id)\n result = await applyHtmlTransforms(result, postHooks, {\n path: '/' + shortEmitName,\n filename: id,\n bundle,\n chunk\n })\n\n this.emitFile({\n type: 'asset',\n fileName: shortEmitName,\n source: result\n })\n }\n }\n }\n}\n\nexport interface HtmlTagDescriptor {\n tag: string\n attrs?: Record\n children?: string | HtmlTagDescriptor[]\n /**\n * default: 'head-prepend'\n */\n injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend'\n}\n\nexport type IndexHtmlTransformResult =\n | string\n | HtmlTagDescriptor[]\n | {\n html: string\n tags: HtmlTagDescriptor[]\n }\n\nexport interface IndexHtmlTransformContext {\n /**\n * public path when served\n */\n path: string\n /**\n * filename on disk\n */\n filename: string\n server?: ViteDevServer\n bundle?: OutputBundle\n chunk?: OutputChunk\n originalUrl?: string\n}\n\nexport type IndexHtmlTransformHook = (\n html: string,\n ctx: IndexHtmlTransformContext\n) => IndexHtmlTransformResult | void | Promise\n\nexport type IndexHtmlTransform =\n | IndexHtmlTransformHook\n | {\n enforce?: 'pre' | 'post'\n transform: IndexHtmlTransformHook\n }\n\nexport function resolveHtmlTransforms(\n plugins: readonly Plugin[]\n): [IndexHtmlTransformHook[], IndexHtmlTransformHook[]] {\n const preHooks: IndexHtmlTransformHook[] = []\n const postHooks: IndexHtmlTransformHook[] = []\n\n for (const plugin of plugins) {\n const hook = plugin.transformIndexHtml\n if (hook) {\n if (typeof hook === 'function') {\n postHooks.push(hook)\n } else if (hook.enforce === 'pre') {\n preHooks.push(hook.transform)\n } else {\n postHooks.push(hook.transform)\n }\n }\n }\n\n return [preHooks, postHooks]\n}\n\nexport async function applyHtmlTransforms(\n html: string,\n hooks: IndexHtmlTransformHook[],\n ctx: IndexHtmlTransformContext\n): Promise {\n const headTags: HtmlTagDescriptor[] = []\n const headPrependTags: HtmlTagDescriptor[] = []\n const bodyTags: HtmlTagDescriptor[] = []\n const bodyPrependTags: HtmlTagDescriptor[] = []\n\n for (const hook of hooks) {\n const res = await hook(html, ctx)\n if (!res) {\n continue\n }\n if (typeof res === 'string') {\n html = res\n } else {\n let tags: HtmlTagDescriptor[]\n if (Array.isArray(res)) {\n tags = res\n } else {\n html = res.html || html\n tags = res.tags\n }\n for (const tag of tags) {\n if (tag.injectTo === 'body') {\n bodyTags.push(tag)\n } else if (tag.injectTo === 'body-prepend') {\n bodyPrependTags.push(tag)\n } else if (tag.injectTo === 'head') {\n headTags.push(tag)\n } else {\n headPrependTags.push(tag)\n }\n }\n }\n }\n\n // inject tags\n if (headPrependTags.length) {\n html = injectToHead(html, headPrependTags, true)\n }\n if (headTags.length) {\n html = injectToHead(html, headTags)\n }\n if (bodyPrependTags.length) {\n html = injectToBody(html, bodyPrependTags, true)\n }\n if (bodyTags.length) {\n html = injectToBody(html, bodyTags)\n }\n\n return html\n}\n\nfunction toPublicPath(filename: string, config: ResolvedConfig) {\n return isExternalUrl(filename) ? filename : config.base + filename\n}\n\nconst headInjectRE = /<\\/head>/\nconst headPrependInjectRE = [//, //i]\nfunction injectToHead(\n html: string,\n tags: HtmlTagDescriptor[],\n prepend = false\n) {\n const tagsHtml = serializeTags(tags)\n if (prepend) {\n // inject after head or doctype\n for (const re of headPrependInjectRE) {\n if (re.test(html)) {\n return html.replace(re, `$&\\n${tagsHtml}`)\n }\n }\n } else {\n // inject before head close\n if (headInjectRE.test(html)) {\n return html.replace(headInjectRE, `${tagsHtml}\\n $&`)\n }\n }\n // if no tag is present, just prepend\n return tagsHtml + `\\n` + html\n}\n\nconst bodyInjectRE = /<\\/body>/\nconst bodyPrependInjectRE = /]*>/\nfunction injectToBody(\n html: string,\n tags: HtmlTagDescriptor[],\n prepend = false\n) {\n if (prepend) {\n // inject after body open\n const tagsHtml = `\\n` + serializeTags(tags)\n if (bodyPrependInjectRE.test(html)) {\n return html.replace(bodyPrependInjectRE, `$&\\n${tagsHtml}`)\n }\n // if no body, prepend\n return tagsHtml + `\\n` + html\n } else {\n // inject before body close\n const tagsHtml = `\\n` + serializeTags(tags)\n if (bodyInjectRE.test(html)) {\n return html.replace(bodyInjectRE, `${tagsHtml}\\n$&`)\n }\n // if no body, append\n return html + `\\n` + tagsHtml\n }\n}\n\nconst unaryTags = new Set(['link', 'meta', 'base'])\n\nfunction serializeTag({ tag, attrs, children }: HtmlTagDescriptor): string {\n if (unaryTags.has(tag)) {\n return `<${tag}${serializeAttrs(attrs)}>`\n } else {\n return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children)}`\n }\n}\n\nfunction serializeTags(tags: HtmlTagDescriptor['children']): string {\n if (typeof tags === 'string') {\n return tags\n } else if (tags) {\n return ` ${tags.map(serializeTag).join('\\n ')}`\n }\n return ''\n}\n\nfunction serializeAttrs(attrs: HtmlTagDescriptor['attrs']): string {\n let res = ''\n for (const key in attrs) {\n if (typeof attrs[key] === 'boolean') {\n res += attrs[key] ? ` ${key}` : ``\n } else {\n res += ` ${key}=${JSON.stringify(attrs[key])}`\n }\n }\n return res\n}\n","'use strict';\n\nmodule.exports = string => {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError(`Expected a string, got ${typeof string}`);\n\t}\n\n\t// Catches EFBBBF (UTF-8 BOM) because the buffer-to-string\n\t// conversion translates it to FEFF (UTF-16 BOM)\n\tif (string.charCodeAt(0) === 0xFEFF) {\n\t\treturn string.slice(1);\n\t}\n\n\treturn string;\n};\n","'use strict';\nconst singleComment = Symbol('singleComment');\nconst multiComment = Symbol('multiComment');\nconst stripWithoutWhitespace = () => '';\nconst stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\\S/g, ' ');\n\nconst isEscaped = (jsonString, quotePosition) => {\n\tlet index = quotePosition - 1;\n\tlet backslashCount = 0;\n\n\twhile (jsonString[index] === '\\\\') {\n\t\tindex -= 1;\n\t\tbackslashCount += 1;\n\t}\n\n\treturn Boolean(backslashCount % 2);\n};\n\nmodule.exports = (jsonString, options = {}) => {\n\tif (typeof jsonString !== 'string') {\n\t\tthrow new TypeError(`Expected argument \\`jsonString\\` to be a \\`string\\`, got \\`${typeof jsonString}\\``);\n\t}\n\n\tconst strip = options.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;\n\n\tlet insideString = false;\n\tlet insideComment = false;\n\tlet offset = 0;\n\tlet result = '';\n\n\tfor (let i = 0; i < jsonString.length; i++) {\n\t\tconst currentCharacter = jsonString[i];\n\t\tconst nextCharacter = jsonString[i + 1];\n\n\t\tif (!insideComment && currentCharacter === '\"') {\n\t\t\tconst escaped = isEscaped(jsonString, i);\n\t\t\tif (!escaped) {\n\t\t\t\tinsideString = !insideString;\n\t\t\t}\n\t\t}\n\n\t\tif (insideString) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!insideComment && currentCharacter + nextCharacter === '//') {\n\t\t\tresult += jsonString.slice(offset, i);\n\t\t\toffset = i;\n\t\t\tinsideComment = singleComment;\n\t\t\ti++;\n\t\t} else if (insideComment === singleComment && currentCharacter + nextCharacter === '\\r\\n') {\n\t\t\ti++;\n\t\t\tinsideComment = false;\n\t\t\tresult += strip(jsonString, offset, i);\n\t\t\toffset = i;\n\t\t\tcontinue;\n\t\t} else if (insideComment === singleComment && currentCharacter === '\\n') {\n\t\t\tinsideComment = false;\n\t\t\tresult += strip(jsonString, offset, i);\n\t\t\toffset = i;\n\t\t} else if (!insideComment && currentCharacter + nextCharacter === '/*') {\n\t\t\tresult += jsonString.slice(offset, i);\n\t\t\toffset = i;\n\t\t\tinsideComment = multiComment;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t} else if (insideComment === multiComment && currentCharacter + nextCharacter === '*/') {\n\t\t\ti++;\n\t\t\tinsideComment = false;\n\t\t\tresult += strip(jsonString, offset, i + 1);\n\t\t\toffset = i + 1;\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\treturn result + (insideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));\n};\n","import fs from 'fs'\nimport path from 'path'\nimport chalk from 'chalk'\nimport { Plugin } from '../plugin'\nimport {\n transform,\n Message,\n Loader,\n TransformOptions,\n TransformResult\n} from 'esbuild'\nimport { cleanUrl, createDebugger, generateCodeFrame } from '../utils'\nimport { RawSourceMap } from '@ampproject/remapping/dist/types/types'\nimport { SourceMap } from 'rollup'\nimport { ResolvedConfig } from '..'\nimport { createFilter } from '@rollup/pluginutils'\nimport { combineSourcemaps } from '../utils'\nimport stripBom from 'strip-bom'\nimport stripComments from 'strip-json-comments'\nimport { createRequire } from 'module'\n\nconst debug = createDebugger('vite:esbuild')\n\nexport interface ESBuildOptions extends TransformOptions {\n include?: string | RegExp | string[] | RegExp[]\n exclude?: string | RegExp | string[] | RegExp[]\n jsxInject?: string\n}\n\nexport type ESBuildTransformResult = Omit & {\n map: SourceMap\n}\n\ntype TSConfigJSON = {\n extends?: string\n compilerOptions?: {\n target?: string\n jsxFactory?: string\n jsxFragmentFactory?: string\n useDefineForClassFields?: boolean\n importsNotUsedAsValues?: 'remove' | 'preserve' | 'error'\n }\n [key: string]: any\n}\ntype TSCompilerOptions = NonNullable\n\nexport async function transformWithEsbuild(\n code: string,\n filename: string,\n options?: TransformOptions,\n inMap?: object\n): Promise {\n // if the id ends with a valid ext, use it (e.g. vue blocks)\n // otherwise, cleanup the query before checking the ext\n const ext = path.extname(\n /\\.\\w+$/.test(filename) ? filename : cleanUrl(filename)\n )\n\n let loader = ext.slice(1)\n if (loader === 'cjs' || loader === 'mjs') {\n loader = 'js'\n }\n\n // these fields would affect the compilation result\n // https://esbuild.github.io/content-types/#tsconfig-json\n const meaningfulFields: Array = [\n 'jsxFactory',\n 'jsxFragmentFactory',\n 'useDefineForClassFields',\n 'importsNotUsedAsValues'\n ]\n const compilerOptionsForFile: TSCompilerOptions = {}\n if (loader === 'ts' || loader === 'tsx') {\n const loadedTsconfig = await loadTsconfigJsonForFile(filename)\n const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {}\n\n for (const field of meaningfulFields) {\n if (field in loadedCompilerOptions) {\n // @ts-ignore TypeScript can't tell they are of the same type\n compilerOptionsForFile[field] = loadedCompilerOptions[field]\n }\n }\n\n // align with TypeScript 4.3\n // https://github.com/microsoft/TypeScript/pull/42663\n if (loadedCompilerOptions.target?.toLowerCase() === 'esnext') {\n compilerOptionsForFile.useDefineForClassFields =\n loadedCompilerOptions.useDefineForClassFields ?? true\n }\n }\n\n const resolvedOptions = {\n loader: loader as Loader,\n sourcemap: true,\n // ensure source file name contains full query\n sourcefile: filename,\n tsconfigRaw: { compilerOptions: compilerOptionsForFile },\n ...options\n } as ESBuildOptions\n\n delete resolvedOptions.include\n delete resolvedOptions.exclude\n delete resolvedOptions.jsxInject\n\n try {\n const result = await transform(code, resolvedOptions)\n if (inMap) {\n const nextMap = JSON.parse(result.map)\n nextMap.sourcesContent = []\n return {\n ...result,\n map: combineSourcemaps(filename, [\n nextMap as RawSourceMap,\n inMap as RawSourceMap\n ]) as SourceMap\n }\n } else {\n return {\n ...result,\n map: JSON.parse(result.map)\n }\n }\n } catch (e) {\n debug(`esbuild error with options used: `, resolvedOptions)\n // patch error information\n if (e.errors) {\n e.frame = ''\n e.errors.forEach((m: Message) => {\n e.frame += `\\n` + prettifyMessage(m, code)\n })\n e.loc = e.errors[0].location\n }\n throw e\n }\n}\n\nexport function esbuildPlugin(options: ESBuildOptions = {}): Plugin {\n const filter = createFilter(\n options.include || /\\.(tsx?|jsx)$/,\n options.exclude || /\\.js$/\n )\n\n return {\n name: 'vite:esbuild',\n async transform(code, id) {\n if (filter(id) || filter(cleanUrl(id))) {\n const result = await transformWithEsbuild(code, id, options)\n if (result.warnings.length) {\n result.warnings.forEach((m) => {\n this.warn(prettifyMessage(m, code))\n })\n }\n if (options.jsxInject && /\\.(?:j|t)sx\\b/.test(id)) {\n result.code = options.jsxInject + ';' + result.code\n }\n return {\n code: result.code,\n map: result.map\n }\n }\n }\n }\n}\n\nexport const buildEsbuildPlugin = (config: ResolvedConfig): Plugin => {\n return {\n name: 'vite:esbuild-transpile',\n async renderChunk(code, chunk, opts) {\n // @ts-ignore injected by @vitejs/plugin-legacy\n if (opts.__vite_skip_esbuild__) {\n return null\n }\n\n const target = config.build.target\n const minify = config.build.minify === 'esbuild'\n if ((!target || target === 'esnext') && !minify) {\n return null\n }\n return transformWithEsbuild(code, chunk.fileName, {\n target: target || undefined,\n minify\n })\n }\n }\n}\n\nfunction prettifyMessage(m: Message, code: string): string {\n let res = chalk.yellow(m.text)\n if (m.location) {\n const lines = code.split(/\\r?\\n/g)\n const line = Number(m.location.line)\n const column = Number(m.location.column)\n const offset =\n lines\n .slice(0, line - 1)\n .map((l) => l.length)\n .reduce((total, l) => total + l + 1, 0) + column\n res += `\\n` + generateCodeFrame(code, offset, offset + 1)\n }\n return res + `\\n`\n}\n\n// modified from \n\n/**\n * Copyright (c) 2015 TypeStrong\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nasync function findTSConfig(dir: string): Promise {\n const configFile = path.resolve(dir, 'tsconfig.json')\n\n const stats = await stat(configFile)\n if (isFile(stats)) {\n return configFile\n }\n\n const parentDir = path.dirname(dir)\n\n if (dir === parentDir) {\n return\n }\n\n return findTSConfig(parentDir)\n}\n\n/**\n * Check if a file exists.\n */\nfunction stat(filename: string): Promise {\n return new Promise((resolve, reject) => {\n fs.stat(filename, (err, stats) => {\n return err ? resolve() : resolve(stats)\n })\n })\n}\n\n/**\n * Check filesystem stat is a directory.\n */\nfunction isFile(stats: fs.Stats | void) {\n return stats ? stats.isFile() || stats.isFIFO() : false\n}\n\n// from \n// by @dominikg\n\n/**\n * replace dangling commas from pseudo-json string with single space\n *\n * limitations:\n * - pseudo-json must not contain comments, use strip-json-comments before\n * - only a single dangling comma before } or ] is removed\n * stripDanglingComma('[1,2,]') === '[1,2 ]\n * stripDanglingComma('[1,2,,]') === '[1,2, ]\n *\n * implementation heavily inspired by strip-json-comments\n */\nfunction stripDanglingComma(jsonString: string) {\n /**\n * Check if char at qoutePosition is escaped by an odd number of backslashes preceding it\n */\n function isEscaped(jsonString: string, quotePosition: number) {\n let index = quotePosition - 1\n let backslashCount = 0\n\n while (jsonString[index] === '\\\\') {\n index -= 1\n backslashCount += 1\n }\n\n return backslashCount % 2 === 1\n }\n\n let insideString = false\n let offset = 0\n let result = ''\n let danglingCommaPos = null\n for (let i = 0; i < jsonString.length; i++) {\n const currentCharacter = jsonString[i]\n\n if (currentCharacter === '\"') {\n const escaped = isEscaped(jsonString, i)\n if (!escaped) {\n insideString = !insideString\n }\n }\n\n if (insideString) {\n danglingCommaPos = null\n continue\n }\n if (currentCharacter === ',') {\n danglingCommaPos = i\n continue\n }\n if (danglingCommaPos) {\n if (currentCharacter === '}' || currentCharacter === ']') {\n result += jsonString.slice(offset, danglingCommaPos) + ' '\n offset = danglingCommaPos + 1\n danglingCommaPos = null\n } else if (!currentCharacter.match(/\\s/)) {\n danglingCommaPos = null\n }\n }\n }\n\n return result + jsonString.substring(offset)\n}\n\nasync function readTSConfig(configPath: string): Promise {\n const content: string = await new Promise((resolve, reject) => {\n fs.readFile(configPath, 'utf-8', (err, data) => {\n if (err) {\n reject(err)\n return\n }\n resolve(stripComments(stripBom(data)))\n })\n })\n\n // tsconfig.json can be empty\n if (/^\\s*$/.test(content)) {\n return {}\n }\n\n return JSON.parse(stripDanglingComma(content)) as TSConfigJSON\n}\n\nconst tsconfigCache = new Map()\nasync function loadTsconfigJsonForFile(\n filename: string\n): Promise {\n const directory = path.dirname(filename)\n\n const cached = tsconfigCache.get(directory)\n if (cached) {\n return cached\n }\n\n let configPath = await findTSConfig(directory)\n let tsconfig: TSConfigJSON = {}\n\n if (configPath) {\n const visited = new Set()\n visited.add(configPath)\n\n tsconfig = await readTSConfig(configPath)\n while (tsconfig.extends) {\n const configRequire = createRequire(configPath)\n\n const extendsPath = configRequire.resolve(tsconfig.extends)\n const extendedConfig = await readTSConfig(extendsPath)\n\n if (visited.has(extendsPath)) {\n throw new Error(\n `Circular dependency detected in the \"extends\" field of ${configPath}`\n )\n }\n visited.add(extendsPath)\n\n tsconfig = {\n extends: extendedConfig.extends,\n compilerOptions: {\n ...extendedConfig.compilerOptions,\n ...tsconfig.compilerOptions\n }\n }\n configPath = extendsPath\n }\n }\n\n tsconfigCache.set(directory, tsconfig)\n return tsconfig\n}\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Worker = void 0;\nconst os_1 = __importDefault(require(\"os\"));\nconst worker_threads_1 = require(\"worker_threads\");\nclass Worker {\n constructor(fn, options = {}) {\n this.code = genWorkerCode(fn);\n this.max = options.max || Math.max(1, os_1.default.cpus().length - 1);\n this.pool = [];\n this.idlePool = [];\n this.queue = [];\n }\n async run(...args) {\n const worker = await this._getAvailableWorker();\n return new Promise((resolve, reject) => {\n worker.currentResolve = resolve;\n worker.currentReject = reject;\n worker.postMessage(args);\n });\n }\n stop() {\n this.pool.forEach((w) => w.unref());\n this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.')));\n this.pool = [];\n this.idlePool = [];\n this.queue = [];\n }\n async _getAvailableWorker() {\n // has idle one?\n if (this.idlePool.length) {\n return this.idlePool.shift();\n }\n // can spawn more?\n if (this.pool.length < this.max) {\n const worker = new worker_threads_1.Worker(this.code, { eval: true });\n worker.on('message', (res) => {\n worker.currentResolve && worker.currentResolve(res);\n worker.currentResolve = null;\n this._assignDoneWorker(worker);\n });\n worker.on('error', (err) => {\n worker.currentReject && worker.currentReject(err);\n worker.currentReject = null;\n });\n worker.on('exit', (code) => {\n const i = this.pool.indexOf(worker);\n if (i > -1)\n this.pool.splice(i, 1);\n if (code !== 0 && worker.currentReject) {\n worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`));\n worker.currentReject = null;\n }\n });\n this.pool.push(worker);\n return worker;\n }\n // no one is available, we have to wait\n let resolve;\n let reject;\n const onWorkerAvailablePromise = new Promise((r, rj) => {\n resolve = r;\n reject = rj;\n });\n this.queue.push([resolve, reject]);\n return onWorkerAvailablePromise;\n }\n _assignDoneWorker(worker) {\n // someone's waiting already?\n if (this.queue.length) {\n const [resolve] = this.queue.shift();\n resolve(worker);\n return;\n }\n // take a rest.\n this.idlePool.push(worker);\n }\n}\nexports.Worker = Worker;\nfunction genWorkerCode(fn) {\n return `\nconst doWork = ${fn.toString()}\n\nconst { parentPort } = require('worker_threads')\n\nparentPort.on('message', async (args) => {\n const res = await doWork(...args)\n parentPort.postMessage(res)\n})\n `;\n}\n","import { Plugin } from '../plugin'\nimport { Worker } from 'okie'\nimport { Terser } from 'types/terser'\n\nexport function terserPlugin(options: Terser.MinifyOptions): Plugin {\n const worker = new Worker(\n (basedir: string, code: string, options: Terser.MinifyOptions) => {\n // when vite is linked, the worker thread won't share the same resolve\n // root with vite itself, so we have to pass in the basedir and resolve\n // terser first.\n // eslint-disable-next-line node/no-restricted-require\n const terserPath = require.resolve('terser', {\n paths: [basedir]\n })\n return require(terserPath).minify(code, options) as Terser.MinifyOutput\n }\n )\n\n return {\n name: 'vite:terser',\n\n async renderChunk(code, _chunk, outputOptions) {\n const res = await worker.run(__dirname, code, {\n safari10: true,\n ...options,\n sourceMap: !!outputOptions.sourcemap,\n module: outputOptions.format.startsWith('es'),\n toplevel: outputOptions.format === 'cjs'\n })\n return {\n code: res.code!,\n map: res.map as any\n }\n },\n\n closeBundle() {\n worker.stop()\n }\n }\n}\n","import path from 'path'\nimport { OutputChunk } from 'rollup'\nimport { ResolvedConfig } from '..'\nimport { Plugin } from '../plugin'\nimport { chunkToEmittedCssFileMap } from './css'\nimport { chunkToEmittedAssetsMap } from './asset'\nimport { normalizePath } from '../utils'\n\nexport type Manifest = Record\n\nexport interface ManifestChunk {\n src?: string\n file: string\n css?: string[]\n assets?: string[]\n isEntry?: boolean\n isDynamicEntry?: boolean\n imports?: string[]\n dynamicImports?: string[]\n}\n\nexport function manifestPlugin(config: ResolvedConfig): Plugin {\n const manifest: Manifest = {}\n\n let outputCount: number\n\n return {\n name: 'vite:manifest',\n\n buildStart() {\n outputCount = 0\n },\n\n generateBundle({ format }, bundle) {\n function getChunkName(chunk: OutputChunk) {\n if (chunk.facadeModuleId) {\n let name = normalizePath(\n path.relative(config.root, chunk.facadeModuleId)\n )\n if (format === 'system' && !chunk.name.includes('-legacy')) {\n const ext = path.extname(name)\n name = name.slice(0, -ext.length) + `-legacy` + ext\n }\n return name\n } else {\n return `_` + path.basename(chunk.fileName)\n }\n }\n\n function getInternalImports(imports: string[]): string[] {\n const filteredImports: string[] = []\n\n for (const file of imports) {\n if (bundle[file] === undefined) {\n continue\n }\n\n filteredImports.push(getChunkName(bundle[file] as OutputChunk))\n }\n\n return filteredImports\n }\n\n function createChunk(chunk: OutputChunk): ManifestChunk {\n const manifestChunk: ManifestChunk = {\n file: chunk.fileName\n }\n\n if (chunk.facadeModuleId) {\n manifestChunk.src = getChunkName(chunk)\n }\n if (chunk.isEntry) {\n manifestChunk.isEntry = true\n }\n if (chunk.isDynamicEntry) {\n manifestChunk.isDynamicEntry = true\n }\n\n if (chunk.imports.length) {\n const internalImports = getInternalImports(chunk.imports)\n if (internalImports.length > 0) {\n manifestChunk.imports = internalImports\n }\n }\n\n if (chunk.dynamicImports.length) {\n const internalImports = getInternalImports(chunk.dynamicImports)\n if (internalImports.length > 0) {\n manifestChunk.dynamicImports = internalImports\n }\n }\n\n const cssFiles = chunkToEmittedCssFileMap.get(chunk)\n if (cssFiles) {\n manifestChunk.css = [...cssFiles]\n }\n\n const assets = chunkToEmittedAssetsMap.get(chunk)\n if (assets) [(manifestChunk.assets = [...assets])]\n\n return manifestChunk\n }\n\n for (const file in bundle) {\n const chunk = bundle[file]\n if (chunk.type === 'chunk') {\n manifest[getChunkName(chunk)] = createChunk(chunk)\n }\n }\n\n outputCount++\n const output = config.build.rollupOptions?.output\n const outputLength = Array.isArray(output) ? output.length : 1\n if (outputCount >= outputLength) {\n this.emitFile({\n fileName: `manifest.json`,\n type: 'asset',\n source: JSON.stringify(manifest, null, 2)\n })\n }\n }\n }\n}\n","import { extname, sep, resolve, posix } from 'path';\nimport pm from 'picomatch';\n\nconst addExtension = function addExtension(filename, ext = '.js') {\n let result = `${filename}`;\n if (!extname(filename))\n result += ext;\n return result;\n};\n\nfunction walk(ast, { enter, leave }) {\n\treturn visit(ast, null, enter, leave);\n}\n\nlet should_skip = false;\nlet should_remove = false;\nlet replacement = null;\nconst context = {\n\tskip: () => should_skip = true,\n\tremove: () => should_remove = true,\n\treplace: (node) => replacement = node\n};\n\nfunction replace(parent, prop, index, node) {\n\tif (parent) {\n\t\tif (index !== null) {\n\t\t\tparent[prop][index] = node;\n\t\t} else {\n\t\t\tparent[prop] = node;\n\t\t}\n\t}\n}\n\nfunction remove(parent, prop, index) {\n\tif (parent) {\n\t\tif (index !== null) {\n\t\t\tparent[prop].splice(index, 1);\n\t\t} else {\n\t\t\tdelete parent[prop];\n\t\t}\n\t}\n}\n\nfunction visit(\n\tnode,\n\tparent,\n\tenter,\n\tleave,\n\tprop,\n\tindex\n) {\n\tif (node) {\n\t\tif (enter) {\n\t\t\tconst _should_skip = should_skip;\n\t\t\tconst _should_remove = should_remove;\n\t\t\tconst _replacement = replacement;\n\t\t\tshould_skip = false;\n\t\t\tshould_remove = false;\n\t\t\treplacement = null;\n\n\t\t\tenter.call(context, node, parent, prop, index);\n\n\t\t\tif (replacement) {\n\t\t\t\tnode = replacement;\n\t\t\t\treplace(parent, prop, index, node);\n\t\t\t}\n\n\t\t\tif (should_remove) {\n\t\t\t\tremove(parent, prop, index);\n\t\t\t}\n\n\t\t\tconst skipped = should_skip;\n\t\t\tconst removed = should_remove;\n\n\t\t\tshould_skip = _should_skip;\n\t\t\tshould_remove = _should_remove;\n\t\t\treplacement = _replacement;\n\n\t\t\tif (skipped) return node;\n\t\t\tif (removed) return null;\n\t\t}\n\n\t\tfor (const key in node) {\n\t\t\tconst value = (node )[key];\n\n\t\t\tif (typeof value !== 'object') {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\telse if (Array.isArray(value)) {\n\t\t\t\tfor (let j = 0, k = 0; j < value.length; j += 1, k += 1) {\n\t\t\t\t\tif (value[j] !== null && typeof value[j].type === 'string') {\n\t\t\t\t\t\tif (!visit(value[j], node, enter, leave, key, k)) {\n\t\t\t\t\t\t\t// removed\n\t\t\t\t\t\t\tj--;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\telse if (value !== null && typeof value.type === 'string') {\n\t\t\t\tvisit(value, node, enter, leave, key, null);\n\t\t\t}\n\t\t}\n\n\t\tif (leave) {\n\t\t\tconst _replacement = replacement;\n\t\t\tconst _should_remove = should_remove;\n\t\t\treplacement = null;\n\t\t\tshould_remove = false;\n\n\t\t\tleave.call(context, node, parent, prop, index);\n\n\t\t\tif (replacement) {\n\t\t\t\tnode = replacement;\n\t\t\t\treplace(parent, prop, index, node);\n\t\t\t}\n\n\t\t\tif (should_remove) {\n\t\t\t\tremove(parent, prop, index);\n\t\t\t}\n\n\t\t\tconst removed = should_remove;\n\n\t\t\treplacement = _replacement;\n\t\t\tshould_remove = _should_remove;\n\n\t\t\tif (removed) return null;\n\t\t}\n\t}\n\n\treturn node;\n}\n\nconst extractors = {\n ArrayPattern(names, param) {\n for (const element of param.elements) {\n if (element)\n extractors[element.type](names, element);\n }\n },\n AssignmentPattern(names, param) {\n extractors[param.left.type](names, param.left);\n },\n Identifier(names, param) {\n names.push(param.name);\n },\n MemberExpression() { },\n ObjectPattern(names, param) {\n for (const prop of param.properties) {\n // @ts-ignore Typescript reports that this is not a valid type\n if (prop.type === 'RestElement') {\n extractors.RestElement(names, prop);\n }\n else {\n extractors[prop.value.type](names, prop.value);\n }\n }\n },\n RestElement(names, param) {\n extractors[param.argument.type](names, param.argument);\n }\n};\nconst extractAssignedNames = function extractAssignedNames(param) {\n const names = [];\n extractors[param.type](names, param);\n return names;\n};\n\nconst blockDeclarations = {\n const: true,\n let: true\n};\nclass Scope {\n constructor(options = {}) {\n this.parent = options.parent;\n this.isBlockScope = !!options.block;\n this.declarations = Object.create(null);\n if (options.params) {\n options.params.forEach((param) => {\n extractAssignedNames(param).forEach((name) => {\n this.declarations[name] = true;\n });\n });\n }\n }\n addDeclaration(node, isBlockDeclaration, isVar) {\n if (!isBlockDeclaration && this.isBlockScope) {\n // it's a `var` or function node, and this\n // is a block scope, so we need to go up\n this.parent.addDeclaration(node, isBlockDeclaration, isVar);\n }\n else if (node.id) {\n extractAssignedNames(node.id).forEach((name) => {\n this.declarations[name] = true;\n });\n }\n }\n contains(name) {\n return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);\n }\n}\nconst attachScopes = function attachScopes(ast, propertyName = 'scope') {\n let scope = new Scope();\n walk(ast, {\n enter(n, parent) {\n const node = n;\n // function foo () {...}\n // class Foo {...}\n if (/(Function|Class)Declaration/.test(node.type)) {\n scope.addDeclaration(node, false, false);\n }\n // var foo = 1\n if (node.type === 'VariableDeclaration') {\n const { kind } = node;\n const isBlockDeclaration = blockDeclarations[kind];\n // don't add const/let declarations in the body of a for loop #113\n const parentType = parent ? parent.type : '';\n if (!(isBlockDeclaration && /ForOfStatement/.test(parentType))) {\n node.declarations.forEach((declaration) => {\n scope.addDeclaration(declaration, isBlockDeclaration, true);\n });\n }\n }\n let newScope;\n // create new function scope\n if (/Function/.test(node.type)) {\n const func = node;\n newScope = new Scope({\n parent: scope,\n block: false,\n params: func.params\n });\n // named function expressions - the name is considered\n // part of the function's scope\n if (func.type === 'FunctionExpression' && func.id) {\n newScope.addDeclaration(func, false, false);\n }\n }\n // create new block scope\n if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {\n newScope = new Scope({\n parent: scope,\n block: true\n });\n }\n // catch clause has its own block scope\n if (node.type === 'CatchClause') {\n newScope = new Scope({\n parent: scope,\n params: node.param ? [node.param] : [],\n block: true\n });\n }\n if (newScope) {\n Object.defineProperty(node, propertyName, {\n value: newScope,\n configurable: true\n });\n scope = newScope;\n }\n },\n leave(n) {\n const node = n;\n if (node[propertyName])\n scope = scope.parent;\n }\n });\n return scope;\n};\n\n// Helper since Typescript can't detect readonly arrays with Array.isArray\nfunction isArray(arg) {\n return Array.isArray(arg);\n}\nfunction ensureArray(thing) {\n if (isArray(thing))\n return thing;\n if (thing == null)\n return [];\n return [thing];\n}\n\nfunction getMatcherString(id, resolutionBase) {\n if (resolutionBase === false) {\n return id;\n }\n // resolve('') is valid and will default to process.cwd()\n const basePath = resolve(resolutionBase || '')\n .split(sep)\n .join('/')\n // escape all possible (posix + win) path characters that might interfere with regex\n .replace(/[-^$*+?.()|[\\]{}]/g, '\\\\$&');\n // Note that we use posix.join because:\n // 1. the basePath has been normalized to use /\n // 2. the incoming glob (id) matcher, also uses /\n // otherwise Node will force backslash (\\) on windows\n return posix.join(basePath, id);\n}\nconst createFilter = function createFilter(include, exclude, options) {\n const resolutionBase = options && options.resolve;\n const getMatcher = (id) => id instanceof RegExp\n ? id\n : {\n test: (what) => {\n // this refactor is a tad overly verbose but makes for easy debugging\n const pattern = getMatcherString(id, resolutionBase);\n const fn = pm(pattern, { dot: true });\n const result = fn(what);\n return result;\n }\n };\n const includeMatchers = ensureArray(include).map(getMatcher);\n const excludeMatchers = ensureArray(exclude).map(getMatcher);\n return function result(id) {\n if (typeof id !== 'string')\n return false;\n if (/\\0/.test(id))\n return false;\n const pathId = id.split(sep).join('/');\n for (let i = 0; i < excludeMatchers.length; ++i) {\n const matcher = excludeMatchers[i];\n if (matcher.test(pathId))\n return false;\n }\n for (let i = 0; i < includeMatchers.length; ++i) {\n const matcher = includeMatchers[i];\n if (matcher.test(pathId))\n return true;\n }\n return !includeMatchers.length;\n };\n};\n\nconst reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';\nconst builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';\nconst forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));\nforbiddenIdentifiers.add('');\nconst makeLegalIdentifier = function makeLegalIdentifier(str) {\n let identifier = str\n .replace(/-(\\w)/g, (_, letter) => letter.toUpperCase())\n .replace(/[^$_a-zA-Z0-9]/g, '_');\n if (/\\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {\n identifier = `_${identifier}`;\n }\n return identifier || '_';\n};\n\nfunction stringify(obj) {\n return (JSON.stringify(obj) || 'undefined').replace(/[\\u2028\\u2029]/g, (char) => `\\\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);\n}\nfunction serializeArray(arr, indent, baseIndent) {\n let output = '[';\n const separator = indent ? `\\n${baseIndent}${indent}` : '';\n for (let i = 0; i < arr.length; i++) {\n const key = arr[i];\n output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;\n }\n return `${output}${indent ? `\\n${baseIndent}` : ''}]`;\n}\nfunction serializeObject(obj, indent, baseIndent) {\n let output = '{';\n const separator = indent ? `\\n${baseIndent}${indent}` : '';\n const entries = Object.entries(obj);\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i];\n const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);\n output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;\n }\n return `${output}${indent ? `\\n${baseIndent}` : ''}}`;\n}\nfunction serialize(obj, indent, baseIndent) {\n if (obj === Infinity)\n return 'Infinity';\n if (obj === -Infinity)\n return '-Infinity';\n if (obj === 0 && 1 / obj === -Infinity)\n return '-0';\n if (obj instanceof Date)\n return `new Date(${obj.getTime()})`;\n if (obj instanceof RegExp)\n return obj.toString();\n if (obj !== obj)\n return 'NaN'; // eslint-disable-line no-self-compare\n if (Array.isArray(obj))\n return serializeArray(obj, indent, baseIndent);\n if (obj === null)\n return 'null';\n if (typeof obj === 'object')\n return serializeObject(obj, indent, baseIndent);\n return stringify(obj);\n}\nconst dataToEsm = function dataToEsm(data, options = {}) {\n const t = options.compact ? '' : 'indent' in options ? options.indent : '\\t';\n const _ = options.compact ? '' : ' ';\n const n = options.compact ? '' : '\\n';\n const declarationType = options.preferConst ? 'const' : 'var';\n if (options.namedExports === false ||\n typeof data !== 'object' ||\n Array.isArray(data) ||\n data instanceof Date ||\n data instanceof RegExp ||\n data === null) {\n const code = serialize(data, options.compact ? null : t, '');\n const magic = _ || (/^[{[\\-\\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape\n return `export default${magic}${code};`;\n }\n let namedExportCode = '';\n const defaultExportRows = [];\n for (const [key, value] of Object.entries(data)) {\n if (key === makeLegalIdentifier(key)) {\n if (options.objectShorthand)\n defaultExportRows.push(key);\n else\n defaultExportRows.push(`${key}:${_}${key}`);\n namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;\n }\n else {\n defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);\n }\n }\n return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;\n};\n\n// TODO: remove this in next major\nvar index = {\n addExtension,\n attachScopes,\n createFilter,\n dataToEsm,\n extractAssignedNames,\n makeLegalIdentifier\n};\n\nexport default index;\nexport { addExtension, attachScopes, createFilter, dataToEsm, extractAssignedNames, makeLegalIdentifier };\n","var path = require('path');\n\nmodule.exports = function (basedir, relfiles) {\n if (relfiles) {\n var files = relfiles.map(function (r) {\n return path.resolve(basedir, r);\n });\n }\n else {\n var files = basedir;\n }\n \n var res = files.slice(1).reduce(function (ps, file) {\n if (!file.match(/^([A-Za-z]:)?\\/|\\\\/)) {\n throw new Error('relative path without a basedir');\n }\n \n var xs = file.split(/\\/+|\\\\+/);\n for (\n var i = 0;\n ps[i] === xs[i] && i < Math.min(ps.length, xs.length);\n i++\n );\n return ps.slice(0, i);\n }, files[0].split(/\\/+|\\\\+/));\n \n // Windows correctly handles paths with forward-slashes\n return res.length > 1 ? res.join('/') : '/'\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\nvar pathModule = require('path');\nvar isWindows = process.platform === 'win32';\nvar fs = require('fs');\n\n// JavaScript implementation of realpath, ported from node pre-v6\n\nvar DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);\n\nfunction rethrow() {\n // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and\n // is fairly slow to generate.\n var callback;\n if (DEBUG) {\n var backtrace = new Error;\n callback = debugCallback;\n } else\n callback = missingCallback;\n\n return callback;\n\n function debugCallback(err) {\n if (err) {\n backtrace.message = err.message;\n err = backtrace;\n missingCallback(err);\n }\n }\n\n function missingCallback(err) {\n if (err) {\n if (process.throwDeprecation)\n throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs\n else if (!process.noDeprecation) {\n var msg = 'fs: missing callback ' + (err.stack || err.message);\n if (process.traceDeprecation)\n console.trace(msg);\n else\n console.error(msg);\n }\n }\n }\n}\n\nfunction maybeCallback(cb) {\n return typeof cb === 'function' ? cb : rethrow();\n}\n\nvar normalize = pathModule.normalize;\n\n// Regexp that finds the next partion of a (partial) path\n// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']\nif (isWindows) {\n var nextPartRe = /(.*?)(?:[\\/\\\\]+|$)/g;\n} else {\n var nextPartRe = /(.*?)(?:[\\/]+|$)/g;\n}\n\n// Regex to find the device root, including trailing slash. E.g. 'c:\\\\'.\nif (isWindows) {\n var splitRootRe = /^(?:[a-zA-Z]:|[\\\\\\/]{2}[^\\\\\\/]+[\\\\\\/][^\\\\\\/]+)?[\\\\\\/]*/;\n} else {\n var splitRootRe = /^[\\/]*/;\n}\n\nexports.realpathSync = function realpathSync(p, cache) {\n // make p is absolute\n p = pathModule.resolve(p);\n\n if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {\n return cache[p];\n }\n\n var original = p,\n seenLinks = {},\n knownHard = {};\n\n // current character position in p\n var pos;\n // the partial path so far, including a trailing slash if any\n var current;\n // the partial path without a trailing slash (except when pointing at a root)\n var base;\n // the partial path scanned in the previous round, with slash\n var previous;\n\n start();\n\n function start() {\n // Skip over roots\n var m = splitRootRe.exec(p);\n pos = m[0].length;\n current = m[0];\n base = m[0];\n previous = '';\n\n // On windows, check that the root exists. On unix there is no need.\n if (isWindows && !knownHard[base]) {\n fs.lstatSync(base);\n knownHard[base] = true;\n }\n }\n\n // walk down the path, swapping out linked pathparts for their real\n // values\n // NB: p.length changes.\n while (pos < p.length) {\n // find the next part\n nextPartRe.lastIndex = pos;\n var result = nextPartRe.exec(p);\n previous = current;\n current += result[0];\n base = previous + result[1];\n pos = nextPartRe.lastIndex;\n\n // continue if not a symlink\n if (knownHard[base] || (cache && cache[base] === base)) {\n continue;\n }\n\n var resolvedLink;\n if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {\n // some known symbolic link. no need to stat again.\n resolvedLink = cache[base];\n } else {\n var stat = fs.lstatSync(base);\n if (!stat.isSymbolicLink()) {\n knownHard[base] = true;\n if (cache) cache[base] = base;\n continue;\n }\n\n // read the link if it wasn't read before\n // dev/ino always return 0 on windows, so skip the check.\n var linkTarget = null;\n if (!isWindows) {\n var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);\n if (seenLinks.hasOwnProperty(id)) {\n linkTarget = seenLinks[id];\n }\n }\n if (linkTarget === null) {\n fs.statSync(base);\n linkTarget = fs.readlinkSync(base);\n }\n resolvedLink = pathModule.resolve(previous, linkTarget);\n // track this, if given a cache.\n if (cache) cache[base] = resolvedLink;\n if (!isWindows) seenLinks[id] = linkTarget;\n }\n\n // resolve the link, then start over\n p = pathModule.resolve(resolvedLink, p.slice(pos));\n start();\n }\n\n if (cache) cache[original] = p;\n\n return p;\n};\n\n\nexports.realpath = function realpath(p, cache, cb) {\n if (typeof cb !== 'function') {\n cb = maybeCallback(cache);\n cache = null;\n }\n\n // make p is absolute\n p = pathModule.resolve(p);\n\n if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {\n return process.nextTick(cb.bind(null, null, cache[p]));\n }\n\n var original = p,\n seenLinks = {},\n knownHard = {};\n\n // current character position in p\n var pos;\n // the partial path so far, including a trailing slash if any\n var current;\n // the partial path without a trailing slash (except when pointing at a root)\n var base;\n // the partial path scanned in the previous round, with slash\n var previous;\n\n start();\n\n function start() {\n // Skip over roots\n var m = splitRootRe.exec(p);\n pos = m[0].length;\n current = m[0];\n base = m[0];\n previous = '';\n\n // On windows, check that the root exists. On unix there is no need.\n if (isWindows && !knownHard[base]) {\n fs.lstat(base, function(err) {\n if (err) return cb(err);\n knownHard[base] = true;\n LOOP();\n });\n } else {\n process.nextTick(LOOP);\n }\n }\n\n // walk down the path, swapping out linked pathparts for their real\n // values\n function LOOP() {\n // stop if scanned past end of path\n if (pos >= p.length) {\n if (cache) cache[original] = p;\n return cb(null, p);\n }\n\n // find the next part\n nextPartRe.lastIndex = pos;\n var result = nextPartRe.exec(p);\n previous = current;\n current += result[0];\n base = previous + result[1];\n pos = nextPartRe.lastIndex;\n\n // continue if not a symlink\n if (knownHard[base] || (cache && cache[base] === base)) {\n return process.nextTick(LOOP);\n }\n\n if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {\n // known symbolic link. no need to stat again.\n return gotResolvedLink(cache[base]);\n }\n\n return fs.lstat(base, gotStat);\n }\n\n function gotStat(err, stat) {\n if (err) return cb(err);\n\n // if not a symlink, skip to the next path part\n if (!stat.isSymbolicLink()) {\n knownHard[base] = true;\n if (cache) cache[base] = base;\n return process.nextTick(LOOP);\n }\n\n // stat & read the link if not read before\n // call gotTarget as soon as the link target is known\n // dev/ino always return 0 on windows, so skip the check.\n if (!isWindows) {\n var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);\n if (seenLinks.hasOwnProperty(id)) {\n return gotTarget(null, seenLinks[id], base);\n }\n }\n fs.stat(base, function(err) {\n if (err) return cb(err);\n\n fs.readlink(base, function(err, target) {\n if (!isWindows) seenLinks[id] = target;\n gotTarget(err, target);\n });\n });\n }\n\n function gotTarget(err, target, base) {\n if (err) return cb(err);\n\n var resolvedLink = pathModule.resolve(previous, target);\n if (cache) cache[base] = resolvedLink;\n gotResolvedLink(resolvedLink);\n }\n\n function gotResolvedLink(resolvedLink) {\n // resolve the link, then start over\n p = pathModule.resolve(resolvedLink, p.slice(pos));\n start();\n }\n};\n","module.exports = realpath\nrealpath.realpath = realpath\nrealpath.sync = realpathSync\nrealpath.realpathSync = realpathSync\nrealpath.monkeypatch = monkeypatch\nrealpath.unmonkeypatch = unmonkeypatch\n\nvar fs = require('fs')\nvar origRealpath = fs.realpath\nvar origRealpathSync = fs.realpathSync\n\nvar version = process.version\nvar ok = /^v[0-5]\\./.test(version)\nvar old = require('./old.js')\n\nfunction newError (er) {\n return er && er.syscall === 'realpath' && (\n er.code === 'ELOOP' ||\n er.code === 'ENOMEM' ||\n er.code === 'ENAMETOOLONG'\n )\n}\n\nfunction realpath (p, cache, cb) {\n if (ok) {\n return origRealpath(p, cache, cb)\n }\n\n if (typeof cache === 'function') {\n cb = cache\n cache = null\n }\n origRealpath(p, cache, function (er, result) {\n if (newError(er)) {\n old.realpath(p, cache, cb)\n } else {\n cb(er, result)\n }\n })\n}\n\nfunction realpathSync (p, cache) {\n if (ok) {\n return origRealpathSync(p, cache)\n }\n\n try {\n return origRealpathSync(p, cache)\n } catch (er) {\n if (newError(er)) {\n return old.realpathSync(p, cache)\n } else {\n throw er\n }\n }\n}\n\nfunction monkeypatch () {\n fs.realpath = realpath\n fs.realpathSync = realpathSync\n}\n\nfunction unmonkeypatch () {\n fs.realpath = origRealpath\n fs.realpathSync = origRealpathSync\n}\n","module.exports = function (xs, fn) {\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n var x = fn(xs[i], i);\n if (isArray(x)) res.push.apply(res, x);\n else res.push(x);\n }\n return res;\n};\n\nvar isArray = Array.isArray || function (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]';\n};\n","'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n if(a===b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n","var concatMap = require('concat-map');\nvar balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str) {\n if (!str)\n return [];\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), true).map(unescapeBraces);\n}\n\nfunction identity(e) {\n return e;\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m || /\\$$/.test(m.pre)) return [str];\n\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,.*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], false).map(embrace);\n if (n.length === 1) {\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.abs(numeric(n[2]))\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y); i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = concatMap(n, function(el) { return expand(el, false) });\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n\n return expansions;\n}\n\n","module.exports = minimatch\nminimatch.Minimatch = Minimatch\n\nvar path = { sep: '/' }\ntry {\n path = require('path')\n} catch (er) {}\n\nvar GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}\nvar expand = require('brace-expansion')\n\nvar plTypes = {\n '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},\n '?': { open: '(?:', close: ')?' },\n '+': { open: '(?:', close: ')+' },\n '*': { open: '(?:', close: ')*' },\n '@': { open: '(?:', close: ')' }\n}\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nvar qmark = '[^/]'\n\n// * => any number of characters\nvar star = qmark + '*?'\n\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nvar twoStarDot = '(?:(?!(?:\\\\\\/|^)(?:\\\\.{1,2})($|\\\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nvar twoStarNoDot = '(?:(?!(?:\\\\\\/|^)\\\\.).)*?'\n\n// characters that need to be escaped in RegExp.\nvar reSpecials = charSet('().*{}+?[]^$\\\\!')\n\n// \"abc\" -> { a:true, b:true, c:true }\nfunction charSet (s) {\n return s.split('').reduce(function (set, c) {\n set[c] = true\n return set\n }, {})\n}\n\n// normalizes slashes.\nvar slashSplit = /\\/+/\n\nminimatch.filter = filter\nfunction filter (pattern, options) {\n options = options || {}\n return function (p, i, list) {\n return minimatch(p, pattern, options)\n }\n}\n\nfunction ext (a, b) {\n a = a || {}\n b = b || {}\n var t = {}\n Object.keys(b).forEach(function (k) {\n t[k] = b[k]\n })\n Object.keys(a).forEach(function (k) {\n t[k] = a[k]\n })\n return t\n}\n\nminimatch.defaults = function (def) {\n if (!def || !Object.keys(def).length) return minimatch\n\n var orig = minimatch\n\n var m = function minimatch (p, pattern, options) {\n return orig.minimatch(p, pattern, ext(def, options))\n }\n\n m.Minimatch = function Minimatch (pattern, options) {\n return new orig.Minimatch(pattern, ext(def, options))\n }\n\n return m\n}\n\nMinimatch.defaults = function (def) {\n if (!def || !Object.keys(def).length) return Minimatch\n return minimatch.defaults(def).Minimatch\n}\n\nfunction minimatch (p, pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('glob pattern string required')\n }\n\n if (!options) options = {}\n\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false\n }\n\n // \"\" only matches \"\"\n if (pattern.trim() === '') return p === ''\n\n return new Minimatch(pattern, options).match(p)\n}\n\nfunction Minimatch (pattern, options) {\n if (!(this instanceof Minimatch)) {\n return new Minimatch(pattern, options)\n }\n\n if (typeof pattern !== 'string') {\n throw new TypeError('glob pattern string required')\n }\n\n if (!options) options = {}\n pattern = pattern.trim()\n\n // windows support: need to use /, not \\\n if (path.sep !== '/') {\n pattern = pattern.split(path.sep).join('/')\n }\n\n this.options = options\n this.set = []\n this.pattern = pattern\n this.regexp = null\n this.negate = false\n this.comment = false\n this.empty = false\n\n // make the set of regexps etc.\n this.make()\n}\n\nMinimatch.prototype.debug = function () {}\n\nMinimatch.prototype.make = make\nfunction make () {\n // don't do it more than once.\n if (this._made) return\n\n var pattern = this.pattern\n var options = this.options\n\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true\n return\n }\n if (!pattern) {\n this.empty = true\n return\n }\n\n // step 1: figure out negation, etc.\n this.parseNegate()\n\n // step 2: expand braces\n var set = this.globSet = this.braceExpand()\n\n if (options.debug) this.debug = console.error\n\n this.debug(this.pattern, set)\n\n // step 3: now we have a set, so turn each one into a series of path-portion\n // matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n set = this.globParts = set.map(function (s) {\n return s.split(slashSplit)\n })\n\n this.debug(this.pattern, set)\n\n // glob --> regexps\n set = set.map(function (s, si, set) {\n return s.map(this.parse, this)\n }, this)\n\n this.debug(this.pattern, set)\n\n // filter out everything that didn't compile properly.\n set = set.filter(function (s) {\n return s.indexOf(false) === -1\n })\n\n this.debug(this.pattern, set)\n\n this.set = set\n}\n\nMinimatch.prototype.parseNegate = parseNegate\nfunction parseNegate () {\n var pattern = this.pattern\n var negate = false\n var options = this.options\n var negateOffset = 0\n\n if (options.nonegate) return\n\n for (var i = 0, l = pattern.length\n ; i < l && pattern.charAt(i) === '!'\n ; i++) {\n negate = !negate\n negateOffset++\n }\n\n if (negateOffset) this.pattern = pattern.substr(negateOffset)\n this.negate = negate\n}\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nminimatch.braceExpand = function (pattern, options) {\n return braceExpand(pattern, options)\n}\n\nMinimatch.prototype.braceExpand = braceExpand\n\nfunction braceExpand (pattern, options) {\n if (!options) {\n if (this instanceof Minimatch) {\n options = this.options\n } else {\n options = {}\n }\n }\n\n pattern = typeof pattern === 'undefined'\n ? this.pattern : pattern\n\n if (typeof pattern === 'undefined') {\n throw new TypeError('undefined pattern')\n }\n\n if (options.nobrace ||\n !pattern.match(/\\{.*\\}/)) {\n // shortcut. no need to expand.\n return [pattern]\n }\n\n return expand(pattern)\n}\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\nMinimatch.prototype.parse = parse\nvar SUBPARSE = {}\nfunction parse (pattern, isSub) {\n if (pattern.length > 1024 * 64) {\n throw new TypeError('pattern is too long')\n }\n\n var options = this.options\n\n // shortcuts\n if (!options.noglobstar && pattern === '**') return GLOBSTAR\n if (pattern === '') return ''\n\n var re = ''\n var hasMagic = !!options.nocase\n var escaping = false\n // ? => one single character\n var patternListStack = []\n var negativeLists = []\n var stateChar\n var inClass = false\n var reClassStart = -1\n var classStart = -1\n // . and .. never match anything that doesn't start with .,\n // even when options.dot is set.\n var patternStart = pattern.charAt(0) === '.' ? '' // anything\n // not (start or / followed by . or .. followed by / or end)\n : options.dot ? '(?!(?:^|\\\\\\/)\\\\.{1,2}(?:$|\\\\\\/))'\n : '(?!\\\\.)'\n var self = this\n\n function clearStateChar () {\n if (stateChar) {\n // we had some state-tracking character\n // that wasn't consumed by this pass.\n switch (stateChar) {\n case '*':\n re += star\n hasMagic = true\n break\n case '?':\n re += qmark\n hasMagic = true\n break\n default:\n re += '\\\\' + stateChar\n break\n }\n self.debug('clearStateChar %j %j', stateChar, re)\n stateChar = false\n }\n }\n\n for (var i = 0, len = pattern.length, c\n ; (i < len) && (c = pattern.charAt(i))\n ; i++) {\n this.debug('%s\\t%s %s %j', pattern, i, re, c)\n\n // skip over any that are escaped.\n if (escaping && reSpecials[c]) {\n re += '\\\\' + c\n escaping = false\n continue\n }\n\n switch (c) {\n case '/':\n // completely not allowed, even escaped.\n // Should already be path-split by now.\n return false\n\n case '\\\\':\n clearStateChar()\n escaping = true\n continue\n\n // the various stateChar values\n // for the \"extglob\" stuff.\n case '?':\n case '*':\n case '+':\n case '@':\n case '!':\n this.debug('%s\\t%s %s %j <-- stateChar', pattern, i, re, c)\n\n // all of those are literals inside a class, except that\n // the glob [!a] means [^a] in regexp\n if (inClass) {\n this.debug(' in class')\n if (c === '!' && i === classStart + 1) c = '^'\n re += c\n continue\n }\n\n // if we already have a stateChar, then it means\n // that there was something like ** or +? in there.\n // Handle the stateChar, then proceed with this one.\n self.debug('call clearStateChar %j', stateChar)\n clearStateChar()\n stateChar = c\n // if extglob is disabled, then +(asdf|foo) isn't a thing.\n // just clear the statechar *now*, rather than even diving into\n // the patternList stuff.\n if (options.noext) clearStateChar()\n continue\n\n case '(':\n if (inClass) {\n re += '('\n continue\n }\n\n if (!stateChar) {\n re += '\\\\('\n continue\n }\n\n patternListStack.push({\n type: stateChar,\n start: i - 1,\n reStart: re.length,\n open: plTypes[stateChar].open,\n close: plTypes[stateChar].close\n })\n // negation is (?:(?!js)[^/]*)\n re += stateChar === '!' ? '(?:(?!(?:' : '(?:'\n this.debug('plType %j %j', stateChar, re)\n stateChar = false\n continue\n\n case ')':\n if (inClass || !patternListStack.length) {\n re += '\\\\)'\n continue\n }\n\n clearStateChar()\n hasMagic = true\n var pl = patternListStack.pop()\n // negation is (?:(?!js)[^/]*)\n // The others are (?:)\n re += pl.close\n if (pl.type === '!') {\n negativeLists.push(pl)\n }\n pl.reEnd = re.length\n continue\n\n case '|':\n if (inClass || !patternListStack.length || escaping) {\n re += '\\\\|'\n escaping = false\n continue\n }\n\n clearStateChar()\n re += '|'\n continue\n\n // these are mostly the same in regexp and glob\n case '[':\n // swallow any state-tracking char before the [\n clearStateChar()\n\n if (inClass) {\n re += '\\\\' + c\n continue\n }\n\n inClass = true\n classStart = i\n reClassStart = re.length\n re += c\n continue\n\n case ']':\n // a right bracket shall lose its special\n // meaning and represent itself in\n // a bracket expression if it occurs\n // first in the list. -- POSIX.2 2.8.3.2\n if (i === classStart + 1 || !inClass) {\n re += '\\\\' + c\n escaping = false\n continue\n }\n\n // handle the case where we left a class open.\n // \"[z-a]\" is valid, equivalent to \"\\[z-a\\]\"\n if (inClass) {\n // split where the last [ was, make sure we don't have\n // an invalid re. if so, re-walk the contents of the\n // would-be class to re-translate any characters that\n // were passed through as-is\n // TODO: It would probably be faster to determine this\n // without a try/catch and a new RegExp, but it's tricky\n // to do safely. For now, this is safe and works.\n var cs = pattern.substring(classStart + 1, i)\n try {\n RegExp('[' + cs + ']')\n } catch (er) {\n // not a valid class!\n var sp = this.parse(cs, SUBPARSE)\n re = re.substr(0, reClassStart) + '\\\\[' + sp[0] + '\\\\]'\n hasMagic = hasMagic || sp[1]\n inClass = false\n continue\n }\n }\n\n // finish up the class.\n hasMagic = true\n inClass = false\n re += c\n continue\n\n default:\n // swallow any state char that wasn't consumed\n clearStateChar()\n\n if (escaping) {\n // no need\n escaping = false\n } else if (reSpecials[c]\n && !(c === '^' && inClass)) {\n re += '\\\\'\n }\n\n re += c\n\n } // switch\n } // for\n\n // handle the case where we left a class open.\n // \"[abc\" is valid, equivalent to \"\\[abc\"\n if (inClass) {\n // split where the last [ was, and escape it\n // this is a huge pita. We now have to re-walk\n // the contents of the would-be class to re-translate\n // any characters that were passed through as-is\n cs = pattern.substr(classStart + 1)\n sp = this.parse(cs, SUBPARSE)\n re = re.substr(0, reClassStart) + '\\\\[' + sp[0]\n hasMagic = hasMagic || sp[1]\n }\n\n // handle the case where we had a +( thing at the *end*\n // of the pattern.\n // each pattern list stack adds 3 chars, and we need to go through\n // and escape any | chars that were passed through as-is for the regexp.\n // Go through and escape them, taking care not to double-escape any\n // | chars that were already escaped.\n for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {\n var tail = re.slice(pl.reStart + pl.open.length)\n this.debug('setting tail', re, pl)\n // maybe some even number of \\, then maybe 1 \\, followed by a |\n tail = tail.replace(/((?:\\\\{2}){0,64})(\\\\?)\\|/g, function (_, $1, $2) {\n if (!$2) {\n // the | isn't already escaped, so escape it.\n $2 = '\\\\'\n }\n\n // need to escape all those slashes *again*, without escaping the\n // one that we need for escaping the | character. As it works out,\n // escaping an even number of slashes can be done by simply repeating\n // it exactly after itself. That's why this trick works.\n //\n // I am sorry that you have to see this.\n return $1 + $1 + $2 + '|'\n })\n\n this.debug('tail=%j\\n %s', tail, tail, pl, re)\n var t = pl.type === '*' ? star\n : pl.type === '?' ? qmark\n : '\\\\' + pl.type\n\n hasMagic = true\n re = re.slice(0, pl.reStart) + t + '\\\\(' + tail\n }\n\n // handle trailing things that only matter at the very end.\n clearStateChar()\n if (escaping) {\n // trailing \\\\\n re += '\\\\\\\\'\n }\n\n // only need to apply the nodot start if the re starts with\n // something that could conceivably capture a dot\n var addPatternStart = false\n switch (re.charAt(0)) {\n case '.':\n case '[':\n case '(': addPatternStart = true\n }\n\n // Hack to work around lack of negative lookbehind in JS\n // A pattern like: *.!(x).!(y|z) needs to ensure that a name\n // like 'a.xyz.yz' doesn't match. So, the first negative\n // lookahead, has to look ALL the way ahead, to the end of\n // the pattern.\n for (var n = negativeLists.length - 1; n > -1; n--) {\n var nl = negativeLists[n]\n\n var nlBefore = re.slice(0, nl.reStart)\n var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)\n var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)\n var nlAfter = re.slice(nl.reEnd)\n\n nlLast += nlAfter\n\n // Handle nested stuff like *(*.js|!(*.json)), where open parens\n // mean that we should *not* include the ) in the bit that is considered\n // \"after\" the negated section.\n var openParensBefore = nlBefore.split('(').length - 1\n var cleanAfter = nlAfter\n for (i = 0; i < openParensBefore; i++) {\n cleanAfter = cleanAfter.replace(/\\)[+*?]?/, '')\n }\n nlAfter = cleanAfter\n\n var dollar = ''\n if (nlAfter === '' && isSub !== SUBPARSE) {\n dollar = '$'\n }\n var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast\n re = newRe\n }\n\n // if the re is not \"\" at this point, then we need to make sure\n // it doesn't match against an empty path part.\n // Otherwise a/* will match a/, which it should not.\n if (re !== '' && hasMagic) {\n re = '(?=.)' + re\n }\n\n if (addPatternStart) {\n re = patternStart + re\n }\n\n // parsing just a piece of a larger pattern.\n if (isSub === SUBPARSE) {\n return [re, hasMagic]\n }\n\n // skip the regexp for non-magical patterns\n // unescape anything in it, though, so that it'll be\n // an exact match against a file etc.\n if (!hasMagic) {\n return globUnescape(pattern)\n }\n\n var flags = options.nocase ? 'i' : ''\n try {\n var regExp = new RegExp('^' + re + '$', flags)\n } catch (er) {\n // If it was an invalid regular expression, then it can't match\n // anything. This trick looks for a character after the end of\n // the string, which is of course impossible, except in multi-line\n // mode, but it's not a /m regex.\n return new RegExp('$.')\n }\n\n regExp._glob = pattern\n regExp._src = re\n\n return regExp\n}\n\nminimatch.makeRe = function (pattern, options) {\n return new Minimatch(pattern, options || {}).makeRe()\n}\n\nMinimatch.prototype.makeRe = makeRe\nfunction makeRe () {\n if (this.regexp || this.regexp === false) return this.regexp\n\n // at this point, this.set is a 2d array of partial\n // pattern strings, or \"**\".\n //\n // It's better to use .match(). This function shouldn't\n // be used, really, but it's pretty convenient sometimes,\n // when you just want to work with a regex.\n var set = this.set\n\n if (!set.length) {\n this.regexp = false\n return this.regexp\n }\n var options = this.options\n\n var twoStar = options.noglobstar ? star\n : options.dot ? twoStarDot\n : twoStarNoDot\n var flags = options.nocase ? 'i' : ''\n\n var re = set.map(function (pattern) {\n return pattern.map(function (p) {\n return (p === GLOBSTAR) ? twoStar\n : (typeof p === 'string') ? regExpEscape(p)\n : p._src\n }).join('\\\\\\/')\n }).join('|')\n\n // must match entire pattern\n // ending in a * or ** will make it less strict.\n re = '^(?:' + re + ')$'\n\n // can match anything, as long as it's not this.\n if (this.negate) re = '^(?!' + re + ').*$'\n\n try {\n this.regexp = new RegExp(re, flags)\n } catch (ex) {\n this.regexp = false\n }\n return this.regexp\n}\n\nminimatch.match = function (list, pattern, options) {\n options = options || {}\n var mm = new Minimatch(pattern, options)\n list = list.filter(function (f) {\n return mm.match(f)\n })\n if (mm.options.nonull && !list.length) {\n list.push(pattern)\n }\n return list\n}\n\nMinimatch.prototype.match = match\nfunction match (f, partial) {\n this.debug('match', f, this.pattern)\n // short-circuit in the case of busted things.\n // comments, etc.\n if (this.comment) return false\n if (this.empty) return f === ''\n\n if (f === '/' && partial) return true\n\n var options = this.options\n\n // windows: need to use /, not \\\n if (path.sep !== '/') {\n f = f.split(path.sep).join('/')\n }\n\n // treat the test path as a set of pathparts.\n f = f.split(slashSplit)\n this.debug(this.pattern, 'split', f)\n\n // just ONE of the pattern sets in this.set needs to match\n // in order for it to be valid. If negating, then just one\n // match means that we have failed.\n // Either way, return on the first hit.\n\n var set = this.set\n this.debug(this.pattern, 'set', set)\n\n // Find the basename of the path by looking for the last non-empty segment\n var filename\n var i\n for (i = f.length - 1; i >= 0; i--) {\n filename = f[i]\n if (filename) break\n }\n\n for (i = 0; i < set.length; i++) {\n var pattern = set[i]\n var file = f\n if (options.matchBase && pattern.length === 1) {\n file = [filename]\n }\n var hit = this.matchOne(file, pattern, partial)\n if (hit) {\n if (options.flipNegate) return true\n return !this.negate\n }\n }\n\n // didn't get any hits. this is success if it's a negative\n // pattern, failure otherwise.\n if (options.flipNegate) return false\n return this.negate\n}\n\n// set partial to true to test if, for example,\n// \"/a/b\" matches the start of \"/*/b/*/d\"\n// Partial means, if you run out of file before you run\n// out of pattern, then that's fine, as long as all\n// the parts match.\nMinimatch.prototype.matchOne = function (file, pattern, partial) {\n var options = this.options\n\n this.debug('matchOne',\n { 'this': this, file: file, pattern: pattern })\n\n this.debug('matchOne', file.length, pattern.length)\n\n for (var fi = 0,\n pi = 0,\n fl = file.length,\n pl = pattern.length\n ; (fi < fl) && (pi < pl)\n ; fi++, pi++) {\n this.debug('matchOne loop')\n var p = pattern[pi]\n var f = file[fi]\n\n this.debug(pattern, p, f)\n\n // should be impossible.\n // some invalid regexp stuff in the set.\n if (p === false) return false\n\n if (p === GLOBSTAR) {\n this.debug('GLOBSTAR', [pattern, p, f])\n\n // \"**\"\n // a/**/b/**/c would match the following:\n // a/b/x/y/z/c\n // a/x/y/z/b/c\n // a/b/x/b/x/c\n // a/b/c\n // To do this, take the rest of the pattern after\n // the **, and see if it would match the file remainder.\n // If so, return success.\n // If not, the ** \"swallows\" a segment, and try again.\n // This is recursively awful.\n //\n // a/**/b/**/c matching a/b/x/y/z/c\n // - a matches a\n // - doublestar\n // - matchOne(b/x/y/z/c, b/**/c)\n // - b matches b\n // - doublestar\n // - matchOne(x/y/z/c, c) -> no\n // - matchOne(y/z/c, c) -> no\n // - matchOne(z/c, c) -> no\n // - matchOne(c, c) yes, hit\n var fr = fi\n var pr = pi + 1\n if (pr === pl) {\n this.debug('** at the end')\n // a ** at the end will just swallow the rest.\n // We have found a match.\n // however, it will not swallow /.x, unless\n // options.dot is set.\n // . and .. are *never* matched by **, for explosively\n // exponential reasons.\n for (; fi < fl; fi++) {\n if (file[fi] === '.' || file[fi] === '..' ||\n (!options.dot && file[fi].charAt(0) === '.')) return false\n }\n return true\n }\n\n // ok, let's see if we can swallow whatever we can.\n while (fr < fl) {\n var swallowee = file[fr]\n\n this.debug('\\nglobstar while', file, fr, pattern, pr, swallowee)\n\n // XXX remove this slice. Just pass the start index.\n if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {\n this.debug('globstar found match!', fr, fl, swallowee)\n // found a match.\n return true\n } else {\n // can't swallow \".\" or \"..\" ever.\n // can only swallow \".foo\" when explicitly asked.\n if (swallowee === '.' || swallowee === '..' ||\n (!options.dot && swallowee.charAt(0) === '.')) {\n this.debug('dot detected!', file, fr, pattern, pr)\n break\n }\n\n // ** swallows a segment, and continue.\n this.debug('globstar swallow a segment, and continue')\n fr++\n }\n }\n\n // no match was found.\n // However, in partial mode, we can't say this is necessarily over.\n // If there's more *pattern* left, then\n if (partial) {\n // ran out of file\n this.debug('\\n>>> no match, partial?', file, fr, pattern, pr)\n if (fr === fl) return true\n }\n return false\n }\n\n // something other than **\n // non-magic patterns just have to match exactly\n // patterns with magic have been turned into regexps.\n var hit\n if (typeof p === 'string') {\n if (options.nocase) {\n hit = f.toLowerCase() === p.toLowerCase()\n } else {\n hit = f === p\n }\n this.debug('string match', p, f, hit)\n } else {\n hit = f.match(p)\n this.debug('pattern match', p, f, hit)\n }\n\n if (!hit) return false\n }\n\n // Note: ending in / means that we'll get a final \"\"\n // at the end of the pattern. This can only match a\n // corresponding \"\" at the end of the file.\n // If the file ends in /, then it can only match a\n // a pattern that ends in /, unless the pattern just\n // doesn't have any more for it. But, a/b/ should *not*\n // match \"a/b/*\", even though \"\" matches against the\n // [^/]*? pattern, except in partial mode, where it might\n // simply not be reached yet.\n // However, a/b/ should still satisfy a/*\n\n // now either we fell off the end of the pattern, or we're done.\n if (fi === fl && pi === pl) {\n // ran out of pattern and filename at the same time.\n // an exact hit!\n return true\n } else if (fi === fl) {\n // ran out of file, but still had pattern left.\n // this is ok if we're doing the match as part of\n // a glob fs traversal.\n return partial\n } else if (pi === pl) {\n // ran out of pattern, still have file left.\n // this is only acceptable if we're on the very last\n // empty segment of a file with a trailing slash.\n // a/* should match a/b/\n var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')\n return emptyFileEnd\n }\n\n // should be unreachable.\n throw new Error('wtf?')\n}\n\n// replace stuff like \\* with *\nfunction globUnescape (s) {\n return s.replace(/\\\\(.)/g, '$1')\n}\n\nfunction regExpEscape (s) {\n return s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\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 };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (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 }\n}\n","try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n","'use strict';\n\nfunction posix(path) {\n\treturn path.charAt(0) === '/';\n}\n\nfunction win32(path) {\n\t// https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56\n\tvar splitDeviceRe = /^([a-zA-Z]:|[\\\\\\/]{2}[^\\\\\\/]+[\\\\\\/]+[^\\\\\\/]+)?([\\\\\\/])?([\\s\\S]*?)$/;\n\tvar result = splitDeviceRe.exec(path);\n\tvar device = result[1] || '';\n\tvar isUnc = Boolean(device && device.charAt(1) !== ':');\n\n\t// UNC paths are always absolute\n\treturn Boolean(result[2] || isUnc);\n}\n\nmodule.exports = process.platform === 'win32' ? win32 : posix;\nmodule.exports.posix = posix;\nmodule.exports.win32 = win32;\n","exports.setopts = setopts\nexports.ownProp = ownProp\nexports.makeAbs = makeAbs\nexports.finish = finish\nexports.mark = mark\nexports.isIgnored = isIgnored\nexports.childrenIgnored = childrenIgnored\n\nfunction ownProp (obj, field) {\n return Object.prototype.hasOwnProperty.call(obj, field)\n}\n\nvar path = require(\"path\")\nvar minimatch = require(\"minimatch\")\nvar isAbsolute = require(\"path-is-absolute\")\nvar Minimatch = minimatch.Minimatch\n\nfunction alphasort (a, b) {\n return a.localeCompare(b, 'en')\n}\n\nfunction setupIgnores (self, options) {\n self.ignore = options.ignore || []\n\n if (!Array.isArray(self.ignore))\n self.ignore = [self.ignore]\n\n if (self.ignore.length) {\n self.ignore = self.ignore.map(ignoreMap)\n }\n}\n\n// ignore patterns are always in dot:true mode.\nfunction ignoreMap (pattern) {\n var gmatcher = null\n if (pattern.slice(-3) === '/**') {\n var gpattern = pattern.replace(/(\\/\\*\\*)+$/, '')\n gmatcher = new Minimatch(gpattern, { dot: true })\n }\n\n return {\n matcher: new Minimatch(pattern, { dot: true }),\n gmatcher: gmatcher\n }\n}\n\nfunction setopts (self, pattern, options) {\n if (!options)\n options = {}\n\n // base-matching: just use globstar for that.\n if (options.matchBase && -1 === pattern.indexOf(\"/\")) {\n if (options.noglobstar) {\n throw new Error(\"base matching requires globstar\")\n }\n pattern = \"**/\" + pattern\n }\n\n self.silent = !!options.silent\n self.pattern = pattern\n self.strict = options.strict !== false\n self.realpath = !!options.realpath\n self.realpathCache = options.realpathCache || Object.create(null)\n self.follow = !!options.follow\n self.dot = !!options.dot\n self.mark = !!options.mark\n self.nodir = !!options.nodir\n if (self.nodir)\n self.mark = true\n self.sync = !!options.sync\n self.nounique = !!options.nounique\n self.nonull = !!options.nonull\n self.nosort = !!options.nosort\n self.nocase = !!options.nocase\n self.stat = !!options.stat\n self.noprocess = !!options.noprocess\n self.absolute = !!options.absolute\n\n self.maxLength = options.maxLength || Infinity\n self.cache = options.cache || Object.create(null)\n self.statCache = options.statCache || Object.create(null)\n self.symlinks = options.symlinks || Object.create(null)\n\n setupIgnores(self, options)\n\n self.changedCwd = false\n var cwd = process.cwd()\n if (!ownProp(options, \"cwd\"))\n self.cwd = cwd\n else {\n self.cwd = path.resolve(options.cwd)\n self.changedCwd = self.cwd !== cwd\n }\n\n self.root = options.root || path.resolve(self.cwd, \"/\")\n self.root = path.resolve(self.root)\n if (process.platform === \"win32\")\n self.root = self.root.replace(/\\\\/g, \"/\")\n\n // TODO: is an absolute `cwd` supposed to be resolved against `root`?\n // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')\n self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)\n if (process.platform === \"win32\")\n self.cwdAbs = self.cwdAbs.replace(/\\\\/g, \"/\")\n self.nomount = !!options.nomount\n\n // disable comments and negation in Minimatch.\n // Note that they are not supported in Glob itself anyway.\n options.nonegate = true\n options.nocomment = true\n\n self.minimatch = new Minimatch(pattern, options)\n self.options = self.minimatch.options\n}\n\nfunction finish (self) {\n var nou = self.nounique\n var all = nou ? [] : Object.create(null)\n\n for (var i = 0, l = self.matches.length; i < l; i ++) {\n var matches = self.matches[i]\n if (!matches || Object.keys(matches).length === 0) {\n if (self.nonull) {\n // do like the shell, and spit out the literal glob\n var literal = self.minimatch.globSet[i]\n if (nou)\n all.push(literal)\n else\n all[literal] = true\n }\n } else {\n // had matches\n var m = Object.keys(matches)\n if (nou)\n all.push.apply(all, m)\n else\n m.forEach(function (m) {\n all[m] = true\n })\n }\n }\n\n if (!nou)\n all = Object.keys(all)\n\n if (!self.nosort)\n all = all.sort(alphasort)\n\n // at *some* point we statted all of these\n if (self.mark) {\n for (var i = 0; i < all.length; i++) {\n all[i] = self._mark(all[i])\n }\n if (self.nodir) {\n all = all.filter(function (e) {\n var notDir = !(/\\/$/.test(e))\n var c = self.cache[e] || self.cache[makeAbs(self, e)]\n if (notDir && c)\n notDir = c !== 'DIR' && !Array.isArray(c)\n return notDir\n })\n }\n }\n\n if (self.ignore.length)\n all = all.filter(function(m) {\n return !isIgnored(self, m)\n })\n\n self.found = all\n}\n\nfunction mark (self, p) {\n var abs = makeAbs(self, p)\n var c = self.cache[abs]\n var m = p\n if (c) {\n var isDir = c === 'DIR' || Array.isArray(c)\n var slash = p.slice(-1) === '/'\n\n if (isDir && !slash)\n m += '/'\n else if (!isDir && slash)\n m = m.slice(0, -1)\n\n if (m !== p) {\n var mabs = makeAbs(self, m)\n self.statCache[mabs] = self.statCache[abs]\n self.cache[mabs] = self.cache[abs]\n }\n }\n\n return m\n}\n\n// lotta situps...\nfunction makeAbs (self, f) {\n var abs = f\n if (f.charAt(0) === '/') {\n abs = path.join(self.root, f)\n } else if (isAbsolute(f) || f === '') {\n abs = f\n } else if (self.changedCwd) {\n abs = path.resolve(self.cwd, f)\n } else {\n abs = path.resolve(f)\n }\n\n if (process.platform === 'win32')\n abs = abs.replace(/\\\\/g, '/')\n\n return abs\n}\n\n\n// Return true, if pattern ends with globstar '**', for the accompanying parent directory.\n// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents\nfunction isIgnored (self, path) {\n if (!self.ignore.length)\n return false\n\n return self.ignore.some(function(item) {\n return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))\n })\n}\n\nfunction childrenIgnored (self, path) {\n if (!self.ignore.length)\n return false\n\n return self.ignore.some(function(item) {\n return !!(item.gmatcher && item.gmatcher.match(path))\n })\n}\n","module.exports = globSync\nglobSync.GlobSync = GlobSync\n\nvar fs = require('fs')\nvar rp = require('fs.realpath')\nvar minimatch = require('minimatch')\nvar Minimatch = minimatch.Minimatch\nvar Glob = require('./glob.js').Glob\nvar util = require('util')\nvar path = require('path')\nvar assert = require('assert')\nvar isAbsolute = require('path-is-absolute')\nvar common = require('./common.js')\nvar setopts = common.setopts\nvar ownProp = common.ownProp\nvar childrenIgnored = common.childrenIgnored\nvar isIgnored = common.isIgnored\n\nfunction globSync (pattern, options) {\n if (typeof options === 'function' || arguments.length === 3)\n throw new TypeError('callback provided to sync glob\\n'+\n 'See: https://github.com/isaacs/node-glob/issues/167')\n\n return new GlobSync(pattern, options).found\n}\n\nfunction GlobSync (pattern, options) {\n if (!pattern)\n throw new Error('must provide pattern')\n\n if (typeof options === 'function' || arguments.length === 3)\n throw new TypeError('callback provided to sync glob\\n'+\n 'See: https://github.com/isaacs/node-glob/issues/167')\n\n if (!(this instanceof GlobSync))\n return new GlobSync(pattern, options)\n\n setopts(this, pattern, options)\n\n if (this.noprocess)\n return this\n\n var n = this.minimatch.set.length\n this.matches = new Array(n)\n for (var i = 0; i < n; i ++) {\n this._process(this.minimatch.set[i], i, false)\n }\n this._finish()\n}\n\nGlobSync.prototype._finish = function () {\n assert(this instanceof GlobSync)\n if (this.realpath) {\n var self = this\n this.matches.forEach(function (matchset, index) {\n var set = self.matches[index] = Object.create(null)\n for (var p in matchset) {\n try {\n p = self._makeAbs(p)\n var real = rp.realpathSync(p, self.realpathCache)\n set[real] = true\n } catch (er) {\n if (er.syscall === 'stat')\n set[self._makeAbs(p)] = true\n else\n throw er\n }\n }\n })\n }\n common.finish(this)\n}\n\n\nGlobSync.prototype._process = function (pattern, index, inGlobStar) {\n assert(this instanceof GlobSync)\n\n // Get the first [n] parts of pattern that are all strings.\n var n = 0\n while (typeof pattern[n] === 'string') {\n n ++\n }\n // now n is the index of the first one that is *not* a string.\n\n // See if there's anything else\n var prefix\n switch (n) {\n // if not, then this is rather simple\n case pattern.length:\n this._processSimple(pattern.join('/'), index)\n return\n\n case 0:\n // pattern *starts* with some non-trivial item.\n // going to readdir(cwd), but not include the prefix in matches.\n prefix = null\n break\n\n default:\n // pattern has some string bits in the front.\n // whatever it starts with, whether that's 'absolute' like /foo/bar,\n // or 'relative' like '../baz'\n prefix = pattern.slice(0, n).join('/')\n break\n }\n\n var remain = pattern.slice(n)\n\n // get the list of entries.\n var read\n if (prefix === null)\n read = '.'\n else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {\n if (!prefix || !isAbsolute(prefix))\n prefix = '/' + prefix\n read = prefix\n } else\n read = prefix\n\n var abs = this._makeAbs(read)\n\n //if ignored, skip processing\n if (childrenIgnored(this, read))\n return\n\n var isGlobStar = remain[0] === minimatch.GLOBSTAR\n if (isGlobStar)\n this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)\n else\n this._processReaddir(prefix, read, abs, remain, index, inGlobStar)\n}\n\n\nGlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {\n var entries = this._readdir(abs, inGlobStar)\n\n // if the abs isn't a dir, then nothing can match!\n if (!entries)\n return\n\n // It will only match dot entries if it starts with a dot, or if\n // dot is set. Stuff like @(.foo|.bar) isn't allowed.\n var pn = remain[0]\n var negate = !!this.minimatch.negate\n var rawGlob = pn._glob\n var dotOk = this.dot || rawGlob.charAt(0) === '.'\n\n var matchedEntries = []\n for (var i = 0; i < entries.length; i++) {\n var e = entries[i]\n if (e.charAt(0) !== '.' || dotOk) {\n var m\n if (negate && !prefix) {\n m = !e.match(pn)\n } else {\n m = e.match(pn)\n }\n if (m)\n matchedEntries.push(e)\n }\n }\n\n var len = matchedEntries.length\n // If there are no matched entries, then nothing matches.\n if (len === 0)\n return\n\n // if this is the last remaining pattern bit, then no need for\n // an additional stat *unless* the user has specified mark or\n // stat explicitly. We know they exist, since readdir returned\n // them.\n\n if (remain.length === 1 && !this.mark && !this.stat) {\n if (!this.matches[index])\n this.matches[index] = Object.create(null)\n\n for (var i = 0; i < len; i ++) {\n var e = matchedEntries[i]\n if (prefix) {\n if (prefix.slice(-1) !== '/')\n e = prefix + '/' + e\n else\n e = prefix + e\n }\n\n if (e.charAt(0) === '/' && !this.nomount) {\n e = path.join(this.root, e)\n }\n this._emitMatch(index, e)\n }\n // This was the last one, and no stats were needed\n return\n }\n\n // now test all matched entries as stand-ins for that part\n // of the pattern.\n remain.shift()\n for (var i = 0; i < len; i ++) {\n var e = matchedEntries[i]\n var newPattern\n if (prefix)\n newPattern = [prefix, e]\n else\n newPattern = [e]\n this._process(newPattern.concat(remain), index, inGlobStar)\n }\n}\n\n\nGlobSync.prototype._emitMatch = function (index, e) {\n if (isIgnored(this, e))\n return\n\n var abs = this._makeAbs(e)\n\n if (this.mark)\n e = this._mark(e)\n\n if (this.absolute) {\n e = abs\n }\n\n if (this.matches[index][e])\n return\n\n if (this.nodir) {\n var c = this.cache[abs]\n if (c === 'DIR' || Array.isArray(c))\n return\n }\n\n this.matches[index][e] = true\n\n if (this.stat)\n this._stat(e)\n}\n\n\nGlobSync.prototype._readdirInGlobStar = function (abs) {\n // follow all symlinked directories forever\n // just proceed as if this is a non-globstar situation\n if (this.follow)\n return this._readdir(abs, false)\n\n var entries\n var lstat\n var stat\n try {\n lstat = fs.lstatSync(abs)\n } catch (er) {\n if (er.code === 'ENOENT') {\n // lstat failed, doesn't exist\n return null\n }\n }\n\n var isSym = lstat && lstat.isSymbolicLink()\n this.symlinks[abs] = isSym\n\n // If it's not a symlink or a dir, then it's definitely a regular file.\n // don't bother doing a readdir in that case.\n if (!isSym && lstat && !lstat.isDirectory())\n this.cache[abs] = 'FILE'\n else\n entries = this._readdir(abs, false)\n\n return entries\n}\n\nGlobSync.prototype._readdir = function (abs, inGlobStar) {\n var entries\n\n if (inGlobStar && !ownProp(this.symlinks, abs))\n return this._readdirInGlobStar(abs)\n\n if (ownProp(this.cache, abs)) {\n var c = this.cache[abs]\n if (!c || c === 'FILE')\n return null\n\n if (Array.isArray(c))\n return c\n }\n\n try {\n return this._readdirEntries(abs, fs.readdirSync(abs))\n } catch (er) {\n this._readdirError(abs, er)\n return null\n }\n}\n\nGlobSync.prototype._readdirEntries = function (abs, entries) {\n // if we haven't asked to stat everything, then just\n // assume that everything in there exists, so we can avoid\n // having to stat it a second time.\n if (!this.mark && !this.stat) {\n for (var i = 0; i < entries.length; i ++) {\n var e = entries[i]\n if (abs === '/')\n e = abs + e\n else\n e = abs + '/' + e\n this.cache[e] = true\n }\n }\n\n this.cache[abs] = entries\n\n // mark and cache dir-ness\n return entries\n}\n\nGlobSync.prototype._readdirError = function (f, er) {\n // handle errors, and cache the information\n switch (er.code) {\n case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205\n case 'ENOTDIR': // totally normal. means it *does* exist.\n var abs = this._makeAbs(f)\n this.cache[abs] = 'FILE'\n if (abs === this.cwdAbs) {\n var error = new Error(er.code + ' invalid cwd ' + this.cwd)\n error.path = this.cwd\n error.code = er.code\n throw error\n }\n break\n\n case 'ENOENT': // not terribly unusual\n case 'ELOOP':\n case 'ENAMETOOLONG':\n case 'UNKNOWN':\n this.cache[this._makeAbs(f)] = false\n break\n\n default: // some unusual error. Treat as failure.\n this.cache[this._makeAbs(f)] = false\n if (this.strict)\n throw er\n if (!this.silent)\n console.error('glob error', er)\n break\n }\n}\n\nGlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {\n\n var entries = this._readdir(abs, inGlobStar)\n\n // no entries means not a dir, so it can never have matches\n // foo.txt/** doesn't match foo.txt\n if (!entries)\n return\n\n // test without the globstar, and with every child both below\n // and replacing the globstar.\n var remainWithoutGlobStar = remain.slice(1)\n var gspref = prefix ? [ prefix ] : []\n var noGlobStar = gspref.concat(remainWithoutGlobStar)\n\n // the noGlobStar pattern exits the inGlobStar state\n this._process(noGlobStar, index, false)\n\n var len = entries.length\n var isSym = this.symlinks[abs]\n\n // If it's a symlink, and we're in a globstar, then stop\n if (isSym && inGlobStar)\n return\n\n for (var i = 0; i < len; i++) {\n var e = entries[i]\n if (e.charAt(0) === '.' && !this.dot)\n continue\n\n // these two cases enter the inGlobStar state\n var instead = gspref.concat(entries[i], remainWithoutGlobStar)\n this._process(instead, index, true)\n\n var below = gspref.concat(entries[i], remain)\n this._process(below, index, true)\n }\n}\n\nGlobSync.prototype._processSimple = function (prefix, index) {\n // XXX review this. Shouldn't it be doing the mounting etc\n // before doing stat? kinda weird?\n var exists = this._stat(prefix)\n\n if (!this.matches[index])\n this.matches[index] = Object.create(null)\n\n // If it doesn't exist, then just mark the lack of results\n if (!exists)\n return\n\n if (prefix && isAbsolute(prefix) && !this.nomount) {\n var trail = /[\\/\\\\]$/.test(prefix)\n if (prefix.charAt(0) === '/') {\n prefix = path.join(this.root, prefix)\n } else {\n prefix = path.resolve(this.root, prefix)\n if (trail)\n prefix += '/'\n }\n }\n\n if (process.platform === 'win32')\n prefix = prefix.replace(/\\\\/g, '/')\n\n // Mark this as a match\n this._emitMatch(index, prefix)\n}\n\n// Returns either 'DIR', 'FILE', or false\nGlobSync.prototype._stat = function (f) {\n var abs = this._makeAbs(f)\n var needDir = f.slice(-1) === '/'\n\n if (f.length > this.maxLength)\n return false\n\n if (!this.stat && ownProp(this.cache, abs)) {\n var c = this.cache[abs]\n\n if (Array.isArray(c))\n c = 'DIR'\n\n // It exists, but maybe not how we need it\n if (!needDir || c === 'DIR')\n return c\n\n if (needDir && c === 'FILE')\n return false\n\n // otherwise we have to stat, because maybe c=true\n // if we know it exists, but not what it is.\n }\n\n var exists\n var stat = this.statCache[abs]\n if (!stat) {\n var lstat\n try {\n lstat = fs.lstatSync(abs)\n } catch (er) {\n if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {\n this.statCache[abs] = false\n return false\n }\n }\n\n if (lstat && lstat.isSymbolicLink()) {\n try {\n stat = fs.statSync(abs)\n } catch (er) {\n stat = lstat\n }\n } else {\n stat = lstat\n }\n }\n\n this.statCache[abs] = stat\n\n var c = true\n if (stat)\n c = stat.isDirectory() ? 'DIR' : 'FILE'\n\n this.cache[abs] = this.cache[abs] || c\n\n if (needDir && c === 'FILE')\n return false\n\n return c\n}\n\nGlobSync.prototype._mark = function (p) {\n return common.mark(this, p)\n}\n\nGlobSync.prototype._makeAbs = function (f) {\n return common.makeAbs(this, f)\n}\n","// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n","var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n","var wrappy = require('wrappy')\nvar reqs = Object.create(null)\nvar once = require('once')\n\nmodule.exports = wrappy(inflight)\n\nfunction inflight (key, cb) {\n if (reqs[key]) {\n reqs[key].push(cb)\n return null\n } else {\n reqs[key] = [cb]\n return makeres(key)\n }\n}\n\nfunction makeres (key) {\n return once(function RES () {\n var cbs = reqs[key]\n var len = cbs.length\n var args = slice(arguments)\n\n // XXX It's somewhat ambiguous whether a new callback added in this\n // pass should be queued for later execution if something in the\n // list of callbacks throws, or if it should just be discarded.\n // However, it's such an edge case that it hardly matters, and either\n // choice is likely as surprising as the other.\n // As it happens, we do go ahead and schedule it for later execution.\n try {\n for (var i = 0; i < len; i++) {\n cbs[i].apply(null, args)\n }\n } finally {\n if (cbs.length > len) {\n // added more in the interim.\n // de-zalgo, just in case, but don't call again.\n cbs.splice(0, len)\n process.nextTick(function () {\n RES.apply(null, args)\n })\n } else {\n delete reqs[key]\n }\n }\n })\n}\n\nfunction slice (args) {\n var length = args.length\n var array = []\n\n for (var i = 0; i < length; i++) array[i] = args[i]\n return array\n}\n","// Approach:\n//\n// 1. Get the minimatch set\n// 2. For each pattern in the set, PROCESS(pattern, false)\n// 3. Store matches per-set, then uniq them\n//\n// PROCESS(pattern, inGlobStar)\n// Get the first [n] items from pattern that are all strings\n// Join these together. This is PREFIX.\n// If there is no more remaining, then stat(PREFIX) and\n// add to matches if it succeeds. END.\n//\n// If inGlobStar and PREFIX is symlink and points to dir\n// set ENTRIES = []\n// else readdir(PREFIX) as ENTRIES\n// If fail, END\n//\n// with ENTRIES\n// If pattern[n] is GLOBSTAR\n// // handle the case where the globstar match is empty\n// // by pruning it out, and testing the resulting pattern\n// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)\n// // handle other cases.\n// for ENTRY in ENTRIES (not dotfiles)\n// // attach globstar + tail onto the entry\n// // Mark that this entry is a globstar match\n// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)\n//\n// else // not globstar\n// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)\n// Test ENTRY against pattern[n]\n// If fails, continue\n// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])\n//\n// Caveat:\n// Cache all stats and readdirs results to minimize syscall. Since all\n// we ever care about is existence and directory-ness, we can just keep\n// `true` for files, and [children,...] for directories, or `false` for\n// things that don't exist.\n\nmodule.exports = glob\n\nvar fs = require('fs')\nvar rp = require('fs.realpath')\nvar minimatch = require('minimatch')\nvar Minimatch = minimatch.Minimatch\nvar inherits = require('inherits')\nvar EE = require('events').EventEmitter\nvar path = require('path')\nvar assert = require('assert')\nvar isAbsolute = require('path-is-absolute')\nvar globSync = require('./sync.js')\nvar common = require('./common.js')\nvar setopts = common.setopts\nvar ownProp = common.ownProp\nvar inflight = require('inflight')\nvar util = require('util')\nvar childrenIgnored = common.childrenIgnored\nvar isIgnored = common.isIgnored\n\nvar once = require('once')\n\nfunction glob (pattern, options, cb) {\n if (typeof options === 'function') cb = options, options = {}\n if (!options) options = {}\n\n if (options.sync) {\n if (cb)\n throw new TypeError('callback provided to sync glob')\n return globSync(pattern, options)\n }\n\n return new Glob(pattern, options, cb)\n}\n\nglob.sync = globSync\nvar GlobSync = glob.GlobSync = globSync.GlobSync\n\n// old api surface\nglob.glob = glob\n\nfunction extend (origin, add) {\n if (add === null || typeof add !== 'object') {\n return origin\n }\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\nglob.hasMagic = function (pattern, options_) {\n var options = extend({}, options_)\n options.noprocess = true\n\n var g = new Glob(pattern, options)\n var set = g.minimatch.set\n\n if (!pattern)\n return false\n\n if (set.length > 1)\n return true\n\n for (var j = 0; j < set[0].length; j++) {\n if (typeof set[0][j] !== 'string')\n return true\n }\n\n return false\n}\n\nglob.Glob = Glob\ninherits(Glob, EE)\nfunction Glob (pattern, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = null\n }\n\n if (options && options.sync) {\n if (cb)\n throw new TypeError('callback provided to sync glob')\n return new GlobSync(pattern, options)\n }\n\n if (!(this instanceof Glob))\n return new Glob(pattern, options, cb)\n\n setopts(this, pattern, options)\n this._didRealPath = false\n\n // process each pattern in the minimatch set\n var n = this.minimatch.set.length\n\n // The matches are stored as {: true,...} so that\n // duplicates are automagically pruned.\n // Later, we do an Object.keys() on these.\n // Keep them as a list so we can fill in when nonull is set.\n this.matches = new Array(n)\n\n if (typeof cb === 'function') {\n cb = once(cb)\n this.on('error', cb)\n this.on('end', function (matches) {\n cb(null, matches)\n })\n }\n\n var self = this\n this._processing = 0\n\n this._emitQueue = []\n this._processQueue = []\n this.paused = false\n\n if (this.noprocess)\n return this\n\n if (n === 0)\n return done()\n\n var sync = true\n for (var i = 0; i < n; i ++) {\n this._process(this.minimatch.set[i], i, false, done)\n }\n sync = false\n\n function done () {\n --self._processing\n if (self._processing <= 0) {\n if (sync) {\n process.nextTick(function () {\n self._finish()\n })\n } else {\n self._finish()\n }\n }\n }\n}\n\nGlob.prototype._finish = function () {\n assert(this instanceof Glob)\n if (this.aborted)\n return\n\n if (this.realpath && !this._didRealpath)\n return this._realpath()\n\n common.finish(this)\n this.emit('end', this.found)\n}\n\nGlob.prototype._realpath = function () {\n if (this._didRealpath)\n return\n\n this._didRealpath = true\n\n var n = this.matches.length\n if (n === 0)\n return this._finish()\n\n var self = this\n for (var i = 0; i < this.matches.length; i++)\n this._realpathSet(i, next)\n\n function next () {\n if (--n === 0)\n self._finish()\n }\n}\n\nGlob.prototype._realpathSet = function (index, cb) {\n var matchset = this.matches[index]\n if (!matchset)\n return cb()\n\n var found = Object.keys(matchset)\n var self = this\n var n = found.length\n\n if (n === 0)\n return cb()\n\n var set = this.matches[index] = Object.create(null)\n found.forEach(function (p, i) {\n // If there's a problem with the stat, then it means that\n // one or more of the links in the realpath couldn't be\n // resolved. just return the abs value in that case.\n p = self._makeAbs(p)\n rp.realpath(p, self.realpathCache, function (er, real) {\n if (!er)\n set[real] = true\n else if (er.syscall === 'stat')\n set[p] = true\n else\n self.emit('error', er) // srsly wtf right here\n\n if (--n === 0) {\n self.matches[index] = set\n cb()\n }\n })\n })\n}\n\nGlob.prototype._mark = function (p) {\n return common.mark(this, p)\n}\n\nGlob.prototype._makeAbs = function (f) {\n return common.makeAbs(this, f)\n}\n\nGlob.prototype.abort = function () {\n this.aborted = true\n this.emit('abort')\n}\n\nGlob.prototype.pause = function () {\n if (!this.paused) {\n this.paused = true\n this.emit('pause')\n }\n}\n\nGlob.prototype.resume = function () {\n if (this.paused) {\n this.emit('resume')\n this.paused = false\n if (this._emitQueue.length) {\n var eq = this._emitQueue.slice(0)\n this._emitQueue.length = 0\n for (var i = 0; i < eq.length; i ++) {\n var e = eq[i]\n this._emitMatch(e[0], e[1])\n }\n }\n if (this._processQueue.length) {\n var pq = this._processQueue.slice(0)\n this._processQueue.length = 0\n for (var i = 0; i < pq.length; i ++) {\n var p = pq[i]\n this._processing--\n this._process(p[0], p[1], p[2], p[3])\n }\n }\n }\n}\n\nGlob.prototype._process = function (pattern, index, inGlobStar, cb) {\n assert(this instanceof Glob)\n assert(typeof cb === 'function')\n\n if (this.aborted)\n return\n\n this._processing++\n if (this.paused) {\n this._processQueue.push([pattern, index, inGlobStar, cb])\n return\n }\n\n //console.error('PROCESS %d', this._processing, pattern)\n\n // Get the first [n] parts of pattern that are all strings.\n var n = 0\n while (typeof pattern[n] === 'string') {\n n ++\n }\n // now n is the index of the first one that is *not* a string.\n\n // see if there's anything else\n var prefix\n switch (n) {\n // if not, then this is rather simple\n case pattern.length:\n this._processSimple(pattern.join('/'), index, cb)\n return\n\n case 0:\n // pattern *starts* with some non-trivial item.\n // going to readdir(cwd), but not include the prefix in matches.\n prefix = null\n break\n\n default:\n // pattern has some string bits in the front.\n // whatever it starts with, whether that's 'absolute' like /foo/bar,\n // or 'relative' like '../baz'\n prefix = pattern.slice(0, n).join('/')\n break\n }\n\n var remain = pattern.slice(n)\n\n // get the list of entries.\n var read\n if (prefix === null)\n read = '.'\n else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {\n if (!prefix || !isAbsolute(prefix))\n prefix = '/' + prefix\n read = prefix\n } else\n read = prefix\n\n var abs = this._makeAbs(read)\n\n //if ignored, skip _processing\n if (childrenIgnored(this, read))\n return cb()\n\n var isGlobStar = remain[0] === minimatch.GLOBSTAR\n if (isGlobStar)\n this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)\n else\n this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)\n}\n\nGlob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {\n var self = this\n this._readdir(abs, inGlobStar, function (er, entries) {\n return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)\n })\n}\n\nGlob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {\n\n // if the abs isn't a dir, then nothing can match!\n if (!entries)\n return cb()\n\n // It will only match dot entries if it starts with a dot, or if\n // dot is set. Stuff like @(.foo|.bar) isn't allowed.\n var pn = remain[0]\n var negate = !!this.minimatch.negate\n var rawGlob = pn._glob\n var dotOk = this.dot || rawGlob.charAt(0) === '.'\n\n var matchedEntries = []\n for (var i = 0; i < entries.length; i++) {\n var e = entries[i]\n if (e.charAt(0) !== '.' || dotOk) {\n var m\n if (negate && !prefix) {\n m = !e.match(pn)\n } else {\n m = e.match(pn)\n }\n if (m)\n matchedEntries.push(e)\n }\n }\n\n //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)\n\n var len = matchedEntries.length\n // If there are no matched entries, then nothing matches.\n if (len === 0)\n return cb()\n\n // if this is the last remaining pattern bit, then no need for\n // an additional stat *unless* the user has specified mark or\n // stat explicitly. We know they exist, since readdir returned\n // them.\n\n if (remain.length === 1 && !this.mark && !this.stat) {\n if (!this.matches[index])\n this.matches[index] = Object.create(null)\n\n for (var i = 0; i < len; i ++) {\n var e = matchedEntries[i]\n if (prefix) {\n if (prefix !== '/')\n e = prefix + '/' + e\n else\n e = prefix + e\n }\n\n if (e.charAt(0) === '/' && !this.nomount) {\n e = path.join(this.root, e)\n }\n this._emitMatch(index, e)\n }\n // This was the last one, and no stats were needed\n return cb()\n }\n\n // now test all matched entries as stand-ins for that part\n // of the pattern.\n remain.shift()\n for (var i = 0; i < len; i ++) {\n var e = matchedEntries[i]\n var newPattern\n if (prefix) {\n if (prefix !== '/')\n e = prefix + '/' + e\n else\n e = prefix + e\n }\n this._process([e].concat(remain), index, inGlobStar, cb)\n }\n cb()\n}\n\nGlob.prototype._emitMatch = function (index, e) {\n if (this.aborted)\n return\n\n if (isIgnored(this, e))\n return\n\n if (this.paused) {\n this._emitQueue.push([index, e])\n return\n }\n\n var abs = isAbsolute(e) ? e : this._makeAbs(e)\n\n if (this.mark)\n e = this._mark(e)\n\n if (this.absolute)\n e = abs\n\n if (this.matches[index][e])\n return\n\n if (this.nodir) {\n var c = this.cache[abs]\n if (c === 'DIR' || Array.isArray(c))\n return\n }\n\n this.matches[index][e] = true\n\n var st = this.statCache[abs]\n if (st)\n this.emit('stat', e, st)\n\n this.emit('match', e)\n}\n\nGlob.prototype._readdirInGlobStar = function (abs, cb) {\n if (this.aborted)\n return\n\n // follow all symlinked directories forever\n // just proceed as if this is a non-globstar situation\n if (this.follow)\n return this._readdir(abs, false, cb)\n\n var lstatkey = 'lstat\\0' + abs\n var self = this\n var lstatcb = inflight(lstatkey, lstatcb_)\n\n if (lstatcb)\n fs.lstat(abs, lstatcb)\n\n function lstatcb_ (er, lstat) {\n if (er && er.code === 'ENOENT')\n return cb()\n\n var isSym = lstat && lstat.isSymbolicLink()\n self.symlinks[abs] = isSym\n\n // If it's not a symlink or a dir, then it's definitely a regular file.\n // don't bother doing a readdir in that case.\n if (!isSym && lstat && !lstat.isDirectory()) {\n self.cache[abs] = 'FILE'\n cb()\n } else\n self._readdir(abs, false, cb)\n }\n}\n\nGlob.prototype._readdir = function (abs, inGlobStar, cb) {\n if (this.aborted)\n return\n\n cb = inflight('readdir\\0'+abs+'\\0'+inGlobStar, cb)\n if (!cb)\n return\n\n //console.error('RD %j %j', +inGlobStar, abs)\n if (inGlobStar && !ownProp(this.symlinks, abs))\n return this._readdirInGlobStar(abs, cb)\n\n if (ownProp(this.cache, abs)) {\n var c = this.cache[abs]\n if (!c || c === 'FILE')\n return cb()\n\n if (Array.isArray(c))\n return cb(null, c)\n }\n\n var self = this\n fs.readdir(abs, readdirCb(this, abs, cb))\n}\n\nfunction readdirCb (self, abs, cb) {\n return function (er, entries) {\n if (er)\n self._readdirError(abs, er, cb)\n else\n self._readdirEntries(abs, entries, cb)\n }\n}\n\nGlob.prototype._readdirEntries = function (abs, entries, cb) {\n if (this.aborted)\n return\n\n // if we haven't asked to stat everything, then just\n // assume that everything in there exists, so we can avoid\n // having to stat it a second time.\n if (!this.mark && !this.stat) {\n for (var i = 0; i < entries.length; i ++) {\n var e = entries[i]\n if (abs === '/')\n e = abs + e\n else\n e = abs + '/' + e\n this.cache[e] = true\n }\n }\n\n this.cache[abs] = entries\n return cb(null, entries)\n}\n\nGlob.prototype._readdirError = function (f, er, cb) {\n if (this.aborted)\n return\n\n // handle errors, and cache the information\n switch (er.code) {\n case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205\n case 'ENOTDIR': // totally normal. means it *does* exist.\n var abs = this._makeAbs(f)\n this.cache[abs] = 'FILE'\n if (abs === this.cwdAbs) {\n var error = new Error(er.code + ' invalid cwd ' + this.cwd)\n error.path = this.cwd\n error.code = er.code\n this.emit('error', error)\n this.abort()\n }\n break\n\n case 'ENOENT': // not terribly unusual\n case 'ELOOP':\n case 'ENAMETOOLONG':\n case 'UNKNOWN':\n this.cache[this._makeAbs(f)] = false\n break\n\n default: // some unusual error. Treat as failure.\n this.cache[this._makeAbs(f)] = false\n if (this.strict) {\n this.emit('error', er)\n // If the error is handled, then we abort\n // if not, we threw out of here\n this.abort()\n }\n if (!this.silent)\n console.error('glob error', er)\n break\n }\n\n return cb()\n}\n\nGlob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {\n var self = this\n this._readdir(abs, inGlobStar, function (er, entries) {\n self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)\n })\n}\n\n\nGlob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {\n //console.error('pgs2', prefix, remain[0], entries)\n\n // no entries means not a dir, so it can never have matches\n // foo.txt/** doesn't match foo.txt\n if (!entries)\n return cb()\n\n // test without the globstar, and with every child both below\n // and replacing the globstar.\n var remainWithoutGlobStar = remain.slice(1)\n var gspref = prefix ? [ prefix ] : []\n var noGlobStar = gspref.concat(remainWithoutGlobStar)\n\n // the noGlobStar pattern exits the inGlobStar state\n this._process(noGlobStar, index, false, cb)\n\n var isSym = this.symlinks[abs]\n var len = entries.length\n\n // If it's a symlink, and we're in a globstar, then stop\n if (isSym && inGlobStar)\n return cb()\n\n for (var i = 0; i < len; i++) {\n var e = entries[i]\n if (e.charAt(0) === '.' && !this.dot)\n continue\n\n // these two cases enter the inGlobStar state\n var instead = gspref.concat(entries[i], remainWithoutGlobStar)\n this._process(instead, index, true, cb)\n\n var below = gspref.concat(entries[i], remain)\n this._process(below, index, true, cb)\n }\n\n cb()\n}\n\nGlob.prototype._processSimple = function (prefix, index, cb) {\n // XXX review this. Shouldn't it be doing the mounting etc\n // before doing stat? kinda weird?\n var self = this\n this._stat(prefix, function (er, exists) {\n self._processSimple2(prefix, index, er, exists, cb)\n })\n}\nGlob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {\n\n //console.error('ps2', prefix, exists)\n\n if (!this.matches[index])\n this.matches[index] = Object.create(null)\n\n // If it doesn't exist, then just mark the lack of results\n if (!exists)\n return cb()\n\n if (prefix && isAbsolute(prefix) && !this.nomount) {\n var trail = /[\\/\\\\]$/.test(prefix)\n if (prefix.charAt(0) === '/') {\n prefix = path.join(this.root, prefix)\n } else {\n prefix = path.resolve(this.root, prefix)\n if (trail)\n prefix += '/'\n }\n }\n\n if (process.platform === 'win32')\n prefix = prefix.replace(/\\\\/g, '/')\n\n // Mark this as a match\n this._emitMatch(index, prefix)\n cb()\n}\n\n// Returns either 'DIR', 'FILE', or false\nGlob.prototype._stat = function (f, cb) {\n var abs = this._makeAbs(f)\n var needDir = f.slice(-1) === '/'\n\n if (f.length > this.maxLength)\n return cb()\n\n if (!this.stat && ownProp(this.cache, abs)) {\n var c = this.cache[abs]\n\n if (Array.isArray(c))\n c = 'DIR'\n\n // It exists, but maybe not how we need it\n if (!needDir || c === 'DIR')\n return cb(null, c)\n\n if (needDir && c === 'FILE')\n return cb()\n\n // otherwise we have to stat, because maybe c=true\n // if we know it exists, but not what it is.\n }\n\n var exists\n var stat = this.statCache[abs]\n if (stat !== undefined) {\n if (stat === false)\n return cb(null, stat)\n else {\n var type = stat.isDirectory() ? 'DIR' : 'FILE'\n if (needDir && type === 'FILE')\n return cb()\n else\n return cb(null, type, stat)\n }\n }\n\n var self = this\n var statcb = inflight('stat\\0' + abs, lstatcb_)\n if (statcb)\n fs.lstat(abs, statcb)\n\n function lstatcb_ (er, lstat) {\n if (lstat && lstat.isSymbolicLink()) {\n // If it's a symlink, then treat it as the target, unless\n // the target does not exist, then treat it as a file.\n return fs.stat(abs, function (er, stat) {\n if (er)\n self._stat2(f, abs, null, lstat, cb)\n else\n self._stat2(f, abs, er, stat, cb)\n })\n } else {\n self._stat2(f, abs, er, lstat, cb)\n }\n }\n}\n\nGlob.prototype._stat2 = function (f, abs, er, stat, cb) {\n if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {\n this.statCache[abs] = false\n return cb()\n }\n\n var needDir = f.slice(-1) === '/'\n this.statCache[abs] = stat\n\n if (abs.slice(-1) === '/' && stat && !stat.isDirectory())\n return cb(null, false, stat)\n\n var c = true\n if (stat)\n c = stat.isDirectory() ? 'DIR' : 'FILE'\n this.cache[abs] = this.cache[abs] || c\n\n if (needDir && c === 'FILE')\n return cb()\n\n return cb(null, c, stat)\n}\n","// @ts-check\n/** @typedef { import('estree').BaseNode} BaseNode */\n\n/** @typedef {{\n\tskip: () => void;\n\tremove: () => void;\n\treplace: (node: BaseNode) => void;\n}} WalkerContext */\n\nclass WalkerBase {\n\tconstructor() {\n\t\t/** @type {boolean} */\n\t\tthis.should_skip = false;\n\n\t\t/** @type {boolean} */\n\t\tthis.should_remove = false;\n\n\t\t/** @type {BaseNode | null} */\n\t\tthis.replacement = null;\n\n\t\t/** @type {WalkerContext} */\n\t\tthis.context = {\n\t\t\tskip: () => (this.should_skip = true),\n\t\t\tremove: () => (this.should_remove = true),\n\t\t\treplace: (node) => (this.replacement = node)\n\t\t};\n\t}\n\n\t/**\n\t *\n\t * @param {any} parent\n\t * @param {string} prop\n\t * @param {number} index\n\t * @param {BaseNode} node\n\t */\n\treplace(parent, prop, index, node) {\n\t\tif (parent) {\n\t\t\tif (index !== null) {\n\t\t\t\tparent[prop][index] = node;\n\t\t\t} else {\n\t\t\t\tparent[prop] = node;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t *\n\t * @param {any} parent\n\t * @param {string} prop\n\t * @param {number} index\n\t */\n\tremove(parent, prop, index) {\n\t\tif (parent) {\n\t\t\tif (index !== null) {\n\t\t\t\tparent[prop].splice(index, 1);\n\t\t\t} else {\n\t\t\t\tdelete parent[prop];\n\t\t\t}\n\t\t}\n\t}\n}\n\n// @ts-check\n\n/** @typedef { import('estree').BaseNode} BaseNode */\n/** @typedef { import('./walker.js').WalkerContext} WalkerContext */\n\n/** @typedef {(\n * this: WalkerContext,\n * node: BaseNode,\n * parent: BaseNode,\n * key: string,\n * index: number\n * ) => void} SyncHandler */\n\nclass SyncWalker extends WalkerBase {\n\t/**\n\t *\n\t * @param {SyncHandler} enter\n\t * @param {SyncHandler} leave\n\t */\n\tconstructor(enter, leave) {\n\t\tsuper();\n\n\t\t/** @type {SyncHandler} */\n\t\tthis.enter = enter;\n\n\t\t/** @type {SyncHandler} */\n\t\tthis.leave = leave;\n\t}\n\n\t/**\n\t *\n\t * @param {BaseNode} node\n\t * @param {BaseNode} parent\n\t * @param {string} [prop]\n\t * @param {number} [index]\n\t * @returns {BaseNode}\n\t */\n\tvisit(node, parent, prop, index) {\n\t\tif (node) {\n\t\t\tif (this.enter) {\n\t\t\t\tconst _should_skip = this.should_skip;\n\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\tthis.should_skip = false;\n\t\t\t\tthis.should_remove = false;\n\t\t\t\tthis.replacement = null;\n\n\t\t\t\tthis.enter.call(this.context, node, parent, prop, index);\n\n\t\t\t\tif (this.replacement) {\n\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t}\n\n\t\t\t\tif (this.should_remove) {\n\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t}\n\n\t\t\t\tconst skipped = this.should_skip;\n\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\tthis.should_skip = _should_skip;\n\t\t\t\tthis.should_remove = _should_remove;\n\t\t\t\tthis.replacement = _replacement;\n\n\t\t\t\tif (skipped) return node;\n\t\t\t\tif (removed) return null;\n\t\t\t}\n\n\t\t\tfor (const key in node) {\n\t\t\t\tconst value = node[key];\n\n\t\t\t\tif (typeof value !== \"object\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (Array.isArray(value)) {\n\t\t\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\t\t\tif (value[i] !== null && typeof value[i].type === 'string') {\n\t\t\t\t\t\t\tif (!this.visit(value[i], node, key, i)) {\n\t\t\t\t\t\t\t\t// removed\n\t\t\t\t\t\t\t\ti--;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (value !== null && typeof value.type === \"string\") {\n\t\t\t\t\tthis.visit(value, node, key, null);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.leave) {\n\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\tthis.replacement = null;\n\t\t\t\tthis.should_remove = false;\n\n\t\t\t\tthis.leave.call(this.context, node, parent, prop, index);\n\n\t\t\t\tif (this.replacement) {\n\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t}\n\n\t\t\t\tif (this.should_remove) {\n\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t}\n\n\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\tthis.replacement = _replacement;\n\t\t\t\tthis.should_remove = _should_remove;\n\n\t\t\t\tif (removed) return null;\n\t\t\t}\n\t\t}\n\n\t\treturn node;\n\t}\n}\n\n// @ts-check\n\n/** @typedef { import('estree').BaseNode} BaseNode */\n/** @typedef { import('./walker').WalkerContext} WalkerContext */\n\n/** @typedef {(\n * this: WalkerContext,\n * node: BaseNode,\n * parent: BaseNode,\n * key: string,\n * index: number\n * ) => Promise} AsyncHandler */\n\nclass AsyncWalker extends WalkerBase {\n\t/**\n\t *\n\t * @param {AsyncHandler} enter\n\t * @param {AsyncHandler} leave\n\t */\n\tconstructor(enter, leave) {\n\t\tsuper();\n\n\t\t/** @type {AsyncHandler} */\n\t\tthis.enter = enter;\n\n\t\t/** @type {AsyncHandler} */\n\t\tthis.leave = leave;\n\t}\n\n\t/**\n\t *\n\t * @param {BaseNode} node\n\t * @param {BaseNode} parent\n\t * @param {string} [prop]\n\t * @param {number} [index]\n\t * @returns {Promise}\n\t */\n\tasync visit(node, parent, prop, index) {\n\t\tif (node) {\n\t\t\tif (this.enter) {\n\t\t\t\tconst _should_skip = this.should_skip;\n\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\tthis.should_skip = false;\n\t\t\t\tthis.should_remove = false;\n\t\t\t\tthis.replacement = null;\n\n\t\t\t\tawait this.enter.call(this.context, node, parent, prop, index);\n\n\t\t\t\tif (this.replacement) {\n\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t}\n\n\t\t\t\tif (this.should_remove) {\n\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t}\n\n\t\t\t\tconst skipped = this.should_skip;\n\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\tthis.should_skip = _should_skip;\n\t\t\t\tthis.should_remove = _should_remove;\n\t\t\t\tthis.replacement = _replacement;\n\n\t\t\t\tif (skipped) return node;\n\t\t\t\tif (removed) return null;\n\t\t\t}\n\n\t\t\tfor (const key in node) {\n\t\t\t\tconst value = node[key];\n\n\t\t\t\tif (typeof value !== \"object\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (Array.isArray(value)) {\n\t\t\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\t\t\tif (value[i] !== null && typeof value[i].type === 'string') {\n\t\t\t\t\t\t\tif (!(await this.visit(value[i], node, key, i))) {\n\t\t\t\t\t\t\t\t// removed\n\t\t\t\t\t\t\t\ti--;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (value !== null && typeof value.type === \"string\") {\n\t\t\t\t\tawait this.visit(value, node, key, null);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.leave) {\n\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\tthis.replacement = null;\n\t\t\t\tthis.should_remove = false;\n\n\t\t\t\tawait this.leave.call(this.context, node, parent, prop, index);\n\n\t\t\t\tif (this.replacement) {\n\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t}\n\n\t\t\t\tif (this.should_remove) {\n\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t}\n\n\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\tthis.replacement = _replacement;\n\t\t\t\tthis.should_remove = _should_remove;\n\n\t\t\t\tif (removed) return null;\n\t\t\t}\n\t\t}\n\n\t\treturn node;\n\t}\n}\n\n// @ts-check\n\n/** @typedef { import('estree').BaseNode} BaseNode */\n/** @typedef { import('./sync.js').SyncHandler} SyncHandler */\n/** @typedef { import('./async.js').AsyncHandler} AsyncHandler */\n\n/**\n *\n * @param {BaseNode} ast\n * @param {{\n * enter?: SyncHandler\n * leave?: SyncHandler\n * }} walker\n * @returns {BaseNode}\n */\nfunction walk(ast, { enter, leave }) {\n\tconst instance = new SyncWalker(enter, leave);\n\treturn instance.visit(ast, null);\n}\n\n/**\n *\n * @param {BaseNode} ast\n * @param {{\n * enter?: AsyncHandler\n * leave?: AsyncHandler\n * }} walker\n * @returns {Promise}\n */\nasync function asyncWalk(ast, { enter, leave }) {\n\tconst instance = new AsyncWalker(enter, leave);\n\treturn await instance.visit(ast, null);\n}\n\nexport { asyncWalk, walk };\n","function isReference(node, parent) {\n if (node.type === 'MemberExpression') {\n return !node.computed && isReference(node.object, node);\n }\n if (node.type === 'Identifier') {\n if (!parent)\n return true;\n switch (parent.type) {\n // disregard `bar` in `foo.bar`\n case 'MemberExpression': return parent.computed || node === parent.object;\n // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`\n case 'MethodDefinition': return parent.computed;\n // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`\n case 'FieldDefinition': return parent.computed || node === parent.value;\n // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`\n case 'Property': return parent.computed || node === parent.value;\n // disregard the `bar` in `export { foo as bar }` or\n // the foo in `import { foo as bar }`\n case 'ExportSpecifier':\n case 'ImportSpecifier': return node === parent.local;\n // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`\n case 'LabeledStatement':\n case 'BreakStatement':\n case 'ContinueStatement': return false;\n default: return true;\n }\n }\n return false;\n}\n\nexport default isReference;\n","import { basename, extname, dirname, join, resolve, sep } from 'path';\nimport { makeLegalIdentifier, attachScopes, extractAssignedNames, createFilter } from '@rollup/pluginutils';\nimport getCommonDir from 'commondir';\nimport { existsSync, readFileSync, statSync } from 'fs';\nimport glob from 'glob';\nimport { walk } from 'estree-walker';\nimport MagicString from 'magic-string';\nimport isReference from 'is-reference';\nimport { sync } from 'resolve';\n\nvar peerDependencies = {\n\trollup: \"^2.38.3\"\n};\n\nfunction tryParse(parse, code, id) {\n try {\n return parse(code, { allowReturnOutsideFunction: true });\n } catch (err) {\n err.message += ` in ${id}`;\n throw err;\n }\n}\n\nconst firstpassGlobal = /\\b(?:require|module|exports|global)\\b/;\n\nconst firstpassNoGlobal = /\\b(?:require|module|exports)\\b/;\n\nfunction hasCjsKeywords(code, ignoreGlobal) {\n const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;\n return firstpass.test(code);\n}\n\n/* eslint-disable no-underscore-dangle */\n\nfunction analyzeTopLevelStatements(parse, code, id) {\n const ast = tryParse(parse, code, id);\n\n let isEsModule = false;\n let hasDefaultExport = false;\n let hasNamedExports = false;\n\n for (const node of ast.body) {\n switch (node.type) {\n case 'ExportDefaultDeclaration':\n isEsModule = true;\n hasDefaultExport = true;\n break;\n case 'ExportNamedDeclaration':\n isEsModule = true;\n if (node.declaration) {\n hasNamedExports = true;\n } else {\n for (const specifier of node.specifiers) {\n if (specifier.exported.name === 'default') {\n hasDefaultExport = true;\n } else {\n hasNamedExports = true;\n }\n }\n }\n break;\n case 'ExportAllDeclaration':\n isEsModule = true;\n if (node.exported && node.exported.name === 'default') {\n hasDefaultExport = true;\n } else {\n hasNamedExports = true;\n }\n break;\n case 'ImportDeclaration':\n isEsModule = true;\n break;\n }\n }\n\n return { isEsModule, hasDefaultExport, hasNamedExports, ast };\n}\n\nconst isWrappedId = (id, suffix) => id.endsWith(suffix);\nconst wrapId = (id, suffix) => `\\0${id}${suffix}`;\nconst unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);\n\nconst PROXY_SUFFIX = '?commonjs-proxy';\nconst REQUIRE_SUFFIX = '?commonjs-require';\nconst EXTERNAL_SUFFIX = '?commonjs-external';\nconst EXPORTS_SUFFIX = '?commonjs-exports';\nconst MODULE_SUFFIX = '?commonjs-module';\n\nconst DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';\nconst DYNAMIC_JSON_PREFIX = '\\0commonjs-dynamic-json:';\nconst DYNAMIC_PACKAGES_ID = '\\0commonjs-dynamic-packages';\n\nconst HELPERS_ID = '\\0commonjsHelpers.js';\n\n// `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.\n// Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.\n// This will no longer be necessary once Rollup switches to ES6 output, likely\n// in Rollup 3\n\nconst HELPERS = `\nexport var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nexport function getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nexport function getDefaultExportFromNamespaceIfPresent (n) {\n\treturn n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;\n}\n\nexport function getDefaultExportFromNamespaceIfNotNamed (n) {\n\treturn n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;\n}\n\nexport function getAugmentedNamespace(n) {\n\tif (n.__esModule) return n;\n\tvar a = Object.defineProperty({}, '__esModule', {value: true});\n\tObject.keys(n).forEach(function (k) {\n\t\tvar d = Object.getOwnPropertyDescriptor(n, k);\n\t\tObject.defineProperty(a, k, d.get ? d : {\n\t\t\tenumerable: true,\n\t\t\tget: function () {\n\t\t\t\treturn n[k];\n\t\t\t}\n\t\t});\n\t});\n\treturn a;\n}\n`;\n\nconst FAILED_REQUIRE_ERROR = `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.');`;\n\nconst HELPER_NON_DYNAMIC = `\nexport function commonjsRequire (path) {\n\t${FAILED_REQUIRE_ERROR}\n}\n`;\n\nconst getDynamicHelpers = (ignoreDynamicRequires) => `\nexport function createModule(modulePath) {\n\treturn {\n\t\tpath: modulePath,\n\t\texports: {},\n\t\trequire: function (path, base) {\n\t\t\treturn commonjsRequire(path, base == null ? modulePath : base);\n\t\t}\n\t};\n}\n\nexport function commonjsRegister (path, loader) {\n\tDYNAMIC_REQUIRE_LOADERS[path] = loader;\n}\n\nexport function commonjsRegisterOrShort (path, to) {\n\tconst resolvedPath = commonjsResolveImpl(path, null, true);\n\tif (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {\n\t DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];\n\t} else {\n\t DYNAMIC_REQUIRE_SHORTS[path] = to;\n\t}\n}\n\nconst DYNAMIC_REQUIRE_LOADERS = Object.create(null);\nconst DYNAMIC_REQUIRE_CACHE = Object.create(null);\nconst DYNAMIC_REQUIRE_SHORTS = Object.create(null);\nconst DEFAULT_PARENT_MODULE = {\n\tid: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []\n};\nconst CHECKED_EXTENSIONS = ['', '.js', '.json'];\n\nfunction normalize (path) {\n\tpath = path.replace(/\\\\\\\\/g, '/');\n\tconst parts = path.split('/');\n\tconst slashed = parts[0] === '';\n\tfor (let i = 1; i < parts.length; i++) {\n\t\tif (parts[i] === '.' || parts[i] === '') {\n\t\t\tparts.splice(i--, 1);\n\t\t}\n\t}\n\tfor (let i = 1; i < parts.length; i++) {\n\t\tif (parts[i] !== '..') continue;\n\t\tif (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {\n\t\t\tparts.splice(--i, 2);\n\t\t\ti--;\n\t\t}\n\t}\n\tpath = parts.join('/');\n\tif (slashed && path[0] !== '/')\n\t path = '/' + path;\n\telse if (path.length === 0)\n\t path = '.';\n\treturn path;\n}\n\nfunction join () {\n\tif (arguments.length === 0)\n\t return '.';\n\tlet joined;\n\tfor (let i = 0; i < arguments.length; ++i) {\n\t let arg = arguments[i];\n\t if (arg.length > 0) {\n\t\tif (joined === undefined)\n\t\t joined = arg;\n\t\telse\n\t\t joined += '/' + arg;\n\t }\n\t}\n\tif (joined === undefined)\n\t return '.';\n\n\treturn joined;\n}\n\nfunction isPossibleNodeModulesPath (modulePath) {\n\tlet c0 = modulePath[0];\n\tif (c0 === '/' || c0 === '\\\\\\\\') return false;\n\tlet c1 = modulePath[1], c2 = modulePath[2];\n\tif ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\\\\\')) ||\n\t\t(c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\\\\\'))) return false;\n\tif (c1 === ':' && (c2 === '/' || c2 === '\\\\\\\\'))\n\t\treturn false;\n\treturn true;\n}\n\nfunction dirname (path) {\n if (path.length === 0)\n return '.';\n\n let i = path.length - 1;\n while (i > 0) {\n const c = path.charCodeAt(i);\n if ((c === 47 || c === 92) && i !== path.length - 1)\n break;\n i--;\n }\n\n if (i > 0)\n return path.substr(0, i);\n\n if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)\n return path.charAt(0);\n\n return '.';\n}\n\nexport function commonjsResolveImpl (path, originalModuleDir, testCache) {\n\tconst shouldTryNodeModules = isPossibleNodeModulesPath(path);\n\tpath = normalize(path);\n\tlet relPath;\n\tif (path[0] === '/') {\n\t\toriginalModuleDir = '/';\n\t}\n\twhile (true) {\n\t\tif (!shouldTryNodeModules) {\n\t\t\trelPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;\n\t\t} else if (originalModuleDir) {\n\t\t\trelPath = normalize(originalModuleDir + '/node_modules/' + path);\n\t\t} else {\n\t\t\trelPath = normalize(join('node_modules', path));\n\t\t}\n\n\t\tif (relPath.endsWith('/..')) {\n\t\t\tbreak; // Travelled too far up, avoid infinite loop\n\t\t}\n\n\t\tfor (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {\n\t\t\tconst resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];\n\t\t\tif (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {\n\t\t\t\treturn resolvedPath;\n\t\t\t}\n\t\t\tif (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {\n\t\t\t return resolvedPath;\n\t\t\t}\n\t\t\tif (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {\n\t\t\t\treturn resolvedPath;\n\t\t\t}\n\t\t}\n\t\tif (!shouldTryNodeModules) break;\n\t\tconst nextDir = normalize(originalModuleDir + '/..');\n\t\tif (nextDir === originalModuleDir) break;\n\t\toriginalModuleDir = nextDir;\n\t}\n\treturn null;\n}\n\nexport function commonjsResolve (path, originalModuleDir) {\n\tconst resolvedPath = commonjsResolveImpl(path, originalModuleDir);\n\tif (resolvedPath !== null) {\n\t\treturn resolvedPath;\n\t}\n\treturn require.resolve(path);\n}\n\nexport function commonjsRequire (path, originalModuleDir) {\n\tlet resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);\n\tif (resolvedPath !== null) {\n let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];\n if (cachedModule) return cachedModule.exports;\n let shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];\n if (shortTo) {\n cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];\n if (cachedModule)\n return cachedModule.exports;\n resolvedPath = commonjsResolveImpl(shortTo, null, true);\n }\n const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];\n if (loader) {\n DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {\n id: resolvedPath,\n filename: resolvedPath,\n path: dirname(resolvedPath),\n exports: {},\n parent: DEFAULT_PARENT_MODULE,\n loaded: false,\n children: [],\n paths: [],\n require: function (path, base) {\n return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);\n }\n };\n try {\n loader.call(commonjsGlobal, cachedModule, cachedModule.exports);\n } catch (error) {\n delete DYNAMIC_REQUIRE_CACHE[resolvedPath];\n throw error;\n }\n cachedModule.loaded = true;\n return cachedModule.exports;\n };\n\t}\n\t${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}\n}\n\ncommonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;\ncommonjsRequire.resolve = commonjsResolve;\n`;\n\nfunction getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) {\n return `${HELPERS}${\n isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC\n }`;\n}\n\n/* eslint-disable import/prefer-default-export */\n\nfunction deconflict(scopes, globals, identifier) {\n let i = 1;\n let deconflicted = makeLegalIdentifier(identifier);\n const hasConflicts = () =>\n scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);\n\n while (hasConflicts()) {\n deconflicted = makeLegalIdentifier(`${identifier}_${i}`);\n i += 1;\n }\n\n for (const scope of scopes) {\n scope.declarations[deconflicted] = true;\n }\n\n return deconflicted;\n}\n\nfunction getName(id) {\n const name = makeLegalIdentifier(basename(id, extname(id)));\n if (name !== 'index') {\n return name;\n }\n return makeLegalIdentifier(basename(dirname(id)));\n}\n\nfunction normalizePathSlashes(path) {\n return path.replace(/\\\\/g, '/');\n}\n\nconst VIRTUAL_PATH_BASE = '/$$rollup_base$$';\nconst getVirtualPathForDynamicRequirePath = (path, commonDir) => {\n const normalizedPath = normalizePathSlashes(path);\n return normalizedPath.startsWith(commonDir)\n ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)\n : normalizedPath;\n};\n\nfunction getPackageEntryPoint(dirPath) {\n let entryPoint = 'index.js';\n\n try {\n if (existsSync(join(dirPath, 'package.json'))) {\n entryPoint =\n JSON.parse(readFileSync(join(dirPath, 'package.json'), { encoding: 'utf8' })).main ||\n entryPoint;\n }\n } catch (ignored) {\n // ignored\n }\n\n return entryPoint;\n}\n\nfunction getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {\n let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`;\n for (const dir of dynamicRequireModuleDirPaths) {\n const entryPoint = getPackageEntryPoint(dir);\n\n code += `\\ncommonjsRegisterOrShort(${JSON.stringify(\n getVirtualPathForDynamicRequirePath(dir, commonDir)\n )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(join(dir, entryPoint), commonDir))});`;\n }\n return code;\n}\n\nfunction getDynamicPackagesEntryIntro(\n dynamicRequireModuleDirPaths,\n dynamicRequireModuleSet\n) {\n let dynamicImports = Array.from(\n dynamicRequireModuleSet,\n (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});`\n ).join('\\n');\n\n if (dynamicRequireModuleDirPaths.length) {\n dynamicImports += `require(${JSON.stringify(\n wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX)\n )});`;\n }\n\n return dynamicImports;\n}\n\nfunction isDynamicModuleImport(id, dynamicRequireModuleSet) {\n const normalizedPath = normalizePathSlashes(id);\n return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');\n}\n\nfunction isDirectory(path) {\n try {\n if (statSync(path).isDirectory()) return true;\n } catch (ignored) {\n // Nothing to do here\n }\n return false;\n}\n\nfunction getDynamicRequirePaths(patterns) {\n const dynamicRequireModuleSet = new Set();\n for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {\n const isNegated = pattern.startsWith('!');\n const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);\n for (const path of glob.sync(isNegated ? pattern.substr(1) : pattern)) {\n modifySet(normalizePathSlashes(resolve(path)));\n if (isDirectory(path)) {\n modifySet(normalizePathSlashes(resolve(join(path, getPackageEntryPoint(path)))));\n }\n }\n }\n const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) =>\n isDirectory(path)\n );\n return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };\n}\n\nfunction getCommonJSMetaPromise(commonJSMetaPromises, id) {\n let commonJSMetaPromise = commonJSMetaPromises.get(id);\n if (commonJSMetaPromise) return commonJSMetaPromise.promise;\n\n const promise = new Promise((resolve) => {\n commonJSMetaPromise = {\n resolve,\n promise: null\n };\n commonJSMetaPromises.set(id, commonJSMetaPromise);\n });\n commonJSMetaPromise.promise = promise;\n\n return promise;\n}\n\nfunction setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) {\n const commonJSMetaPromise = commonJSMetaPromises.get(id);\n if (commonJSMetaPromise) {\n if (commonJSMetaPromise.resolve) {\n commonJSMetaPromise.resolve(commonjsMeta);\n commonJSMetaPromise.resolve = null;\n }\n } else {\n commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null });\n }\n}\n\n// e.g. id === \"commonjsHelpers?commonjsRegister\"\nfunction getSpecificHelperProxy(id) {\n return `export {${id.split('?')[1]} as default} from \"${HELPERS_ID}\";`;\n}\n\nfunction getUnknownRequireProxy(id, requireReturnsDefault) {\n if (requireReturnsDefault === true || id.endsWith('.json')) {\n return `export {default} from ${JSON.stringify(id)};`;\n }\n const name = getName(id);\n const exported =\n requireReturnsDefault === 'auto'\n ? `import {getDefaultExportFromNamespaceIfNotNamed} from \"${HELPERS_ID}\"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`\n : requireReturnsDefault === 'preferred'\n ? `import {getDefaultExportFromNamespaceIfPresent} from \"${HELPERS_ID}\"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`\n : !requireReturnsDefault\n ? `import {getAugmentedNamespace} from \"${HELPERS_ID}\"; export default /*@__PURE__*/getAugmentedNamespace(${name});`\n : `export default ${name};`;\n return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;\n}\n\nfunction getDynamicJsonProxy(id, commonDir) {\n const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));\n return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\\ncommonjsRegister(${JSON.stringify(\n getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)\n )}, function (module, exports) {\n module.exports = require(${JSON.stringify(normalizedPath)});\n});`;\n}\n\nfunction getDynamicRequireProxy(normalizedPath, commonDir) {\n return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\\ncommonjsRegister(${JSON.stringify(\n getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)\n )}, function (module, exports) {\n ${readFileSync(normalizedPath, { encoding: 'utf8' })}\n});`;\n}\n\nasync function getStaticRequireProxy(\n id,\n requireReturnsDefault,\n esModulesWithDefaultExport,\n esModulesWithNamedExports,\n commonJsMetaPromises\n) {\n const name = getName(id);\n const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id);\n if (commonjsMeta && commonjsMeta.isCommonJS) {\n return `export { __moduleExports as default } from ${JSON.stringify(id)};`;\n } else if (commonjsMeta === null) {\n return getUnknownRequireProxy(id, requireReturnsDefault);\n } else if (!requireReturnsDefault) {\n return `import { getAugmentedNamespace } from \"${HELPERS_ID}\"; import * as ${name} from ${JSON.stringify(\n id\n )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;\n } else if (\n requireReturnsDefault !== true &&\n (requireReturnsDefault === 'namespace' ||\n !esModulesWithDefaultExport.has(id) ||\n (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))\n ) {\n return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;\n }\n return `export { default } from ${JSON.stringify(id)};`;\n}\n\n/* eslint-disable no-param-reassign, no-undefined */\n\nfunction getCandidatesForExtension(resolved, extension) {\n return [resolved + extension, `${resolved}${sep}index${extension}`];\n}\n\nfunction getCandidates(resolved, extensions) {\n return extensions.reduce(\n (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),\n [resolved]\n );\n}\n\nfunction getResolveId(extensions) {\n function resolveExtensions(importee, importer) {\n // not our problem\n if (importee[0] !== '.' || !importer) return undefined;\n\n const resolved = resolve(dirname(importer), importee);\n const candidates = getCandidates(resolved, extensions);\n\n for (let i = 0; i < candidates.length; i += 1) {\n try {\n const stats = statSync(candidates[i]);\n if (stats.isFile()) return { id: candidates[i] };\n } catch (err) {\n /* noop */\n }\n }\n\n return undefined;\n }\n\n return function resolveId(importee, rawImporter) {\n if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {\n return importee;\n }\n\n const importer =\n rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)\n ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)\n : rawImporter;\n\n // Except for exports, proxies are only importing resolved ids,\n // no need to resolve again\n if (importer && isWrappedId(importer, PROXY_SUFFIX)) {\n return importee;\n }\n\n const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);\n const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);\n let isModuleRegistration = false;\n\n if (isProxyModule) {\n importee = unwrapId(importee, PROXY_SUFFIX);\n } else if (isRequiredModule) {\n importee = unwrapId(importee, REQUIRE_SUFFIX);\n\n isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);\n if (isModuleRegistration) {\n importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);\n }\n }\n\n if (\n importee.startsWith(HELPERS_ID) ||\n importee === DYNAMIC_PACKAGES_ID ||\n importee.startsWith(DYNAMIC_JSON_PREFIX)\n ) {\n return importee;\n }\n\n if (importee.startsWith('\\0')) {\n return null;\n }\n\n return this.resolve(importee, importer, {\n skipSelf: true,\n custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }\n }).then((resolved) => {\n if (!resolved) {\n resolved = resolveExtensions(importee, importer);\n }\n if (resolved && isProxyModule) {\n resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);\n resolved.external = false;\n } else if (resolved && isModuleRegistration) {\n resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);\n } else if (!resolved && (isProxyModule || isRequiredModule)) {\n return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };\n }\n return resolved;\n });\n };\n}\n\nfunction validateRollupVersion(rollupVersion, peerDependencyVersion) {\n const [major, minor] = rollupVersion.split('.').map(Number);\n const versionRegexp = /\\^(\\d+\\.\\d+)\\.\\d+/g;\n let minMajor = Infinity;\n let minMinor = Infinity;\n let foundVersion;\n // eslint-disable-next-line no-cond-assign\n while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {\n const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);\n if (foundMajor < minMajor) {\n minMajor = foundMajor;\n minMinor = foundMinor;\n }\n }\n if (major < minMajor || (major === minMajor && minor < minMinor)) {\n throw new Error(\n `Insufficient Rollup version: \"@rollup/plugin-commonjs\" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`\n );\n }\n}\n\nconst operators = {\n '==': (x) => equals(x.left, x.right, false),\n\n '!=': (x) => not(operators['=='](x)),\n\n '===': (x) => equals(x.left, x.right, true),\n\n '!==': (x) => not(operators['==='](x)),\n\n '!': (x) => isFalsy(x.argument),\n\n '&&': (x) => isTruthy(x.left) && isTruthy(x.right),\n\n '||': (x) => isTruthy(x.left) || isTruthy(x.right)\n};\n\nfunction not(value) {\n return value === null ? value : !value;\n}\n\nfunction equals(a, b, strict) {\n if (a.type !== b.type) return null;\n // eslint-disable-next-line eqeqeq\n if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;\n return null;\n}\n\nfunction isTruthy(node) {\n if (!node) return false;\n if (node.type === 'Literal') return !!node.value;\n if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);\n if (node.operator in operators) return operators[node.operator](node);\n return null;\n}\n\nfunction isFalsy(node) {\n return not(isTruthy(node));\n}\n\nfunction getKeypath(node) {\n const parts = [];\n\n while (node.type === 'MemberExpression') {\n if (node.computed) return null;\n\n parts.unshift(node.property.name);\n // eslint-disable-next-line no-param-reassign\n node = node.object;\n }\n\n if (node.type !== 'Identifier') return null;\n\n const { name } = node;\n parts.unshift(name);\n\n return { name, keypath: parts.join('.') };\n}\n\nconst KEY_COMPILED_ESM = '__esModule';\n\nfunction isDefineCompiledEsm(node) {\n const definedProperty =\n getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports');\n if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {\n return isTruthy(definedProperty.value);\n }\n return false;\n}\n\nfunction getDefinePropertyCallName(node, targetName) {\n const {\n callee: { object, property }\n } = node;\n if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;\n if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;\n if (node.arguments.length !== 3) return;\n\n const targetNames = targetName.split('.');\n const [target, key, value] = node.arguments;\n if (targetNames.length === 1) {\n if (target.type !== 'Identifier' || target.name !== targetNames[0]) {\n return;\n }\n }\n\n if (targetNames.length === 2) {\n if (\n target.type !== 'MemberExpression' ||\n target.object.name !== targetNames[0] ||\n target.property.name !== targetNames[1]\n ) {\n return;\n }\n }\n\n if (value.type !== 'ObjectExpression' || !value.properties) return;\n\n const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');\n if (!valueProperty || !valueProperty.value) return;\n\n // eslint-disable-next-line consistent-return\n return { key: key.value, value: valueProperty.value };\n}\n\nfunction isShorthandProperty(parent) {\n return parent && parent.type === 'Property' && parent.shorthand;\n}\n\nfunction hasDefineEsmProperty(node) {\n return node.properties.some((property) => {\n if (\n property.type === 'Property' &&\n property.key.type === 'Identifier' &&\n property.key.name === '__esModule' &&\n isTruthy(property.value)\n ) {\n return true;\n }\n return false;\n });\n}\n\nfunction wrapCode(magicString, uses, moduleName, exportsName) {\n const args = [];\n const passedArgs = [];\n if (uses.module) {\n args.push('module');\n passedArgs.push(moduleName);\n }\n if (uses.exports) {\n args.push('exports');\n passedArgs.push(exportsName);\n }\n magicString\n .trim()\n .prepend(`(function (${args.join(', ')}) {\\n`)\n .append(`\\n}(${passedArgs.join(', ')}));`);\n}\n\nfunction rewriteExportsAndGetExportsBlock(\n magicString,\n moduleName,\n exportsName,\n wrapped,\n moduleExportsAssignments,\n firstTopLevelModuleExportsAssignment,\n exportsAssignmentsByName,\n topLevelAssignments,\n defineCompiledEsmExpressions,\n deconflictedExportNames,\n code,\n HELPERS_NAME,\n exportMode,\n detectWrappedDefault,\n defaultIsModuleExports\n) {\n const exports = [];\n const exportDeclarations = [];\n\n if (exportMode === 'replace') {\n getExportsForReplacedModuleExports(\n magicString,\n exports,\n exportDeclarations,\n moduleExportsAssignments,\n firstTopLevelModuleExportsAssignment,\n exportsName\n );\n } else {\n exports.push(`${exportsName} as __moduleExports`);\n if (wrapped) {\n getExportsWhenWrapping(\n exportDeclarations,\n exportsName,\n detectWrappedDefault,\n HELPERS_NAME,\n defaultIsModuleExports\n );\n } else {\n getExports(\n magicString,\n exports,\n exportDeclarations,\n moduleExportsAssignments,\n exportsAssignmentsByName,\n deconflictedExportNames,\n topLevelAssignments,\n moduleName,\n exportsName,\n defineCompiledEsmExpressions,\n HELPERS_NAME,\n defaultIsModuleExports\n );\n }\n }\n if (exports.length) {\n exportDeclarations.push(`export { ${exports.join(', ')} };`);\n }\n\n return `\\n\\n${exportDeclarations.join('\\n')}`;\n}\n\nfunction getExportsForReplacedModuleExports(\n magicString,\n exports,\n exportDeclarations,\n moduleExportsAssignments,\n firstTopLevelModuleExportsAssignment,\n exportsName\n) {\n for (const { left } of moduleExportsAssignments) {\n magicString.overwrite(left.start, left.end, exportsName);\n }\n magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');\n exports.push(`${exportsName} as __moduleExports`);\n exportDeclarations.push(`export default ${exportsName};`);\n}\n\nfunction getExportsWhenWrapping(\n exportDeclarations,\n exportsName,\n detectWrappedDefault,\n HELPERS_NAME,\n defaultIsModuleExports\n) {\n exportDeclarations.push(\n `export default ${\n detectWrappedDefault && defaultIsModuleExports === 'auto'\n ? `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName})`\n : defaultIsModuleExports === false\n ? `${exportsName}.default`\n : exportsName\n };`\n );\n}\n\nfunction getExports(\n magicString,\n exports,\n exportDeclarations,\n moduleExportsAssignments,\n exportsAssignmentsByName,\n deconflictedExportNames,\n topLevelAssignments,\n moduleName,\n exportsName,\n defineCompiledEsmExpressions,\n HELPERS_NAME,\n defaultIsModuleExports\n) {\n let deconflictedDefaultExportName;\n // Collect and rewrite module.exports assignments\n for (const { left } of moduleExportsAssignments) {\n magicString.overwrite(left.start, left.end, `${moduleName}.exports`);\n }\n\n // Collect and rewrite named exports\n for (const [exportName, { nodes }] of exportsAssignmentsByName) {\n const deconflicted = deconflictedExportNames[exportName];\n let needsDeclaration = true;\n for (const node of nodes) {\n let replacement = `${deconflicted} = ${exportsName}.${exportName}`;\n if (needsDeclaration && topLevelAssignments.has(node)) {\n replacement = `var ${replacement}`;\n needsDeclaration = false;\n }\n magicString.overwrite(node.start, node.left.end, replacement);\n }\n if (needsDeclaration) {\n magicString.prepend(`var ${deconflicted};\\n`);\n }\n\n if (exportName === 'default') {\n deconflictedDefaultExportName = deconflicted;\n } else {\n exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);\n }\n }\n\n // Collect and rewrite exports.__esModule assignments\n let isRestorableCompiledEsm = false;\n for (const expression of defineCompiledEsmExpressions) {\n isRestorableCompiledEsm = true;\n const moduleExportsExpression =\n expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;\n magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName);\n }\n\n if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {\n exportDeclarations.push(`export default ${exportsName};`);\n } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {\n exports.push(`${deconflictedDefaultExportName || exportsName} as default`);\n } else {\n exportDeclarations.push(\n `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`\n );\n }\n}\n\nfunction isRequireStatement(node, scope) {\n if (!node) return false;\n if (node.type !== 'CallExpression') return false;\n\n // Weird case of `require()` or `module.require()` without arguments\n if (node.arguments.length === 0) return false;\n\n return isRequire(node.callee, scope);\n}\n\nfunction isRequire(node, scope) {\n return (\n (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||\n (node.type === 'MemberExpression' && isModuleRequire(node, scope))\n );\n}\n\nfunction isModuleRequire({ object, property }, scope) {\n return (\n object.type === 'Identifier' &&\n object.name === 'module' &&\n property.type === 'Identifier' &&\n property.name === 'require' &&\n !scope.contains('module')\n );\n}\n\nfunction isStaticRequireStatement(node, scope) {\n if (!isRequireStatement(node, scope)) return false;\n return !hasDynamicArguments(node);\n}\n\nfunction hasDynamicArguments(node) {\n return (\n node.arguments.length > 1 ||\n (node.arguments[0].type !== 'Literal' &&\n (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))\n );\n}\n\nconst reservedMethod = { resolve: true, cache: true, main: true };\n\nfunction isNodeRequirePropertyAccess(parent) {\n return parent && parent.property && reservedMethod[parent.property.name];\n}\n\nfunction isIgnoredRequireStatement(requiredNode, ignoreRequire) {\n return ignoreRequire(requiredNode.arguments[0].value);\n}\n\nfunction getRequireStringArg(node) {\n return node.arguments[0].type === 'Literal'\n ? node.arguments[0].value\n : node.arguments[0].quasis[0].value.cooked;\n}\n\nfunction hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {\n if (!/^(?:\\.{0,2}[/\\\\]|[A-Za-z]:[/\\\\])/.test(source)) {\n try {\n const resolvedPath = normalizePathSlashes(sync(source, { basedir: dirname(id) }));\n if (dynamicRequireModuleSet.has(resolvedPath)) {\n return true;\n }\n } catch (ex) {\n // Probably a node.js internal module\n return false;\n }\n\n return false;\n }\n\n for (const attemptExt of ['', '.js', '.json']) {\n const resolvedPath = normalizePathSlashes(resolve(dirname(id), source + attemptExt));\n if (dynamicRequireModuleSet.has(resolvedPath)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction getRequireHandlers() {\n const requiredSources = [];\n const requiredBySource = Object.create(null);\n const requiredByNode = new Map();\n const requireExpressionsWithUsedReturnValue = [];\n\n function addRequireStatement(sourceId, node, scope, usesReturnValue) {\n const required = getRequired(sourceId);\n requiredByNode.set(node, { scope, required });\n if (usesReturnValue) {\n required.nodesUsingRequired.push(node);\n requireExpressionsWithUsedReturnValue.push(node);\n }\n }\n\n function getRequired(sourceId) {\n if (!requiredBySource[sourceId]) {\n requiredSources.push(sourceId);\n\n requiredBySource[sourceId] = {\n source: sourceId,\n name: null,\n nodesUsingRequired: []\n };\n }\n\n return requiredBySource[sourceId];\n }\n\n function rewriteRequireExpressionsAndGetImportBlock(\n magicString,\n topLevelDeclarations,\n topLevelRequireDeclarators,\n reassignedNames,\n helpersName,\n dynamicRegisterSources,\n moduleName,\n exportsName,\n id,\n exportMode\n ) {\n setRemainingImportNamesAndRewriteRequires(\n requireExpressionsWithUsedReturnValue,\n requiredByNode,\n magicString\n );\n const imports = [];\n imports.push(`import * as ${helpersName} from \"${HELPERS_ID}\";`);\n if (exportMode === 'module') {\n imports.push(\n `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(\n wrapId(id, MODULE_SUFFIX)\n )}`\n );\n } else if (exportMode === 'exports') {\n imports.push(\n `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`\n );\n }\n for (const source of dynamicRegisterSources) {\n imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);\n }\n for (const source of requiredSources) {\n if (!source.startsWith('\\0')) {\n imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);\n }\n const { name, nodesUsingRequired } = requiredBySource[source];\n imports.push(\n `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(\n source.startsWith('\\0') ? source : wrapId(source, PROXY_SUFFIX)\n )};`\n );\n }\n return imports.length ? `${imports.join('\\n')}\\n\\n` : '';\n }\n\n return {\n addRequireStatement,\n requiredSources,\n rewriteRequireExpressionsAndGetImportBlock\n };\n}\n\nfunction setRemainingImportNamesAndRewriteRequires(\n requireExpressionsWithUsedReturnValue,\n requiredByNode,\n magicString\n) {\n let uid = 0;\n for (const requireExpression of requireExpressionsWithUsedReturnValue) {\n const { required } = requiredByNode.get(requireExpression);\n if (!required.name) {\n let potentialName;\n const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);\n do {\n potentialName = `require$$${uid}`;\n uid += 1;\n } while (required.nodesUsingRequired.some(isUsedName));\n required.name = potentialName;\n }\n magicString.overwrite(requireExpression.start, requireExpression.end, required.name);\n }\n}\n\n/* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */\n\nconst exportsPattern = /^(?:module\\.)?exports(?:\\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;\n\nconst functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;\n\nfunction transformCommonjs(\n parse,\n code,\n id,\n isEsModule,\n ignoreGlobal,\n ignoreRequire,\n ignoreDynamicRequires,\n getIgnoreTryCatchRequireStatementMode,\n sourceMap,\n isDynamicRequireModulesEnabled,\n dynamicRequireModuleSet,\n disableWrap,\n commonDir,\n astCache,\n defaultIsModuleExports\n) {\n const ast = astCache || tryParse(parse, code, id);\n const magicString = new MagicString(code);\n const uses = {\n module: false,\n exports: false,\n global: false,\n require: false\n };\n let usesDynamicRequire = false;\n const virtualDynamicRequirePath =\n isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir);\n let scope = attachScopes(ast, 'scope');\n let lexicalDepth = 0;\n let programDepth = 0;\n let currentTryBlockEnd = null;\n let shouldWrap = false;\n\n const globals = new Set();\n\n // TODO technically wrong since globals isn't populated yet, but ¯\\_(ツ)_/¯\n const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers');\n const dynamicRegisterSources = new Set();\n let hasRemovedRequire = false;\n\n const {\n addRequireStatement,\n requiredSources,\n rewriteRequireExpressionsAndGetImportBlock\n } = getRequireHandlers();\n\n // See which names are assigned to. This is necessary to prevent\n // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,\n // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)\n const reassignedNames = new Set();\n const topLevelDeclarations = [];\n const topLevelRequireDeclarators = new Set();\n const skippedNodes = new Set();\n const moduleAccessScopes = new Set([scope]);\n const exportsAccessScopes = new Set([scope]);\n const moduleExportsAssignments = [];\n let firstTopLevelModuleExportsAssignment = null;\n const exportsAssignmentsByName = new Map();\n const topLevelAssignments = new Set();\n const topLevelDefineCompiledEsmExpressions = [];\n\n walk(ast, {\n enter(node, parent) {\n if (skippedNodes.has(node)) {\n this.skip();\n return;\n }\n\n if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {\n currentTryBlockEnd = null;\n }\n\n programDepth += 1;\n if (node.scope) ({ scope } = node);\n if (functionType.test(node.type)) lexicalDepth += 1;\n if (sourceMap) {\n magicString.addSourcemapLocation(node.start);\n magicString.addSourcemapLocation(node.end);\n }\n\n // eslint-disable-next-line default-case\n switch (node.type) {\n case 'TryStatement':\n if (currentTryBlockEnd === null) {\n currentTryBlockEnd = node.block.end;\n }\n return;\n case 'AssignmentExpression':\n if (node.left.type === 'MemberExpression') {\n const flattened = getKeypath(node.left);\n if (!flattened || scope.contains(flattened.name)) return;\n\n const exportsPatternMatch = exportsPattern.exec(flattened.keypath);\n if (!exportsPatternMatch || flattened.keypath === 'exports') return;\n\n const [, exportName] = exportsPatternMatch;\n uses[flattened.name] = true;\n\n // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –\n if (flattened.keypath === 'module.exports') {\n moduleExportsAssignments.push(node);\n if (programDepth > 3) {\n moduleAccessScopes.add(scope);\n } else if (!firstTopLevelModuleExportsAssignment) {\n firstTopLevelModuleExportsAssignment = node;\n }\n\n if (defaultIsModuleExports === false) {\n shouldWrap = true;\n } else if (defaultIsModuleExports === 'auto') {\n if (node.right.type === 'ObjectExpression') {\n if (hasDefineEsmProperty(node.right)) {\n shouldWrap = true;\n }\n } else if (defaultIsModuleExports === false) {\n shouldWrap = true;\n }\n }\n } else if (exportName === KEY_COMPILED_ESM) {\n if (programDepth > 3) {\n shouldWrap = true;\n } else {\n topLevelDefineCompiledEsmExpressions.push(node);\n }\n } else {\n const exportsAssignments = exportsAssignmentsByName.get(exportName) || {\n nodes: [],\n scopes: new Set()\n };\n exportsAssignments.nodes.push(node);\n exportsAssignments.scopes.add(scope);\n exportsAccessScopes.add(scope);\n exportsAssignmentsByName.set(exportName, exportsAssignments);\n if (programDepth <= 3) {\n topLevelAssignments.add(node);\n }\n }\n\n skippedNodes.add(node.left);\n } else {\n for (const name of extractAssignedNames(node.left)) {\n reassignedNames.add(name);\n }\n }\n return;\n case 'CallExpression': {\n if (isDefineCompiledEsm(node)) {\n if (programDepth === 3 && parent.type === 'ExpressionStatement') {\n // skip special handling for [module.]exports until we know we render this\n skippedNodes.add(node.arguments[0]);\n topLevelDefineCompiledEsmExpressions.push(node);\n } else {\n shouldWrap = true;\n }\n return;\n }\n\n if (\n node.callee.object &&\n node.callee.object.name === 'require' &&\n node.callee.property.name === 'resolve' &&\n hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)\n ) {\n const requireNode = node.callee.object;\n magicString.appendLeft(\n node.end - 1,\n `,${JSON.stringify(\n dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath\n )}`\n );\n magicString.overwrite(\n requireNode.start,\n requireNode.end,\n `${HELPERS_NAME}.commonjsRequire`,\n {\n storeName: true\n }\n );\n return;\n }\n\n if (!isStaticRequireStatement(node, scope)) return;\n if (!isDynamicRequireModulesEnabled) {\n skippedNodes.add(node.callee);\n }\n if (!isIgnoredRequireStatement(node, ignoreRequire)) {\n skippedNodes.add(node.callee);\n const usesReturnValue = parent.type !== 'ExpressionStatement';\n\n let canConvertRequire = true;\n let shouldRemoveRequireStatement = false;\n\n if (currentTryBlockEnd !== null) {\n ({\n canConvertRequire,\n shouldRemoveRequireStatement\n } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));\n\n if (shouldRemoveRequireStatement) {\n hasRemovedRequire = true;\n }\n }\n\n let sourceId = getRequireStringArg(node);\n const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);\n if (isDynamicRegister) {\n sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);\n if (sourceId.endsWith('.json')) {\n sourceId = DYNAMIC_JSON_PREFIX + sourceId;\n }\n dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));\n } else {\n if (\n !sourceId.endsWith('.json') &&\n hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)\n ) {\n if (shouldRemoveRequireStatement) {\n magicString.overwrite(node.start, node.end, `undefined`);\n } else if (canConvertRequire) {\n magicString.overwrite(\n node.start,\n node.end,\n `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(\n getVirtualPathForDynamicRequirePath(sourceId, commonDir)\n )}, ${JSON.stringify(\n dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath\n )})`\n );\n usesDynamicRequire = true;\n }\n return;\n }\n\n if (canConvertRequire) {\n addRequireStatement(sourceId, node, scope, usesReturnValue);\n }\n }\n\n if (usesReturnValue) {\n if (shouldRemoveRequireStatement) {\n magicString.overwrite(node.start, node.end, `undefined`);\n return;\n }\n\n if (\n parent.type === 'VariableDeclarator' &&\n !scope.parent &&\n parent.id.type === 'Identifier'\n ) {\n // This will allow us to reuse this variable name as the imported variable if it is not reassigned\n // and does not conflict with variables in other places where this is imported\n topLevelRequireDeclarators.add(parent);\n }\n } else {\n // This is a bare import, e.g. `require('foo');`\n\n if (!canConvertRequire && !shouldRemoveRequireStatement) {\n return;\n }\n\n magicString.remove(parent.start, parent.end);\n }\n }\n return;\n }\n case 'ConditionalExpression':\n case 'IfStatement':\n // skip dead branches\n if (isFalsy(node.test)) {\n skippedNodes.add(node.consequent);\n } else if (node.alternate && isTruthy(node.test)) {\n skippedNodes.add(node.alternate);\n }\n return;\n case 'Identifier': {\n const { name } = node;\n if (!(isReference(node, parent) && !scope.contains(name))) return;\n switch (name) {\n case 'require':\n if (isNodeRequirePropertyAccess(parent)) {\n if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {\n if (parent.property.name === 'cache') {\n magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {\n storeName: true\n });\n }\n }\n\n return;\n }\n\n if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {\n magicString.appendLeft(\n parent.end - 1,\n `,${JSON.stringify(\n dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath\n )}`\n );\n }\n if (!ignoreDynamicRequires) {\n if (isShorthandProperty(parent)) {\n magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);\n } else {\n magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {\n storeName: true\n });\n }\n }\n usesDynamicRequire = true;\n return;\n case 'module':\n case 'exports':\n shouldWrap = true;\n uses[name] = true;\n return;\n case 'global':\n uses.global = true;\n if (!ignoreGlobal) {\n magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {\n storeName: true\n });\n }\n return;\n case 'define':\n magicString.overwrite(node.start, node.end, 'undefined', {\n storeName: true\n });\n return;\n default:\n globals.add(name);\n return;\n }\n }\n case 'MemberExpression':\n if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {\n magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {\n storeName: true\n });\n skippedNodes.add(node.object);\n skippedNodes.add(node.property);\n }\n return;\n case 'ReturnStatement':\n // if top-level return, we need to wrap it\n if (lexicalDepth === 0) {\n shouldWrap = true;\n }\n return;\n case 'ThisExpression':\n // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`\n if (lexicalDepth === 0) {\n uses.global = true;\n if (!ignoreGlobal) {\n magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {\n storeName: true\n });\n }\n }\n return;\n case 'UnaryExpression':\n // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)\n if (node.operator === 'typeof') {\n const flattened = getKeypath(node.argument);\n if (!flattened) return;\n\n if (scope.contains(flattened.name)) return;\n\n if (\n flattened.keypath === 'module.exports' ||\n flattened.keypath === 'module' ||\n flattened.keypath === 'exports'\n ) {\n magicString.overwrite(node.start, node.end, `'object'`, {\n storeName: false\n });\n }\n }\n return;\n case 'VariableDeclaration':\n if (!scope.parent) {\n topLevelDeclarations.push(node);\n }\n }\n },\n\n leave(node) {\n programDepth -= 1;\n if (node.scope) scope = scope.parent;\n if (functionType.test(node.type)) lexicalDepth -= 1;\n }\n });\n\n const nameBase = getName(id);\n const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);\n const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);\n const deconflictedExportNames = Object.create(null);\n for (const [exportName, { scopes }] of exportsAssignmentsByName) {\n deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);\n }\n\n // We cannot wrap ES/mixed modules\n shouldWrap =\n !isEsModule &&\n !disableWrap &&\n (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));\n const detectWrappedDefault =\n shouldWrap &&\n (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);\n\n if (\n !(\n requiredSources.length ||\n dynamicRegisterSources.size ||\n uses.module ||\n uses.exports ||\n uses.require ||\n usesDynamicRequire ||\n hasRemovedRequire ||\n topLevelDefineCompiledEsmExpressions.length > 0\n ) &&\n (ignoreGlobal || !uses.global)\n ) {\n return { meta: { commonjs: { isCommonJS: false } } };\n }\n\n let leadingComment = '';\n if (code.startsWith('/*')) {\n const commentEnd = code.indexOf('*/', 2) + 2;\n leadingComment = `${code.slice(0, commentEnd)}\\n`;\n magicString.remove(0, commentEnd).trim();\n }\n\n const exportMode = shouldWrap\n ? uses.module\n ? 'module'\n : 'exports'\n : firstTopLevelModuleExportsAssignment\n ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0\n ? 'replace'\n : 'module'\n : moduleExportsAssignments.length === 0\n ? 'exports'\n : 'module';\n\n const importBlock = rewriteRequireExpressionsAndGetImportBlock(\n magicString,\n topLevelDeclarations,\n topLevelRequireDeclarators,\n reassignedNames,\n HELPERS_NAME,\n dynamicRegisterSources,\n moduleName,\n exportsName,\n id,\n exportMode\n );\n\n const exportBlock = isEsModule\n ? ''\n : rewriteExportsAndGetExportsBlock(\n magicString,\n moduleName,\n exportsName,\n shouldWrap,\n moduleExportsAssignments,\n firstTopLevelModuleExportsAssignment,\n exportsAssignmentsByName,\n topLevelAssignments,\n topLevelDefineCompiledEsmExpressions,\n deconflictedExportNames,\n code,\n HELPERS_NAME,\n exportMode,\n detectWrappedDefault,\n defaultIsModuleExports\n );\n\n if (shouldWrap) {\n wrapCode(magicString, uses, moduleName, exportsName);\n }\n\n magicString\n .trim()\n .prepend(leadingComment + importBlock)\n .append(exportBlock);\n\n return {\n code: magicString.toString(),\n map: sourceMap ? magicString.generateMap() : null,\n syntheticNamedExports: isEsModule ? false : '__moduleExports',\n meta: { commonjs: { isCommonJS: !isEsModule } }\n };\n}\n\nfunction commonjs(options = {}) {\n const extensions = options.extensions || ['.js'];\n const filter = createFilter(options.include, options.exclude);\n const {\n ignoreGlobal,\n ignoreDynamicRequires,\n requireReturnsDefault: requireReturnsDefaultOption,\n esmExternals\n } = options;\n const getRequireReturnsDefault =\n typeof requireReturnsDefaultOption === 'function'\n ? requireReturnsDefaultOption\n : () => requireReturnsDefaultOption;\n let esmExternalIds;\n const isEsmExternal =\n typeof esmExternals === 'function'\n ? esmExternals\n : Array.isArray(esmExternals)\n ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))\n : () => esmExternals;\n const defaultIsModuleExports =\n typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';\n\n const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(\n options.dynamicRequireTargets\n );\n const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;\n const commonDir = isDynamicRequireModulesEnabled\n ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))\n : null;\n\n const esModulesWithDefaultExport = new Set();\n const esModulesWithNamedExports = new Set();\n const commonJsMetaPromises = new Map();\n\n const ignoreRequire =\n typeof options.ignore === 'function'\n ? options.ignore\n : Array.isArray(options.ignore)\n ? (id) => options.ignore.includes(id)\n : () => false;\n\n const getIgnoreTryCatchRequireStatementMode = (id) => {\n const mode =\n typeof options.ignoreTryCatch === 'function'\n ? options.ignoreTryCatch(id)\n : Array.isArray(options.ignoreTryCatch)\n ? options.ignoreTryCatch.includes(id)\n : options.ignoreTryCatch || false;\n\n return {\n canConvertRequire: mode !== 'remove' && mode !== true,\n shouldRemoveRequireStatement: mode === 'remove'\n };\n };\n\n const resolveId = getResolveId(extensions);\n\n const sourceMap = options.sourceMap !== false;\n\n function transformAndCheckExports(code, id) {\n if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {\n // eslint-disable-next-line no-param-reassign\n code =\n getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;\n }\n\n const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(\n this.parse,\n code,\n id\n );\n if (hasDefaultExport) {\n esModulesWithDefaultExport.add(id);\n }\n if (hasNamedExports) {\n esModulesWithNamedExports.add(id);\n }\n\n if (\n !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&\n (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))\n ) {\n return { meta: { commonjs: { isCommonJS: false } } };\n }\n\n // avoid wrapping as this is a commonjsRegister call\n const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);\n if (disableWrap) {\n // eslint-disable-next-line no-param-reassign\n id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);\n }\n\n return transformCommonjs(\n this.parse,\n code,\n id,\n isEsModule,\n ignoreGlobal || isEsModule,\n ignoreRequire,\n ignoreDynamicRequires && !isDynamicRequireModulesEnabled,\n getIgnoreTryCatchRequireStatementMode,\n sourceMap,\n isDynamicRequireModulesEnabled,\n dynamicRequireModuleSet,\n disableWrap,\n commonDir,\n ast,\n defaultIsModuleExports\n );\n }\n\n return {\n name: 'commonjs',\n\n buildStart() {\n validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);\n if (options.namedExports != null) {\n this.warn(\n 'The namedExports option from \"@rollup/plugin-commonjs\" is deprecated. Named exports are now handled automatically.'\n );\n }\n },\n\n resolveId,\n\n load(id) {\n if (id === HELPERS_ID) {\n return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);\n }\n\n if (id.startsWith(HELPERS_ID)) {\n return getSpecificHelperProxy(id);\n }\n\n if (isWrappedId(id, MODULE_SUFFIX)) {\n const actualId = unwrapId(id, MODULE_SUFFIX);\n let name = getName(actualId);\n let code;\n if (isDynamicRequireModulesEnabled) {\n if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {\n name = `${name}_`;\n }\n code =\n `import {commonjsRequire, createModule} from \"${HELPERS_ID}\";\\n` +\n `var ${name} = createModule(${JSON.stringify(\n getVirtualPathForDynamicRequirePath(dirname(actualId), commonDir)\n )});\\n` +\n `export {${name} as __module}`;\n } else {\n code = `var ${name} = {exports: {}}; export {${name} as __module}`;\n }\n return {\n code,\n syntheticNamedExports: '__module',\n meta: { commonjs: { isCommonJS: false } }\n };\n }\n\n if (isWrappedId(id, EXPORTS_SUFFIX)) {\n const actualId = unwrapId(id, EXPORTS_SUFFIX);\n const name = getName(actualId);\n return {\n code: `var ${name} = {}; export {${name} as __exports}`,\n meta: { commonjs: { isCommonJS: false } }\n };\n }\n\n if (isWrappedId(id, EXTERNAL_SUFFIX)) {\n const actualId = unwrapId(id, EXTERNAL_SUFFIX);\n return getUnknownRequireProxy(\n actualId,\n isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true\n );\n }\n\n if (id === DYNAMIC_PACKAGES_ID) {\n return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);\n }\n\n if (id.startsWith(DYNAMIC_JSON_PREFIX)) {\n return getDynamicJsonProxy(id, commonDir);\n }\n\n if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {\n return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;\n }\n\n if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {\n return getDynamicRequireProxy(\n normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),\n commonDir\n );\n }\n\n if (isWrappedId(id, PROXY_SUFFIX)) {\n const actualId = unwrapId(id, PROXY_SUFFIX);\n return getStaticRequireProxy(\n actualId,\n getRequireReturnsDefault(actualId),\n esModulesWithDefaultExport,\n esModulesWithNamedExports,\n commonJsMetaPromises\n );\n }\n\n return null;\n },\n\n transform(code, rawId) {\n let id = rawId;\n\n if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {\n id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);\n }\n\n const extName = extname(id);\n if (\n extName !== '.cjs' &&\n id !== DYNAMIC_PACKAGES_ID &&\n !id.startsWith(DYNAMIC_JSON_PREFIX) &&\n (!filter(id) || !extensions.includes(extName))\n ) {\n return null;\n }\n\n try {\n return transformAndCheckExports.call(this, code, rawId);\n } catch (err) {\n return this.error(err, err.loc);\n }\n },\n\n moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {\n if (commonjsMeta && commonjsMeta.isCommonJS != null) {\n setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);\n return;\n }\n setCommonJSMetaPromise(commonJsMetaPromises, id, null);\n }\n };\n}\n\nexport default commonjs;\n//# sourceMappingURL=index.es.js.map\n","'use strict';\n\nmodule.exports = (...arguments_) => {\n\treturn [...new Set([].concat(...arguments_))];\n};\n","'use strict';\nconst {promisify} = require('util');\nconst fs = require('fs');\n\nasync function isType(fsStatType, statsMethodName, filePath) {\n\tif (typeof filePath !== 'string') {\n\t\tthrow new TypeError(`Expected a string, got ${typeof filePath}`);\n\t}\n\n\ttry {\n\t\tconst stats = await promisify(fs[fsStatType])(filePath);\n\t\treturn stats[statsMethodName]();\n\t} catch (error) {\n\t\tif (error.code === 'ENOENT') {\n\t\t\treturn false;\n\t\t}\n\n\t\tthrow error;\n\t}\n}\n\nfunction isTypeSync(fsStatType, statsMethodName, filePath) {\n\tif (typeof filePath !== 'string') {\n\t\tthrow new TypeError(`Expected a string, got ${typeof filePath}`);\n\t}\n\n\ttry {\n\t\treturn fs[fsStatType](filePath)[statsMethodName]();\n\t} catch (error) {\n\t\tif (error.code === 'ENOENT') {\n\t\t\treturn false;\n\t\t}\n\n\t\tthrow error;\n\t}\n}\n\nexports.isFile = isType.bind(null, 'stat', 'isFile');\nexports.isDirectory = isType.bind(null, 'stat', 'isDirectory');\nexports.isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');\nexports.isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');\nexports.isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');\nexports.isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');\n","'use strict';\nconst path = require('path');\nconst pathType = require('path-type');\n\nconst getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];\n\nconst getPath = (filepath, cwd) => {\n\tconst pth = filepath[0] === '!' ? filepath.slice(1) : filepath;\n\treturn path.isAbsolute(pth) ? pth : path.join(cwd, pth);\n};\n\nconst addExtensions = (file, extensions) => {\n\tif (path.extname(file)) {\n\t\treturn `**/${file}`;\n\t}\n\n\treturn `**/${file}.${getExtensions(extensions)}`;\n};\n\nconst getGlob = (directory, options) => {\n\tif (options.files && !Array.isArray(options.files)) {\n\t\tthrow new TypeError(`Expected \\`files\\` to be of type \\`Array\\` but received type \\`${typeof options.files}\\``);\n\t}\n\n\tif (options.extensions && !Array.isArray(options.extensions)) {\n\t\tthrow new TypeError(`Expected \\`extensions\\` to be of type \\`Array\\` but received type \\`${typeof options.extensions}\\``);\n\t}\n\n\tif (options.files && options.extensions) {\n\t\treturn options.files.map(x => path.posix.join(directory, addExtensions(x, options.extensions)));\n\t}\n\n\tif (options.files) {\n\t\treturn options.files.map(x => path.posix.join(directory, `**/${x}`));\n\t}\n\n\tif (options.extensions) {\n\t\treturn [path.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)];\n\t}\n\n\treturn [path.posix.join(directory, '**')];\n};\n\nmodule.exports = async (input, options) => {\n\toptions = {\n\t\tcwd: process.cwd(),\n\t\t...options\n\t};\n\n\tif (typeof options.cwd !== 'string') {\n\t\tthrow new TypeError(`Expected \\`cwd\\` to be of type \\`string\\` but received type \\`${typeof options.cwd}\\``);\n\t}\n\n\tconst globs = await Promise.all([].concat(input).map(async x => {\n\t\tconst isDirectory = await pathType.isDirectory(getPath(x, options.cwd));\n\t\treturn isDirectory ? getGlob(x, options) : x;\n\t}));\n\n\treturn [].concat.apply([], globs); // eslint-disable-line prefer-spread\n};\n\nmodule.exports.sync = (input, options) => {\n\toptions = {\n\t\tcwd: process.cwd(),\n\t\t...options\n\t};\n\n\tif (typeof options.cwd !== 'string') {\n\t\tthrow new TypeError(`Expected \\`cwd\\` to be of type \\`string\\` but received type \\`${typeof options.cwd}\\``);\n\t}\n\n\tconst globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x);\n\n\treturn [].concat.apply([], globs); // eslint-disable-line prefer-spread\n};\n","// A simple implementation of make-array\nfunction makeArray (subject) {\n return Array.isArray(subject)\n ? subject\n : [subject]\n}\n\nconst EMPTY = ''\nconst SPACE = ' '\nconst ESCAPE = '\\\\'\nconst REGEX_TEST_BLANK_LINE = /^\\s+$/\nconst REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/\nconst REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/\nconst REGEX_SPLITALL_CRLF = /\\r?\\n/g\n// /foo,\n// ./foo,\n// ../foo,\n// .\n// ..\nconst REGEX_TEST_INVALID_PATH = /^\\.*\\/|^\\.+$/\n\nconst SLASH = '/'\nconst KEY_IGNORE = typeof Symbol !== 'undefined'\n ? Symbol.for('node-ignore')\n /* istanbul ignore next */\n : 'node-ignore'\n\nconst define = (object, key, value) =>\n Object.defineProperty(object, key, {value})\n\nconst REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g\n\n// Sanitize the range of a regular expression\n// The cases are complicated, see test cases for details\nconst sanitizeRange = range => range.replace(\n REGEX_REGEXP_RANGE,\n (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)\n ? match\n // Invalid range (out of order) which is ok for gitignore rules but\n // fatal for JavaScript regular expression, so eliminate it.\n : EMPTY\n)\n\n// See fixtures #59\nconst cleanRangeBackSlash = slashes => {\n const {length} = slashes\n return slashes.slice(0, length - length % 2)\n}\n\n// > If the pattern ends with a slash,\n// > it is removed for the purpose of the following description,\n// > but it would only find a match with a directory.\n// > In other words, foo/ will match a directory foo and paths underneath it,\n// > but will not match a regular file or a symbolic link foo\n// > (this is consistent with the way how pathspec works in general in Git).\n// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'\n// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call\n// you could use option `mark: true` with `glob`\n\n// '`foo/`' should not continue with the '`..`'\nconst REPLACERS = [\n\n // > Trailing spaces are ignored unless they are quoted with backslash (\"\\\")\n [\n // (a\\ ) -> (a )\n // (a ) -> (a)\n // (a \\ ) -> (a )\n /\\\\?\\s+$/,\n match => match.indexOf('\\\\') === 0\n ? SPACE\n : EMPTY\n ],\n\n // replace (\\ ) with ' '\n [\n /\\\\\\s/g,\n () => SPACE\n ],\n\n // Escape metacharacters\n // which is written down by users but means special for regular expressions.\n\n // > There are 12 characters with special meanings:\n // > - the backslash \\,\n // > - the caret ^,\n // > - the dollar sign $,\n // > - the period or dot .,\n // > - the vertical bar or pipe symbol |,\n // > - the question mark ?,\n // > - the asterisk or star *,\n // > - the plus sign +,\n // > - the opening parenthesis (,\n // > - the closing parenthesis ),\n // > - and the opening square bracket [,\n // > - the opening curly brace {,\n // > These special characters are often called \"metacharacters\".\n [\n /[\\\\$.|*+(){^]/g,\n match => `\\\\${match}`\n ],\n\n [\n // > a question mark (?) matches a single character\n /(?!\\\\)\\?/g,\n () => '[^/]'\n ],\n\n // leading slash\n [\n\n // > A leading slash matches the beginning of the pathname.\n // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n // A leading slash matches the beginning of the pathname\n /^\\//,\n () => '^'\n ],\n\n // replace special metacharacter slash after the leading slash\n [\n /\\//g,\n () => '\\\\/'\n ],\n\n [\n // > A leading \"**\" followed by a slash means match in all directories.\n // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n // > the same as pattern \"foo\".\n // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n // > under directory \"foo\".\n // Notice that the '*'s have been replaced as '\\\\*'\n /^\\^*\\\\\\*\\\\\\*\\\\\\//,\n\n // '**/foo' <-> 'foo'\n () => '^(?:.*\\\\/)?'\n ],\n\n // starting\n [\n // there will be no leading '/'\n // (which has been replaced by section \"leading slash\")\n // If starts with '**', adding a '^' to the regular expression also works\n /^(?=[^^])/,\n function startingReplacer () {\n // If has a slash `/` at the beginning or middle\n return !/\\/(?!$)/.test(this)\n // > Prior to 2.22.1\n // > If the pattern does not contain a slash /,\n // > Git treats it as a shell glob pattern\n // Actually, if there is only a trailing slash,\n // git also treats it as a shell glob pattern\n\n // After 2.22.1 (compatible but clearer)\n // > If there is a separator at the beginning or middle (or both)\n // > of the pattern, then the pattern is relative to the directory\n // > level of the particular .gitignore file itself.\n // > Otherwise the pattern may also match at any level below\n // > the .gitignore level.\n ? '(?:^|\\\\/)'\n\n // > Otherwise, Git treats the pattern as a shell glob suitable for\n // > consumption by fnmatch(3)\n : '^'\n }\n ],\n\n // two globstars\n [\n // Use lookahead assertions so that we could match more than one `'/**'`\n /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n\n // Zero, one or several directories\n // should not use '*', or it will be replaced by the next replacer\n\n // Check if it is not the last `'/**'`\n (_, index, str) => index + 6 < str.length\n\n // case: /**/\n // > A slash followed by two consecutive asterisks then a slash matches\n // > zero or more directories.\n // > For example, \"a/**/b\" matches \"a/b\", \"a/x/b\", \"a/x/y/b\" and so on.\n // '/**/'\n ? '(?:\\\\/[^\\\\/]+)*'\n\n // case: /**\n // > A trailing `\"/**\"` matches everything inside.\n\n // #21: everything inside but it should not include the current folder\n : '\\\\/.+'\n ],\n\n // intermediate wildcards\n [\n // Never replace escaped '*'\n // ignore rule '\\*' will match the path '*'\n\n // 'abc.*/' -> go\n // 'abc.*' -> skip this rule\n /(^|[^\\\\]+)\\\\\\*(?=.+)/g,\n\n // '*.js' matches '.js'\n // '*.js' doesn't match 'abc'\n (_, p1) => `${p1}[^\\\\/]*`\n ],\n\n [\n // unescape, revert step 3 except for back slash\n // For example, if a user escape a '\\\\*',\n // after step 3, the result will be '\\\\\\\\\\\\*'\n /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n () => ESCAPE\n ],\n\n [\n // '\\\\\\\\' -> '\\\\'\n /\\\\\\\\/g,\n () => ESCAPE\n ],\n\n [\n // > The range notation, e.g. [a-zA-Z],\n // > can be used to match one of the characters in a range.\n\n // `\\` is escaped by step 3\n /(\\\\)?\\[([^\\]/]*?)(\\\\*)($|\\])/g,\n (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE\n // '\\\\[bar]' -> '\\\\\\\\[bar\\\\]'\n ? `\\\\[${range}${cleanRangeBackSlash(endEscape)}${close}`\n : close === ']'\n ? endEscape.length % 2 === 0\n // A normal case, and it is a range notation\n // '[bar]'\n // '[bar\\\\\\\\]'\n ? `[${sanitizeRange(range)}${endEscape}]`\n // Invalid range notaton\n // '[bar\\\\]' -> '[bar\\\\\\\\]'\n : '[]'\n : '[]'\n ],\n\n // ending\n [\n // 'js' will not match 'js.'\n // 'ab' will not match 'abc'\n /(?:[^*])$/,\n\n // WTF!\n // https://git-scm.com/docs/gitignore\n // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n // which re-fixes #24, #38\n\n // > If there is a separator at the end of the pattern then the pattern\n // > will only match directories, otherwise the pattern can match both\n // > files and directories.\n\n // 'js*' will not match 'a.js'\n // 'js/' will not match 'a.js'\n // 'js' will match 'a.js' and 'a.js/'\n match => /\\/$/.test(match)\n // foo/ will not match 'foo'\n ? `${match}$`\n // foo matches 'foo' and 'foo/'\n : `${match}(?=$|\\\\/$)`\n ],\n\n // trailing wildcard\n [\n /(\\^|\\\\\\/)?\\\\\\*$/,\n (_, p1) => {\n const prefix = p1\n // '\\^':\n // '/*' does not match EMPTY\n // '/*' does not match everything\n\n // '\\\\\\/':\n // 'abc/*' does not match 'abc/'\n ? `${p1}[^/]+`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n }\n ],\n]\n\n// A simple cache, because an ignore rule only has only one certain meaning\nconst regexCache = Object.create(null)\n\n// @param {pattern}\nconst makeRegex = (pattern, negative, ignorecase) => {\n const r = regexCache[pattern]\n if (r) {\n return r\n }\n\n // const replacers = negative\n // ? NEGATIVE_REPLACERS\n // : POSITIVE_REPLACERS\n\n const source = REPLACERS.reduce(\n (prev, current) => prev.replace(current[0], current[1].bind(pattern)),\n pattern\n )\n\n return regexCache[pattern] = ignorecase\n ? new RegExp(source, 'i')\n : new RegExp(source)\n}\n\nconst isString = subject => typeof subject === 'string'\n\n// > A blank line matches no files, so it can serve as a separator for readability.\nconst checkPattern = pattern => pattern\n && isString(pattern)\n && !REGEX_TEST_BLANK_LINE.test(pattern)\n\n // > A line starting with # serves as a comment.\n && pattern.indexOf('#') !== 0\n\nconst splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF)\n\nclass IgnoreRule {\n constructor (\n origin,\n pattern,\n negative,\n regex\n ) {\n this.origin = origin\n this.pattern = pattern\n this.negative = negative\n this.regex = regex\n }\n}\n\nconst createRule = (pattern, ignorecase) => {\n const origin = pattern\n let negative = false\n\n // > An optional prefix \"!\" which negates the pattern;\n if (pattern.indexOf('!') === 0) {\n negative = true\n pattern = pattern.substr(1)\n }\n\n pattern = pattern\n // > Put a backslash (\"\\\") in front of the first \"!\" for patterns that\n // > begin with a literal \"!\", for example, `\"\\!important!.txt\"`.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')\n // > Put a backslash (\"\\\") in front of the first hash for patterns that\n // > begin with a hash.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')\n\n const regex = makeRegex(pattern, negative, ignorecase)\n\n return new IgnoreRule(\n origin,\n pattern,\n negative,\n regex\n )\n}\n\nconst throwError = (message, Ctor) => {\n throw new Ctor(message)\n}\n\nconst checkPath = (path, originalPath, doThrow) => {\n if (!isString(path)) {\n return doThrow(\n `path must be a string, but got \\`${originalPath}\\``,\n TypeError\n )\n }\n\n // We don't know if we should ignore EMPTY, so throw\n if (!path) {\n return doThrow(`path must not be empty`, TypeError)\n }\n\n // Check if it is a relative path\n if (checkPath.isNotRelative(path)) {\n const r = '`path.relative()`d'\n return doThrow(\n `path should be a ${r} string, but got \"${originalPath}\"`,\n RangeError\n )\n }\n\n return true\n}\n\nconst isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path)\n\ncheckPath.isNotRelative = isNotRelative\ncheckPath.convert = p => p\n\nclass Ignore {\n constructor ({\n ignorecase = true\n } = {}) {\n this._rules = []\n this._ignorecase = ignorecase\n define(this, KEY_IGNORE, true)\n this._initCache()\n }\n\n _initCache () {\n this._ignoreCache = Object.create(null)\n this._testCache = Object.create(null)\n }\n\n _addPattern (pattern) {\n // #32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules)\n this._added = true\n return\n }\n\n if (checkPattern(pattern)) {\n const rule = createRule(pattern, this._ignorecase)\n this._added = true\n this._rules.push(rule)\n }\n }\n\n // @param {Array | string | Ignore} pattern\n add (pattern) {\n this._added = false\n\n makeArray(\n isString(pattern)\n ? splitPattern(pattern)\n : pattern\n ).forEach(this._addPattern, this)\n\n // Some rules have just added to the ignore,\n // making the behavior changed.\n if (this._added) {\n this._initCache()\n }\n\n return this\n }\n\n // legacy\n addPattern (pattern) {\n return this.add(pattern)\n }\n\n // | ignored : unignored\n // negative | 0:0 | 0:1 | 1:0 | 1:1\n // -------- | ------- | ------- | ------- | --------\n // 0 | TEST | TEST | SKIP | X\n // 1 | TESTIF | SKIP | TEST | X\n\n // - SKIP: always skip\n // - TEST: always test\n // - TESTIF: only test if checkUnignored\n // - X: that never happen\n\n // @param {boolean} whether should check if the path is unignored,\n // setting `checkUnignored` to `false` could reduce additional\n // path matching.\n\n // @returns {TestResult} true if a file is ignored\n _testOne (path, checkUnignored) {\n let ignored = false\n let unignored = false\n\n this._rules.forEach(rule => {\n const {negative} = rule\n if (\n unignored === negative && ignored !== unignored\n || negative && !ignored && !unignored && !checkUnignored\n ) {\n return\n }\n\n const matched = rule.regex.test(path)\n\n if (matched) {\n ignored = !negative\n unignored = negative\n }\n })\n\n return {\n ignored,\n unignored\n }\n }\n\n // @returns {TestResult}\n _test (originalPath, cache, checkUnignored, slices) {\n const path = originalPath\n // Supports nullable path\n && checkPath.convert(originalPath)\n\n checkPath(path, originalPath, throwError)\n\n return this._t(path, cache, checkUnignored, slices)\n }\n\n _t (path, cache, checkUnignored, slices) {\n if (path in cache) {\n return cache[path]\n }\n\n if (!slices) {\n // path/to/a.js\n // ['path', 'to', 'a.js']\n slices = path.split(SLASH)\n }\n\n slices.pop()\n\n // If the path has no parent directory, just test it\n if (!slices.length) {\n return cache[path] = this._testOne(path, checkUnignored)\n }\n\n const parent = this._t(\n slices.join(SLASH) + SLASH,\n cache,\n checkUnignored,\n slices\n )\n\n // If the path contains a parent directory, check the parent first\n return cache[path] = parent.ignored\n // > It is not possible to re-include a file if a parent directory of\n // > that file is excluded.\n ? parent\n : this._testOne(path, checkUnignored)\n }\n\n ignores (path) {\n return this._test(path, this._ignoreCache, false).ignored\n }\n\n createFilter () {\n return path => !this.ignores(path)\n }\n\n filter (paths) {\n return makeArray(paths).filter(this.createFilter())\n }\n\n // @returns {TestResult}\n test (path) {\n return this._test(path, this._testCache, true)\n }\n}\n\nconst factory = options => new Ignore(options)\n\nconst returnFalse = () => false\n\nconst isPathValid = path =>\n checkPath(path && checkPath.convert(path), path, returnFalse)\n\nfactory.isPathValid = isPathValid\n\n// Fixes typescript\nfactory.default = factory\n\nmodule.exports = factory\n\n// Windows\n// --------------------------------------------------------------\n/* istanbul ignore if */\nif (\n // Detect `process` so that it can run in browsers.\n typeof process !== 'undefined'\n && (\n process.env && process.env.IGNORE_TEST_WIN32\n || process.platform === 'win32'\n )\n) {\n /* eslint no-control-regex: \"off\" */\n const makePosix = str => /^\\\\\\\\\\?\\\\/.test(str)\n || /[\"<>|\\u0000-\\u001F]+/u.test(str)\n ? str\n : str.replace(/\\\\/g, '/')\n\n checkPath.convert = makePosix\n\n // 'C:\\\\foo' <- 'C:\\\\foo' has been converted to 'C:/'\n // 'd:\\\\foo'\n const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i\n checkPath.isNotRelative = path =>\n REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path)\n || isNotRelative(path)\n}\n","'use strict';\nmodule.exports = path => {\n\tconst isExtendedLengthPath = /^\\\\\\\\\\?\\\\/.test(path);\n\tconst hasNonAscii = /[^\\u0000-\\u0080]+/.test(path); // eslint-disable-line no-control-regex\n\n\tif (isExtendedLengthPath || hasNonAscii) {\n\t\treturn path;\n\t}\n\n\treturn path.replace(/\\\\/g, '/');\n};\n","'use strict';\nconst {promisify} = require('util');\nconst fs = require('fs');\nconst path = require('path');\nconst fastGlob = require('fast-glob');\nconst gitIgnore = require('ignore');\nconst slash = require('slash');\n\nconst DEFAULT_IGNORE = [\n\t'**/node_modules/**',\n\t'**/flow-typed/**',\n\t'**/coverage/**',\n\t'**/.git'\n];\n\nconst readFileP = promisify(fs.readFile);\n\nconst mapGitIgnorePatternTo = base => ignore => {\n\tif (ignore.startsWith('!')) {\n\t\treturn '!' + path.posix.join(base, ignore.slice(1));\n\t}\n\n\treturn path.posix.join(base, ignore);\n};\n\nconst parseGitIgnore = (content, options) => {\n\tconst base = slash(path.relative(options.cwd, path.dirname(options.fileName)));\n\n\treturn content\n\t\t.split(/\\r?\\n/)\n\t\t.filter(Boolean)\n\t\t.filter(line => !line.startsWith('#'))\n\t\t.map(mapGitIgnorePatternTo(base));\n};\n\nconst reduceIgnore = files => {\n\tconst ignores = gitIgnore();\n\tfor (const file of files) {\n\t\tignores.add(parseGitIgnore(file.content, {\n\t\t\tcwd: file.cwd,\n\t\t\tfileName: file.filePath\n\t\t}));\n\t}\n\n\treturn ignores;\n};\n\nconst ensureAbsolutePathForCwd = (cwd, p) => {\n\tcwd = slash(cwd);\n\tif (path.isAbsolute(p)) {\n\t\tif (slash(p).startsWith(cwd)) {\n\t\t\treturn p;\n\t\t}\n\n\t\tthrow new Error(`Path ${p} is not in cwd ${cwd}`);\n\t}\n\n\treturn path.join(cwd, p);\n};\n\nconst getIsIgnoredPredecate = (ignores, cwd) => {\n\treturn p => ignores.ignores(slash(path.relative(cwd, ensureAbsolutePathForCwd(cwd, p.path || p))));\n};\n\nconst getFile = async (file, cwd) => {\n\tconst filePath = path.join(cwd, file);\n\tconst content = await readFileP(filePath, 'utf8');\n\n\treturn {\n\t\tcwd,\n\t\tfilePath,\n\t\tcontent\n\t};\n};\n\nconst getFileSync = (file, cwd) => {\n\tconst filePath = path.join(cwd, file);\n\tconst content = fs.readFileSync(filePath, 'utf8');\n\n\treturn {\n\t\tcwd,\n\t\tfilePath,\n\t\tcontent\n\t};\n};\n\nconst normalizeOptions = ({\n\tignore = [],\n\tcwd = slash(process.cwd())\n} = {}) => {\n\treturn {ignore, cwd};\n};\n\nmodule.exports = async options => {\n\toptions = normalizeOptions(options);\n\n\tconst paths = await fastGlob('**/.gitignore', {\n\t\tignore: DEFAULT_IGNORE.concat(options.ignore),\n\t\tcwd: options.cwd\n\t});\n\n\tconst files = await Promise.all(paths.map(file => getFile(file, options.cwd)));\n\tconst ignores = reduceIgnore(files);\n\n\treturn getIsIgnoredPredecate(ignores, options.cwd);\n};\n\nmodule.exports.sync = options => {\n\toptions = normalizeOptions(options);\n\n\tconst paths = fastGlob.sync('**/.gitignore', {\n\t\tignore: DEFAULT_IGNORE.concat(options.ignore),\n\t\tcwd: options.cwd\n\t});\n\n\tconst files = paths.map(file => getFileSync(file, options.cwd));\n\tconst ignores = reduceIgnore(files);\n\n\treturn getIsIgnoredPredecate(ignores, options.cwd);\n};\n","'use strict';\nconst {Transform} = require('stream');\n\nclass ObjectTransform extends Transform {\n\tconstructor() {\n\t\tsuper({\n\t\t\tobjectMode: true\n\t\t});\n\t}\n}\n\nclass FilterStream extends ObjectTransform {\n\tconstructor(filter) {\n\t\tsuper();\n\t\tthis._filter = filter;\n\t}\n\n\t_transform(data, encoding, callback) {\n\t\tif (this._filter(data)) {\n\t\t\tthis.push(data);\n\t\t}\n\n\t\tcallback();\n\t}\n}\n\nclass UniqueStream extends ObjectTransform {\n\tconstructor() {\n\t\tsuper();\n\t\tthis._pushed = new Set();\n\t}\n\n\t_transform(data, encoding, callback) {\n\t\tif (!this._pushed.has(data)) {\n\t\t\tthis.push(data);\n\t\t\tthis._pushed.add(data);\n\t\t}\n\n\t\tcallback();\n\t}\n}\n\nmodule.exports = {\n\tFilterStream,\n\tUniqueStream\n};\n","'use strict';\nconst fs = require('fs');\nconst arrayUnion = require('array-union');\nconst merge2 = require('merge2');\nconst fastGlob = require('fast-glob');\nconst dirGlob = require('dir-glob');\nconst gitignore = require('./gitignore');\nconst {FilterStream, UniqueStream} = require('./stream-utils');\n\nconst DEFAULT_FILTER = () => false;\n\nconst isNegative = pattern => pattern[0] === '!';\n\nconst assertPatternsInput = patterns => {\n\tif (!patterns.every(pattern => typeof pattern === 'string')) {\n\t\tthrow new TypeError('Patterns must be a string or an array of strings');\n\t}\n};\n\nconst checkCwdOption = (options = {}) => {\n\tif (!options.cwd) {\n\t\treturn;\n\t}\n\n\tlet stat;\n\ttry {\n\t\tstat = fs.statSync(options.cwd);\n\t} catch {\n\t\treturn;\n\t}\n\n\tif (!stat.isDirectory()) {\n\t\tthrow new Error('The `cwd` option must be a path to a directory');\n\t}\n};\n\nconst getPathString = p => p.stats instanceof fs.Stats ? p.path : p;\n\nconst generateGlobTasks = (patterns, taskOptions) => {\n\tpatterns = arrayUnion([].concat(patterns));\n\tassertPatternsInput(patterns);\n\tcheckCwdOption(taskOptions);\n\n\tconst globTasks = [];\n\n\ttaskOptions = {\n\t\tignore: [],\n\t\texpandDirectories: true,\n\t\t...taskOptions\n\t};\n\n\tfor (const [index, pattern] of patterns.entries()) {\n\t\tif (isNegative(pattern)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst ignore = patterns\n\t\t\t.slice(index)\n\t\t\t.filter(pattern => isNegative(pattern))\n\t\t\t.map(pattern => pattern.slice(1));\n\n\t\tconst options = {\n\t\t\t...taskOptions,\n\t\t\tignore: taskOptions.ignore.concat(ignore)\n\t\t};\n\n\t\tglobTasks.push({pattern, options});\n\t}\n\n\treturn globTasks;\n};\n\nconst globDirs = (task, fn) => {\n\tlet options = {};\n\tif (task.options.cwd) {\n\t\toptions.cwd = task.options.cwd;\n\t}\n\n\tif (Array.isArray(task.options.expandDirectories)) {\n\t\toptions = {\n\t\t\t...options,\n\t\t\tfiles: task.options.expandDirectories\n\t\t};\n\t} else if (typeof task.options.expandDirectories === 'object') {\n\t\toptions = {\n\t\t\t...options,\n\t\t\t...task.options.expandDirectories\n\t\t};\n\t}\n\n\treturn fn(task.pattern, options);\n};\n\nconst getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];\n\nconst getFilterSync = options => {\n\treturn options && options.gitignore ?\n\t\tgitignore.sync({cwd: options.cwd, ignore: options.ignore}) :\n\t\tDEFAULT_FILTER;\n};\n\nconst globToTask = task => glob => {\n\tconst {options} = task;\n\tif (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {\n\t\toptions.ignore = dirGlob.sync(options.ignore);\n\t}\n\n\treturn {\n\t\tpattern: glob,\n\t\toptions\n\t};\n};\n\nmodule.exports = async (patterns, options) => {\n\tconst globTasks = generateGlobTasks(patterns, options);\n\n\tconst getFilter = async () => {\n\t\treturn options && options.gitignore ?\n\t\t\tgitignore({cwd: options.cwd, ignore: options.ignore}) :\n\t\t\tDEFAULT_FILTER;\n\t};\n\n\tconst getTasks = async () => {\n\t\tconst tasks = await Promise.all(globTasks.map(async task => {\n\t\t\tconst globs = await getPattern(task, dirGlob);\n\t\t\treturn Promise.all(globs.map(globToTask(task)));\n\t\t}));\n\n\t\treturn arrayUnion(...tasks);\n\t};\n\n\tconst [filter, tasks] = await Promise.all([getFilter(), getTasks()]);\n\tconst paths = await Promise.all(tasks.map(task => fastGlob(task.pattern, task.options)));\n\n\treturn arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));\n};\n\nmodule.exports.sync = (patterns, options) => {\n\tconst globTasks = generateGlobTasks(patterns, options);\n\n\tconst tasks = [];\n\tfor (const task of globTasks) {\n\t\tconst newTask = getPattern(task, dirGlob.sync).map(globToTask(task));\n\t\ttasks.push(...newTask);\n\t}\n\n\tconst filter = getFilterSync(options);\n\n\tlet matches = [];\n\tfor (const task of tasks) {\n\t\tmatches = arrayUnion(matches, fastGlob.sync(task.pattern, task.options));\n\t}\n\n\treturn matches.filter(path_ => !filter(path_));\n};\n\nmodule.exports.stream = (patterns, options) => {\n\tconst globTasks = generateGlobTasks(patterns, options);\n\n\tconst tasks = [];\n\tfor (const task of globTasks) {\n\t\tconst newTask = getPattern(task, dirGlob.sync).map(globToTask(task));\n\t\ttasks.push(...newTask);\n\t}\n\n\tconst filter = getFilterSync(options);\n\tconst filterStream = new FilterStream(p => !filter(p));\n\tconst uniqueStream = new UniqueStream();\n\n\treturn merge2(tasks.map(task => fastGlob.stream(task.pattern, task.options)))\n\t\t.pipe(filterStream)\n\t\t.pipe(uniqueStream);\n};\n\nmodule.exports.generateGlobTasks = generateGlobTasks;\n\nmodule.exports.hasMagic = (patterns, options) => []\n\t.concat(patterns)\n\t.some(pattern => fastGlob.isDynamicPattern(pattern, options));\n\nmodule.exports.gitignore = gitignore;\n","import path from 'path';\nimport { walk } from 'estree-walker';\nimport MagicString from 'magic-string';\nimport globby from 'globby';\nimport { createFilter } from '@rollup/pluginutils';\n\nclass VariableDynamicImportError extends Error {}\n\n/* eslint-disable-next-line no-template-curly-in-string */\nconst example = 'For example: import(`./foo/${bar}.js`).';\n\nfunction sanitizeString(str) {\n if (str.includes('*')) {\n throw new VariableDynamicImportError('A dynamic import cannot contain * characters.');\n }\n return str;\n}\n\nfunction templateLiteralToGlob(node) {\n let glob = '';\n\n for (let i = 0; i < node.quasis.length; i += 1) {\n glob += sanitizeString(node.quasis[i].value.raw);\n if (node.expressions[i]) {\n glob += expressionToGlob(node.expressions[i]);\n }\n }\n\n return glob;\n}\n\nfunction callExpressionToGlob(node) {\n const { callee } = node;\n if (\n callee.type === 'MemberExpression' &&\n callee.property.type === 'Identifier' &&\n callee.property.name === 'concat'\n ) {\n return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join('')}`;\n }\n return '*';\n}\n\nfunction binaryExpressionToGlob(node) {\n if (node.operator !== '+') {\n throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);\n }\n\n return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;\n}\n\nfunction expressionToGlob(node) {\n switch (node.type) {\n case 'TemplateLiteral':\n return templateLiteralToGlob(node);\n case 'CallExpression':\n return callExpressionToGlob(node);\n case 'BinaryExpression':\n return binaryExpressionToGlob(node);\n case 'Literal': {\n return sanitizeString(node.value);\n }\n default:\n return '*';\n }\n}\n\nfunction dynamicImportToGlob(node, sourceString) {\n let glob = expressionToGlob(node);\n if (!glob.includes('*')) {\n return null;\n }\n glob = glob.replace(/\\*\\*/g, '*');\n\n if (glob.startsWith('*')) {\n throw new VariableDynamicImportError(\n `invalid import \"${sourceString}\". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`\n );\n }\n\n if (glob.startsWith('/')) {\n throw new VariableDynamicImportError(\n `invalid import \"${sourceString}\". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`\n );\n }\n\n if (!glob.startsWith('./') && !glob.startsWith('../')) {\n throw new VariableDynamicImportError(\n `invalid import \"${sourceString}\". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`\n );\n }\n\n // Disallow ./*.ext\n const ownDirectoryStarExtension = /^\\.\\/\\*\\.[\\w]+$/;\n if (ownDirectoryStarExtension.test(glob)) {\n throw new VariableDynamicImportError(\n `${\n `invalid import \"${sourceString}\". Variable imports cannot import their own directory, ` +\n 'place imports in a separate directory or make the import filename more specific. '\n }${example}`\n );\n }\n\n if (path.extname(glob) === '') {\n throw new VariableDynamicImportError(\n `invalid import \"${sourceString}\". A file extension must be included in the static part of the import. ${example}`\n );\n }\n\n return glob;\n}\n\nfunction dynamicImportVariables({ include, exclude, warnOnError } = {}) {\n const filter = createFilter(include, exclude);\n\n return {\n name: 'rollup-plugin-dynamic-import-variables',\n\n transform(code, id) {\n if (!filter(id)) {\n return null;\n }\n\n const parsed = this.parse(code);\n\n let dynamicImportIndex = -1;\n let ms;\n\n walk(parsed, {\n enter: (node) => {\n if (node.type !== 'ImportExpression') {\n return;\n }\n dynamicImportIndex += 1;\n\n try {\n // see if this is a variable dynamic import, and generate a glob expression\n const glob = dynamicImportToGlob(node.source, code.substring(node.start, node.end));\n\n if (!glob) {\n // this was not a variable dynamic import\n return;\n }\n\n // execute the glob\n const result = globby.sync(glob, { cwd: path.dirname(id) });\n const paths = result.map((r) =>\n r.startsWith('./') || r.startsWith('../') ? r : `./${r}`\n );\n\n // create magic string if it wasn't created already\n ms = ms || new MagicString(code);\n // unpack variable dynamic import into a function with import statements per file, rollup\n // will turn these into chunks automatically\n ms.prepend(\n `function __variableDynamicImportRuntime${dynamicImportIndex}__(path) {\n switch (path) {\n${paths.map((p) => ` case '${p}': return import('${p}');`).join('\\n')}\n${` default: return new Promise(function(resolve, reject) {\n (typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)(\n reject.bind(null, new Error(\"Unknown variable dynamic import: \" + path))\n );\n })\\n`} }\n }\\n\\n`\n );\n // call the runtime function instead of doing a dynamic import, the import specifier will\n // be evaluated at runtime and the correct import will be returned by the injected function\n ms.overwrite(\n node.start,\n node.start + 6,\n `__variableDynamicImportRuntime${dynamicImportIndex}__`\n );\n } catch (error) {\n if (error instanceof VariableDynamicImportError) {\n // TODO: line number\n if (warnOnError) {\n this.warn(error);\n } else {\n this.error(error);\n }\n } else {\n this.error(error);\n }\n }\n }\n });\n\n if (ms && dynamicImportIndex !== -1) {\n return {\n code: ms.toString(),\n map: ms.generateMap({\n file: id,\n includeContent: true,\n hires: true\n })\n };\n }\n return null;\n }\n };\n}\n\nexport default dynamicImportVariables;\nexport { VariableDynamicImportError, dynamicImportToGlob };\n","// This is based on @rollup/plugin-data-uri\n// MIT Licensed https://github.com/rollup/plugins/blob/master/LICENSE\n// ref https://github.com/vitejs/vite/issues/1428#issuecomment-757033808\nimport { Plugin } from '../plugin'\nimport { URL } from 'url'\n\nconst dataUriRE = /^([^/]+\\/[^;,]+)(;base64)?,([\\s\\S]*)$/\n\nconst dataUriPrefix = `/@data-uri/`\n\n/**\n * Build only, since importing from a data URI works natively.\n */\nexport function dataURIPlugin(): Plugin {\n let resolved: {\n [key: string]: string\n }\n\n return {\n name: 'vite:data-uri',\n\n buildStart() {\n resolved = {}\n },\n\n resolveId(id) {\n if (!dataUriRE.test(id)) {\n return null\n }\n\n const uri = new URL(id)\n if (uri.protocol !== 'data:') {\n return null\n }\n\n const match = uri.pathname.match(dataUriRE)\n if (!match) {\n return null\n }\n\n const [, mime, format, data] = match\n if (mime !== 'text/javascript') {\n throw new Error(\n `data URI with non-JavaScript mime type is not supported.`\n )\n }\n\n // decode data\n const base64 = format && /base64/i.test(format.substring(1))\n const content = base64\n ? Buffer.from(data, 'base64').toString('utf-8')\n : data\n resolved[id] = content\n return dataUriPrefix + id\n },\n\n load(id) {\n if (id.startsWith(dataUriPrefix)) {\n id = id.slice(dataUriPrefix.length)\n return resolved[id] || null\n }\n }\n }\n}\n","/**\n * @param {object} exports\n * @param {Set} keys\n */\nfunction loop(exports, keys) {\n\tif (typeof exports === 'string') {\n\t\treturn exports;\n\t}\n\n\tif (exports) {\n\t\tlet idx, tmp;\n\t\tif (Array.isArray(exports)) {\n\t\t\tfor (idx=0; idx < exports.length; idx++) {\n\t\t\t\tif (tmp = loop(exports[idx], keys)) return tmp;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (idx in exports) {\n\t\t\t\tif (keys.has(idx)) {\n\t\t\t\t\treturn loop(exports[idx], keys);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * @param {string} name The package name\n * @param {string} entry The target entry, eg \".\"\n * @param {number} [condition] Unmatched condition?\n */\nfunction bail(name, entry, condition) {\n\tthrow new Error(\n\t\tcondition\n\t\t? `No known conditions for \"${entry}\" entry in \"${name}\" package`\n\t\t: `Missing \"${entry}\" export in \"${name}\" package`\n\t);\n}\n\n/**\n * @param {string} name the package name\n * @param {string} entry the target path/import\n */\nfunction toName(name, entry) {\n\treturn entry === name ? '.'\n\t\t: entry[0] === '.' ? entry\n\t\t: entry.replace(new RegExp('^' + name + '\\/'), './');\n}\n\n/**\n * @param {object} pkg package.json contents\n * @param {string} [entry] entry name or import path\n * @param {object} [options]\n * @param {boolean} [options.browser]\n * @param {boolean} [options.require]\n * @param {string[]} [options.conditions]\n */\nexport function resolve(pkg, entry='.', options={}) {\n\tlet { name, exports } = pkg;\n\n\tif (exports) {\n\t\tlet { browser, require, conditions=[] } = options;\n\n\t\tlet target = toName(name, entry);\n\t\tif (target[0] !== '.') target = './' + target;\n\n\t\tif (typeof exports === 'string') {\n\t\t\treturn target === '.' ? exports : bail(name, target);\n\t\t}\n\n\t\tlet allows = new Set(['default', ...conditions]);\n\t\tallows.add(require ? 'require' : 'import');\n\t\tallows.add(browser ? 'browser' : 'node');\n\n\t\tlet key, tmp, isSingle=false;\n\n\t\tfor (key in exports) {\n\t\t\tisSingle = key[0] !== '.';\n\t\t\tbreak;\n\t\t}\n\n\t\tif (isSingle) {\n\t\t\treturn target === '.'\n\t\t\t\t? loop(exports, allows) || bail(name, target, 1)\n\t\t\t\t: bail(name, target);\n\t\t}\n\n\t\tif (tmp = exports[target]) {\n\t\t\treturn loop(tmp, allows) || bail(name, target, 1);\n\t\t}\n\n\t\tfor (key in exports) {\n\t\t\ttmp = key[key.length - 1];\n\t\t\tif (tmp === '/' && target.startsWith(key)) {\n\t\t\t\treturn (tmp = loop(exports[key], allows))\n\t\t\t\t\t? (tmp + target.substring(key.length))\n\t\t\t\t\t: bail(name, target, 1);\n\t\t\t}\n\t\t\tif (tmp === '*' && target.startsWith(key.slice(0, -1))) {\n\t\t\t\t// do not trigger if no *content* to inject\n\t\t\t\tif (target.substring(key.length - 1).length > 0) {\n\t\t\t\t\treturn (tmp = loop(exports[key], allows))\n\t\t\t\t\t\t? tmp.replace('*', target.substring(key.length - 1))\n\t\t\t\t\t\t: bail(name, target, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn bail(name, target);\n\t}\n}\n\n/**\n * @param {object} pkg\n * @param {object} [options]\n * @param {string|boolean} [options.browser]\n * @param {string[]} [options.fields]\n */\nexport function legacy(pkg, options={}) {\n\tlet i=0, value,\n\t\tbrowser = options.browser,\n\t\tfields = options.fields || ['module', 'main'];\n\n\tif (browser && !fields.includes('browser')) {\n\t\tfields.unshift('browser');\n\t}\n\n\tfor (; i < fields.length; i++) {\n\t\tif (value = pkg[fields[i]]) {\n\t\t\tif (typeof value == 'string') {\n\t\t\t\t//\n\t\t\t} else if (typeof value == 'object' && fields[i] == 'browser') {\n\t\t\t\tif (typeof browser == 'string') {\n\t\t\t\t\tvalue = value[browser=toName(pkg.name, browser)];\n\t\t\t\t\tif (value == null) return browser;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\treturn typeof value == 'string'\n\t\t\t\t? ('./' + value.replace(/^\\.?\\//, ''))\n\t\t\t\t: value;\n\t\t}\n\t}\n}\n","import fs from 'fs'\nimport path from 'path'\nimport { Plugin } from '../plugin'\nimport chalk from 'chalk'\nimport {\n FS_PREFIX,\n SPECIAL_QUERY_RE,\n DEFAULT_EXTENSIONS,\n DEFAULT_MAIN_FIELDS,\n OPTIMIZABLE_ENTRY_RE\n} from '../constants'\nimport {\n isBuiltin,\n bareImportRE,\n createDebugger,\n deepImportRE,\n injectQuery,\n isExternalUrl,\n isObject,\n normalizePath,\n fsPathFromId,\n ensureVolumeInPath,\n resolveFrom,\n isDataUrl,\n cleanUrl,\n slash,\n nestedResolveFrom\n} from '../utils'\nimport { ViteDevServer, SSROptions } from '..'\nimport { createFilter } from '@rollup/pluginutils'\nimport { PartialResolvedId } from 'rollup'\nimport { resolve as _resolveExports } from 'resolve.exports'\n\n// special id for paths marked with browser: false\n// https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module\nexport const browserExternalId = '__vite-browser-external'\n\nconst isDebug = process.env.DEBUG\nconst debug = createDebugger('vite:resolve-details', {\n onlyWhenFocused: true\n})\n\nexport interface ResolveOptions {\n mainFields?: string[]\n conditions?: string[]\n extensions?: string[]\n dedupe?: string[]\n}\n\nexport interface InternalResolveOptions extends ResolveOptions {\n root: string\n isBuild: boolean\n isProduction: boolean\n ssrConfig?: SSROptions\n /**\n * src code mode also attempts the following:\n * - resolving /xxx as URLs\n * - resolving bare imports from optimized deps\n */\n asSrc?: boolean\n tryIndex?: boolean\n tryPrefix?: string\n skipPackageJson?: boolean\n preferRelative?: boolean\n isRequire?: boolean\n}\n\nexport function resolvePlugin(baseOptions: InternalResolveOptions): Plugin {\n const {\n root,\n isProduction,\n asSrc,\n ssrConfig,\n preferRelative = false\n } = baseOptions\n const requireOptions: InternalResolveOptions = {\n ...baseOptions,\n isRequire: true\n }\n let server: ViteDevServer | undefined\n\n const { target: ssrTarget, noExternal: ssrNoExternal } = ssrConfig ?? {}\n\n return {\n name: 'vite:resolve',\n\n configureServer(_server) {\n server = _server\n },\n\n resolveId(id, importer, resolveOpts, ssr) {\n if (id.startsWith(browserExternalId)) {\n return id\n }\n\n // fast path for commonjs proxy modules\n if (/\\?commonjs/.test(id) || id === 'commonjsHelpers.js') {\n return\n }\n\n const targetWeb = !ssr || ssrTarget === 'webworker'\n\n // this is passed by @rollup/plugin-commonjs\n const isRequire =\n resolveOpts &&\n resolveOpts.custom &&\n resolveOpts.custom['node-resolve'] &&\n resolveOpts.custom['node-resolve'].isRequire\n\n const options = isRequire ? requireOptions : baseOptions\n\n let res: string | PartialResolvedId | undefined\n\n // explicit fs paths that starts with /@fs/*\n if (asSrc && id.startsWith(FS_PREFIX)) {\n const fsPath = fsPathFromId(id)\n res = tryFsResolve(fsPath, options)\n isDebug && debug(`[@fs] ${chalk.cyan(id)} -> ${chalk.dim(res)}`)\n // always return here even if res doesn't exist since /@fs/ is explicit\n // if the file doesn't exist it should be a 404\n return res || fsPath\n }\n\n // URL\n // /foo -> /fs-root/foo\n if (asSrc && id.startsWith('/')) {\n const fsPath = path.resolve(root, id.slice(1))\n if ((res = tryFsResolve(fsPath, options))) {\n isDebug && debug(`[url] ${chalk.cyan(id)} -> ${chalk.dim(res)}`)\n return res\n }\n }\n\n // relative\n if (id.startsWith('.') || (preferRelative && /^\\w/.test(id))) {\n const basedir = importer ? path.dirname(importer) : process.cwd()\n const fsPath = path.resolve(basedir, id)\n // handle browser field mapping for relative imports\n\n const normalizedFsPath = normalizePath(fsPath)\n const pathFromBasedir = normalizedFsPath.slice(basedir.length)\n if (pathFromBasedir.startsWith('/node_modules/')) {\n // normalize direct imports from node_modules to bare imports, so the\n // hashing logic is shared and we avoid duplicated modules #2503\n const bareImport = pathFromBasedir.slice('/node_modules/'.length)\n if (\n (res = tryNodeResolve(\n bareImport,\n importer,\n options,\n targetWeb,\n server,\n ssr\n )) &&\n res.id.startsWith(normalizedFsPath)\n ) {\n return res\n }\n }\n\n if (\n targetWeb &&\n (res = tryResolveBrowserMapping(fsPath, importer, options, true))\n ) {\n return res\n }\n\n if ((res = tryFsResolve(fsPath, options))) {\n isDebug && debug(`[relative] ${chalk.cyan(id)} -> ${chalk.dim(res)}`)\n const pkg = importer != null && idToPkgMap.get(importer)\n if (pkg) {\n idToPkgMap.set(res, pkg)\n return {\n id: res,\n moduleSideEffects: pkg.hasSideEffects(res)\n }\n }\n return res\n }\n }\n\n // absolute fs paths\n if (path.isAbsolute(id) && (res = tryFsResolve(id, options))) {\n isDebug && debug(`[fs] ${chalk.cyan(id)} -> ${chalk.dim(res)}`)\n return res\n }\n\n // external\n if (isExternalUrl(id)) {\n return {\n id,\n external: true\n }\n }\n\n // data uri: pass through (this only happens during build and will be\n // handled by dedicated plugin)\n if (isDataUrl(id)) {\n return null\n }\n\n // bare package imports, perform node resolve\n if (bareImportRE.test(id)) {\n if (\n asSrc &&\n server &&\n !ssr &&\n (res = tryOptimizedResolve(id, server, importer))\n ) {\n return res\n }\n\n if (\n targetWeb &&\n (res = tryResolveBrowserMapping(id, importer, options, false))\n ) {\n return res\n }\n\n if (\n (res = tryNodeResolve(id, importer, options, targetWeb, server, ssr))\n ) {\n return res\n }\n\n // node built-ins.\n // externalize if building for SSR, otherwise redirect to empty module\n if (isBuiltin(id)) {\n if (ssr) {\n if (ssrNoExternal === true) {\n let message = `Cannot bundle Node.js built-in \"${id}\"`\n if (importer) {\n message += ` imported from \"${path.relative(\n process.cwd(),\n importer\n )}\"`\n }\n message += `. Consider disabling ssr.noExternal or remove the built-in dependency.`\n this.error(message)\n }\n\n return {\n id,\n external: true\n }\n } else {\n if (!asSrc) {\n debug(\n `externalized node built-in \"${id}\" to empty module. ` +\n `(imported by: ${chalk.white.dim(importer)})`\n )\n }\n return isProduction\n ? browserExternalId\n : `${browserExternalId}:${id}`\n }\n }\n }\n\n isDebug && debug(`[fallthrough] ${chalk.dim(id)}`)\n },\n\n load(id) {\n if (id.startsWith(browserExternalId)) {\n return isProduction\n ? `export default {}`\n : `export default new Proxy({}, {\n get() {\n throw new Error('Module \"${id.slice(\n browserExternalId.length + 1\n )}\" has been externalized for browser compatibility and cannot be accessed in client code.')\n }\n})`\n }\n }\n }\n}\n\nfunction tryFsResolve(\n fsPath: string,\n options: InternalResolveOptions,\n tryIndex = true,\n targetWeb = true\n): string | undefined {\n let file = fsPath\n let postfix = ''\n\n let postfixIndex = fsPath.indexOf('?')\n if (postfixIndex < 0) {\n postfixIndex = fsPath.indexOf('#')\n }\n if (postfixIndex > 0) {\n file = fsPath.slice(0, postfixIndex)\n postfix = fsPath.slice(postfixIndex)\n }\n\n let res: string | undefined\n if (\n (res = tryResolveFile(\n file,\n postfix,\n options,\n false,\n targetWeb,\n options.tryPrefix,\n options.skipPackageJson\n ))\n ) {\n return res\n }\n\n for (const ext of options.extensions || DEFAULT_EXTENSIONS) {\n if (\n (res = tryResolveFile(\n file + ext,\n postfix,\n options,\n false,\n targetWeb,\n options.tryPrefix,\n options.skipPackageJson\n ))\n ) {\n return res\n }\n }\n\n if (\n (res = tryResolveFile(\n file,\n postfix,\n options,\n tryIndex,\n targetWeb,\n options.tryPrefix,\n options.skipPackageJson\n ))\n ) {\n return res\n }\n}\n\nfunction tryResolveFile(\n file: string,\n postfix: string,\n options: InternalResolveOptions,\n tryIndex: boolean,\n targetWeb: boolean,\n tryPrefix?: string,\n skipPackageJson?: boolean\n): string | undefined {\n let isReadable = false\n try {\n // #2051 if we don't have read permission on a directory, existsSync() still\n // works and will result in massively slow subsequent checks (which are\n // unnecessary in the first place)\n fs.accessSync(file, fs.constants.R_OK)\n isReadable = true\n } catch (e) {}\n if (isReadable) {\n if (!fs.statSync(file).isDirectory()) {\n return normalizePath(ensureVolumeInPath(file)) + postfix\n } else if (tryIndex) {\n if (!skipPackageJson) {\n const pkgPath = file + '/package.json'\n if (fs.existsSync(pkgPath)) {\n // path points to a node package\n const pkg = loadPackageData(pkgPath)\n return resolvePackageEntry(file, pkg, options, targetWeb)\n }\n }\n const index = tryFsResolve(file + '/index', options)\n if (index) return index + postfix\n }\n }\n if (tryPrefix) {\n const prefixed = `${path.dirname(file)}/${tryPrefix}${path.basename(file)}`\n return tryResolveFile(prefixed, postfix, options, tryIndex, targetWeb)\n }\n}\n\nexport const idToPkgMap = new Map()\n\nexport function tryNodeResolve(\n id: string,\n importer: string | undefined,\n options: InternalResolveOptions,\n targetWeb: boolean,\n server?: ViteDevServer,\n ssr?: boolean\n): PartialResolvedId | undefined {\n const { root, dedupe, isBuild } = options\n\n // split id by last '>' for nested selected packages, for example:\n // 'foo > bar > baz' => 'foo > bar' & 'baz'\n // 'foo' => '' & 'foo'\n const lastArrowIndex = id.lastIndexOf('>')\n const nestedRoot = id.substring(0, lastArrowIndex).trim()\n const nestedPath = id.substring(lastArrowIndex + 1).trim()\n\n // check for deep import, e.g. \"my-lib/foo\"\n const deepMatch = nestedPath.match(deepImportRE)\n\n const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : nestedPath\n\n let basedir: string\n if (dedupe && dedupe.includes(pkgId)) {\n basedir = root\n } else if (\n importer &&\n path.isAbsolute(importer) &&\n fs.existsSync(cleanUrl(importer))\n ) {\n basedir = path.dirname(importer)\n } else {\n basedir = root\n }\n\n // nested node module, step-by-step resolve to the basedir of the nestedPath\n if (nestedRoot) {\n basedir = nestedResolveFrom(nestedRoot, basedir)\n }\n\n const pkg = resolvePackageData(pkgId, basedir)\n\n if (!pkg) {\n return\n }\n\n let resolved = deepMatch\n ? resolveDeepImport(id, pkg, options, targetWeb)\n : resolvePackageEntry(id, pkg, options, targetWeb)\n if (!resolved) {\n return\n }\n // link id to pkg for browser field mapping check\n idToPkgMap.set(resolved, pkg)\n if (isBuild) {\n // Resolve package side effects for build so that rollup can better\n // perform tree-shaking\n return {\n id: resolved,\n moduleSideEffects: pkg.hasSideEffects(resolved)\n }\n } else {\n if (\n !resolved.includes('node_modules') || // linked\n !server || // build\n server._isRunningOptimizer || // optimizing\n !server._optimizeDepsMetadata\n ) {\n return { id: resolved }\n }\n // if we reach here, it's a valid dep import that hasn't been optimized.\n const isJsType = OPTIMIZABLE_ENTRY_RE.test(resolved)\n const exclude = server.config.optimizeDeps?.exclude\n if (\n !isJsType ||\n importer?.includes('node_modules') ||\n exclude?.includes(pkgId) ||\n exclude?.includes(id) ||\n SPECIAL_QUERY_RE.test(resolved)\n ) {\n // excluded from optimization\n // Inject a version query to npm deps so that the browser\n // can cache it without re-validation, but only do so for known js types.\n // otherwise we may introduce duplicated modules for externalized files\n // from pre-bundled deps.\n const versionHash = server._optimizeDepsMetadata?.browserHash\n if (versionHash && isJsType) {\n resolved = injectQuery(resolved, `v=${versionHash}`)\n }\n } else {\n // this is a missing import.\n // queue optimize-deps re-run.\n server._registerMissingImport?.(id, resolved, ssr)\n }\n return { id: resolved }\n }\n}\n\nexport function tryOptimizedResolve(\n id: string,\n server: ViteDevServer,\n importer?: string\n): string | undefined {\n const cacheDir = server.config.cacheDir\n const depData = server._optimizeDepsMetadata\n\n if (!cacheDir || !depData) return\n\n const getOptimizedUrl = (optimizedData: typeof depData.optimized[string]) => {\n return (\n optimizedData.file +\n `?v=${depData.browserHash}${\n optimizedData.needsInterop ? `&es-interop` : ``\n }`\n )\n }\n\n // check if id has been optimized\n const isOptimized = depData.optimized[id]\n if (isOptimized) {\n return getOptimizedUrl(isOptimized)\n }\n\n if (!importer) return\n\n // further check if id is imported by nested dependency\n let resolvedSrc: string | undefined\n\n for (const [pkgPath, optimizedData] of Object.entries(depData.optimized)) {\n // check for scenarios, e.g.\n // pkgPath => \"my-lib > foo\"\n // id => \"foo\"\n // this narrows the need to do a full resolve\n if (!pkgPath.endsWith(id)) continue\n\n // lazily initialize resolvedSrc\n if (resolvedSrc == null) {\n try {\n // this may throw errors if unable to resolve, e.g. aliased id\n resolvedSrc = normalizePath(resolveFrom(id, path.dirname(importer)))\n } catch {\n // this is best-effort only so swallow errors\n break\n }\n }\n\n // match by src to correctly identify if id belongs to nested dependency\n if (optimizedData.src === resolvedSrc) {\n return getOptimizedUrl(optimizedData)\n }\n }\n}\n\nexport interface PackageData {\n dir: string\n hasSideEffects: (id: string) => boolean\n webResolvedImports: Record\n nodeResolvedImports: Record\n setResolvedCache: (key: string, entry: string, targetWeb: boolean) => void\n getResolvedCache: (key: string, targetWeb: boolean) => string | undefined\n data: {\n [field: string]: any\n version: string\n main: string\n module: string\n browser: string | Record\n exports: string | Record | string[]\n dependencies: Record\n }\n}\n\nconst packageCache = new Map()\n\nexport function resolvePackageData(\n id: string,\n basedir: string\n): PackageData | undefined {\n const cacheKey = id + basedir\n if (packageCache.has(cacheKey)) {\n return packageCache.get(cacheKey)\n }\n try {\n const pkgPath = resolveFrom(`${id}/package.json`, basedir)\n return loadPackageData(pkgPath, cacheKey)\n } catch (e) {\n isDebug && debug(`${chalk.red(`[failed loading package.json]`)} ${id}`)\n }\n}\n\nfunction loadPackageData(pkgPath: string, cacheKey = pkgPath) {\n const data = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))\n const pkgDir = path.dirname(pkgPath)\n const { sideEffects } = data\n let hasSideEffects: (id: string) => boolean\n if (typeof sideEffects === 'boolean') {\n hasSideEffects = () => sideEffects\n } else if (Array.isArray(sideEffects)) {\n hasSideEffects = createFilter(sideEffects, null, { resolve: pkgDir })\n } else {\n hasSideEffects = () => true\n }\n\n const pkg: PackageData = {\n dir: pkgDir,\n data,\n hasSideEffects,\n webResolvedImports: {},\n nodeResolvedImports: {},\n setResolvedCache(key: string, entry: string, targetWeb: boolean) {\n if (targetWeb) {\n pkg.webResolvedImports[key] = entry\n } else {\n pkg.nodeResolvedImports[key] = entry\n }\n },\n getResolvedCache(key: string, targetWeb: boolean) {\n if (targetWeb) {\n return pkg.webResolvedImports[key]\n } else {\n return pkg.nodeResolvedImports[key]\n }\n }\n }\n packageCache.set(cacheKey, pkg)\n return pkg\n}\n\nexport function resolvePackageEntry(\n id: string,\n { dir, data, setResolvedCache, getResolvedCache }: PackageData,\n options: InternalResolveOptions,\n targetWeb: boolean\n): string | undefined {\n const cached = getResolvedCache('.', targetWeb)\n if (cached) {\n return cached\n }\n try {\n let entryPoint: string | undefined | void\n\n // resolve exports field with highest priority\n // using https://github.com/lukeed/resolve.exports\n if (data.exports) {\n entryPoint = resolveExports(data, '.', options, targetWeb)\n }\n\n // if exports resolved to .mjs, still resolve other fields.\n // This is because .mjs files can technically import .cjs files which would\n // make them invalid for pure ESM environments - so if other module/browser\n // fields are present, prioritize those instead.\n if (targetWeb && (!entryPoint || entryPoint.endsWith('.mjs'))) {\n // check browser field\n // https://github.com/defunctzombie/package-browser-field-spec\n const browserEntry =\n typeof data.browser === 'string'\n ? data.browser\n : isObject(data.browser) && data.browser['.']\n if (browserEntry) {\n // check if the package also has a \"module\" field.\n if (typeof data.module === 'string' && data.module !== browserEntry) {\n // if both are present, we may have a problem: some package points both\n // to ESM, with \"module\" targeting Node.js, while some packages points\n // \"module\" to browser ESM and \"browser\" to UMD.\n // the heuristics here is to actually read the browser entry when\n // possible and check for hints of UMD. If it is UMD, prefer \"module\"\n // instead; Otherwise, assume it's ESM and use it.\n const resolvedBrowserEntry = tryFsResolve(\n path.join(dir, browserEntry),\n options\n )\n if (resolvedBrowserEntry) {\n const content = fs.readFileSync(resolvedBrowserEntry, 'utf-8')\n if (\n (/typeof exports\\s*==/.test(content) &&\n /typeof module\\s*==/.test(content)) ||\n /module\\.exports\\s*=/.test(content)\n ) {\n // likely UMD or CJS(!!! e.g. firebase 7.x), prefer module\n entryPoint = data.module\n }\n }\n } else {\n entryPoint = browserEntry\n }\n }\n }\n\n if (!entryPoint || entryPoint.endsWith('.mjs')) {\n for (const field of options.mainFields || DEFAULT_MAIN_FIELDS) {\n if (typeof data[field] === 'string') {\n entryPoint = data[field]\n break\n }\n }\n }\n\n entryPoint = entryPoint || data.main || 'index.js'\n\n // make sure we don't get scripts when looking for sass\n if (\n options.mainFields?.[0] === 'sass' &&\n !options.extensions?.includes(path.extname(entryPoint))\n ) {\n entryPoint = ''\n options.skipPackageJson = true\n }\n\n // resolve object browser field in package.json\n const { browser: browserField } = data\n if (targetWeb && isObject(browserField)) {\n entryPoint = mapWithBrowserField(entryPoint, browserField) || entryPoint\n }\n\n entryPoint = path.join(dir, entryPoint)\n const resolvedEntryPoint = tryFsResolve(entryPoint, options)\n\n if (resolvedEntryPoint) {\n isDebug &&\n debug(\n `[package entry] ${chalk.cyan(id)} -> ${chalk.dim(\n resolvedEntryPoint\n )}`\n )\n setResolvedCache('.', resolvedEntryPoint, targetWeb)\n return resolvedEntryPoint\n } else {\n packageEntryFailure(id)\n }\n } catch (e) {\n packageEntryFailure(id, e.message)\n }\n}\n\nfunction packageEntryFailure(id: string, details?: string) {\n throw new Error(\n `Failed to resolve entry for package \"${id}\". ` +\n `The package may have incorrect main/module/exports specified in its package.json` +\n (details ? ': ' + details : '.')\n )\n}\n\nfunction resolveExports(\n pkg: PackageData['data'],\n key: string,\n options: InternalResolveOptions,\n targetWeb: boolean\n) {\n const conditions = [options.isProduction ? 'production' : 'development']\n if (!options.isRequire) {\n conditions.push('module')\n }\n if (options.conditions) {\n conditions.push(...options.conditions)\n }\n return _resolveExports(pkg, key, {\n browser: targetWeb,\n require: options.isRequire,\n conditions\n })\n}\n\nfunction resolveDeepImport(\n id: string,\n {\n webResolvedImports,\n setResolvedCache,\n getResolvedCache,\n dir,\n data\n }: PackageData,\n options: InternalResolveOptions,\n targetWeb: boolean\n): string | undefined {\n id = '.' + id.slice(data.name.length)\n const cache = getResolvedCache(id, targetWeb)\n if (cache) {\n return cache\n }\n\n let relativeId: string | undefined | void = id\n const { exports: exportsField, browser: browserField } = data\n\n // map relative based on exports data\n if (exportsField) {\n if (isObject(exportsField) && !Array.isArray(exportsField)) {\n relativeId = resolveExports(data, relativeId, options, targetWeb)\n } else {\n // not exposed\n relativeId = undefined\n }\n if (!relativeId) {\n throw new Error(\n `Package subpath '${relativeId}' is not defined by \"exports\" in ` +\n `${path.join(dir, 'package.json')}.`\n )\n }\n } else if (targetWeb && isObject(browserField)) {\n const mapped = mapWithBrowserField(relativeId, browserField)\n if (mapped) {\n relativeId = mapped\n } else if (mapped === false) {\n return (webResolvedImports[id] = browserExternalId)\n }\n }\n\n if (relativeId) {\n const resolved = tryFsResolve(\n path.join(dir, relativeId),\n options,\n !exportsField, // try index only if no exports field\n targetWeb\n )\n if (resolved) {\n isDebug &&\n debug(`[node/deep-import] ${chalk.cyan(id)} -> ${chalk.dim(resolved)}`)\n setResolvedCache(id, resolved, targetWeb)\n return resolved\n }\n }\n}\n\nfunction tryResolveBrowserMapping(\n id: string,\n importer: string | undefined,\n options: InternalResolveOptions,\n isFilePath: boolean\n) {\n let res: string | undefined\n const pkg = importer && idToPkgMap.get(importer)\n if (pkg && isObject(pkg.data.browser)) {\n const mapId = isFilePath ? './' + slash(path.relative(pkg.dir, id)) : id\n const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser)\n if (browserMappedPath) {\n const fsPath = path.join(pkg.dir, browserMappedPath)\n if ((res = tryFsResolve(fsPath, options))) {\n isDebug &&\n debug(`[browser mapped] ${chalk.cyan(id)} -> ${chalk.dim(res)}`)\n idToPkgMap.set(res, pkg)\n return {\n id: res,\n moduleSideEffects: pkg.hasSideEffects(res)\n }\n }\n } else if (browserMappedPath === false) {\n return browserExternalId\n }\n }\n}\n\n/**\n * given a relative path in pkg dir,\n * return a relative path in pkg dir,\n * mapped with the \"map\" object\n *\n * - Returning `undefined` means there is no browser mapping for this id\n * - Returning `false` means this id is explicitly externalized for browser\n */\nfunction mapWithBrowserField(\n relativePathInPkgDir: string,\n map: Record\n): string | false | undefined {\n const normalizedPath = path.posix.normalize(relativePathInPkgDir)\n\n for (const key in map) {\n const normalizedKey = path.posix.normalize(key)\n if (\n normalizedPath === normalizedKey ||\n equalWithoutSuffix(normalizedPath, normalizedKey, '.js') ||\n equalWithoutSuffix(normalizedPath, normalizedKey, '/index.js')\n ) {\n return map[key]\n }\n }\n}\n\nfunction equalWithoutSuffix(path: string, key: string, suffix: string) {\n return key.endsWith(suffix) && key.slice(0, -suffix.length) === path\n}\n","import fs from 'fs'\nimport path from 'path'\nimport { tryNodeResolve, InternalResolveOptions } from '../plugins/resolve'\nimport { isDefined, lookupFile, resolveFrom, unique } from '../utils'\nimport { ResolvedConfig } from '..'\nimport { createFilter } from '@rollup/pluginutils'\n\n/**\n * Heuristics for determining whether a dependency should be externalized for\n * server-side rendering.\n *\n * TODO right now externals are imported using require(), we probably need to\n * rework this when more libraries ship native ESM distributions for Node.\n */\nexport function resolveSSRExternal(\n config: ResolvedConfig,\n knownImports: string[],\n ssrExternals: Set = new Set(),\n seen: Set = new Set()\n): string[] {\n if (config.ssr?.noExternal === true) {\n return []\n }\n\n const { root } = config\n const pkgContent = lookupFile(root, ['package.json'])\n if (!pkgContent) {\n return []\n }\n const pkg = JSON.parse(pkgContent)\n const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined)\n const deps = unique([\n ...importedDeps,\n ...Object.keys(pkg.devDependencies || {}),\n ...Object.keys(pkg.dependencies || {})\n ])\n\n const resolveOptions: InternalResolveOptions = {\n root,\n isProduction: false,\n isBuild: true\n }\n\n const depsToTrace = new Set()\n\n for (const id of deps) {\n if (seen.has(id)) {\n continue\n }\n seen.add(id)\n\n let entry: string | undefined\n let requireEntry: string\n try {\n entry = tryNodeResolve(\n id,\n undefined,\n resolveOptions,\n true,\n undefined,\n true\n )?.id\n requireEntry = require.resolve(id, { paths: [root] })\n } catch (e) {\n // resolve failed, assume include\n continue\n }\n if (!entry) {\n // no esm entry but has require entry (is this even possible?)\n ssrExternals.add(id)\n continue\n }\n if (!entry.includes('node_modules')) {\n // entry is not a node dep, possibly linked - don't externalize\n // instead, trace its dependencies.\n depsToTrace.add(id)\n continue\n }\n if (entry !== requireEntry) {\n // has separate esm/require entry, assume require entry is cjs\n ssrExternals.add(id)\n } else {\n // node resolve and esm resolve resolves to the same file.\n if (!/\\.m?js$/.test(entry)) {\n // entry is not js, cannot externalize\n continue\n }\n // check if the entry is cjs\n const content = fs.readFileSync(entry, 'utf-8')\n if (/\\bmodule\\.exports\\b|\\bexports[.\\[]|\\brequire\\s*\\(/.test(content)) {\n ssrExternals.add(id)\n }\n }\n }\n\n for (const id of depsToTrace) {\n const depRoot = path.dirname(resolveFrom(`${id}/package.json`, root))\n resolveSSRExternal(\n {\n ...config,\n root: depRoot\n },\n knownImports,\n ssrExternals,\n seen\n )\n }\n\n if (config.ssr?.external) {\n config.ssr.external.forEach((id) => ssrExternals.add(id))\n }\n let externals = [...ssrExternals]\n if (config.ssr?.noExternal) {\n const filter = createFilter(undefined, config.ssr.noExternal, {\n resolve: false\n })\n externals = externals.filter((id) => filter(id))\n }\n return externals.filter((id) => id !== 'vite')\n}\n\nexport function shouldExternalizeForSSR(\n id: string,\n externals: string[]\n): boolean {\n const should = externals.some((e) => {\n if (id === e) {\n return true\n }\n // deep imports, check ext before externalizing - only externalize\n // extension-less imports and explicit .js imports\n if (id.startsWith(e + '/') && (!path.extname(id) || id.endsWith('.js'))) {\n return true\n }\n })\n return should\n}\n\nfunction getNpmPackageName(importPath: string): string | null {\n const parts = importPath.split('/')\n if (parts[0].startsWith('@')) {\n if (!parts[1]) return null\n return `${parts[0]}/${parts[1]}`\n } else {\n return parts[0]\n }\n}\n","import { relative } from 'path'\nimport { normalizePath } from '@rollup/pluginutils'\nimport { ResolvedConfig } from '..'\nimport { Plugin } from '../plugin'\nimport { chunkToEmittedCssFileMap } from '../plugins/css'\nimport { chunkToEmittedAssetsMap } from '../plugins/asset'\n\nexport function ssrManifestPlugin(config: ResolvedConfig): Plugin {\n // module id => preload assets mapping\n const ssrManifest: Record = {}\n const base = config.base\n\n return {\n name: 'vite:manifest',\n generateBundle(_options, bundle) {\n for (const file in bundle) {\n const chunk = bundle[file]\n if (chunk.type === 'chunk') {\n // links for certain entry chunks are already generated in static HTML\n // in those cases we only need to record info for non-entry chunks\n const cssFiles = chunk.isEntry\n ? null\n : chunkToEmittedCssFileMap.get(chunk)\n const assetFiles = chunkToEmittedAssetsMap.get(chunk)\n for (const id in chunk.modules) {\n const normalizedId = normalizePath(relative(config.root, id))\n const mappedChunks =\n ssrManifest[normalizedId] || (ssrManifest[normalizedId] = [])\n if (!chunk.isEntry) {\n mappedChunks.push(base + chunk.fileName)\n }\n if (cssFiles) {\n cssFiles.forEach((file) => {\n mappedChunks.push(base + file)\n })\n }\n if (assetFiles) {\n assetFiles.forEach((file) => {\n mappedChunks.push(base + file)\n })\n }\n }\n }\n }\n\n this.emitFile({\n fileName: 'ssr-manifest.json',\n type: 'asset',\n source: JSON.stringify(ssrManifest, null, 2)\n })\n }\n }\n}\n","// Reserved word lists for various dialects of the language\n\nvar reservedWords = {\n 3: \"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile\",\n 5: \"class enum extends super const export import\",\n 6: \"enum\",\n strict: \"implements interface let package private protected public static yield\",\n strictBind: \"eval arguments\"\n};\n\n// And the keywords\n\nvar ecma5AndLessKeywords = \"break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this\";\n\nvar keywords = {\n 5: ecma5AndLessKeywords,\n \"5module\": ecma5AndLessKeywords + \" export import\",\n 6: ecma5AndLessKeywords + \" const class extends export import super\"\n};\n\nvar keywordRelationalOperator = /^in(stanceof)?$/;\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point above 128.\n// Generated by `bin/generate-identifier-regex.js`.\nvar nonASCIIidentifierStartChars = \"\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u08a0-\\u08b4\\u08b6-\\u08c7\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d04-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e86-\\u0e8a\\u0e8c-\\u0ea3\\u0ea5\\u0ea7-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c88\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf3\\u1cf5\\u1cf6\\u1cfa\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31bf\\u31f0-\\u31ff\\u3400-\\u4dbf\\u4e00-\\u9ffc\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7bf\\ua7c2-\\ua7ca\\ua7f5-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab69\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\";\nvar nonASCIIidentifierChars = \"\\u200c\\u200d\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u08d3-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u09fe\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0afa-\\u0aff\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b55-\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c04\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0d00-\\u0d03\\u0d3b\\u0d3c\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d81-\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0ebc\\u0ec8-\\u0ecd\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u1810-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1abf\\u1ac0\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf4\\u1cf7-\\u1cf9\\u1dc0-\\u1df9\\u1dfb-\\u1dff\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua82c\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua8ff-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f\";\n\nvar nonASCIIidentifierStart = new RegExp(\"[\" + nonASCIIidentifierStartChars + \"]\");\nvar nonASCIIidentifier = new RegExp(\"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\");\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by bin/generate-identifier-regex.js\n\n// eslint-disable-next-line comma-spacing\nvar astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];\n\n// eslint-disable-next-line comma-spacing\nvar astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code, set) {\n var pos = 0x10000;\n for (var i = 0; i < set.length; i += 2) {\n pos += set[i];\n if (pos > code) { return false }\n pos += set[i + 1];\n if (pos >= code) { return true }\n }\n}\n\n// Test whether a given character code starts an identifier.\n\nfunction isIdentifierStart(code, astral) {\n if (code < 65) { return code === 36 }\n if (code < 91) { return true }\n if (code < 97) { return code === 95 }\n if (code < 123) { return true }\n if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }\n if (astral === false) { return false }\n return isInAstralSet(code, astralIdentifierStartCodes)\n}\n\n// Test whether a given character is part of an identifier.\n\nfunction isIdentifierChar(code, astral) {\n if (code < 48) { return code === 36 }\n if (code < 58) { return true }\n if (code < 65) { return false }\n if (code < 91) { return true }\n if (code < 97) { return code === 95 }\n if (code < 123) { return true }\n if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }\n if (astral === false) { return false }\n return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)\n}\n\n// ## Token types\n\n// The assignment of fine-grained, information-carrying type objects\n// allows the tokenizer to store the information it has about a\n// token in a way that is very cheap for the parser to look up.\n\n// All token type variables start with an underscore, to make them\n// easy to recognize.\n\n// The `beforeExpr` property is used to disambiguate between regular\n// expressions and divisions. It is set on all token types that can\n// be followed by an expression (thus, a slash after them would be a\n// regular expression).\n//\n// The `startsExpr` property is used to check if the token ends a\n// `yield` expression. It is set on all token types that either can\n// directly start an expression (like a quotation mark) or can\n// continue an expression (like the body of a string).\n//\n// `isLoop` marks a keyword as starting a loop, which is important\n// to know when parsing a label, in order to allow or disallow\n// continue jumps to that label.\n\nvar TokenType = function TokenType(label, conf) {\n if ( conf === void 0 ) conf = {};\n\n this.label = label;\n this.keyword = conf.keyword;\n this.beforeExpr = !!conf.beforeExpr;\n this.startsExpr = !!conf.startsExpr;\n this.isLoop = !!conf.isLoop;\n this.isAssign = !!conf.isAssign;\n this.prefix = !!conf.prefix;\n this.postfix = !!conf.postfix;\n this.binop = conf.binop || null;\n this.updateContext = null;\n};\n\nfunction binop(name, prec) {\n return new TokenType(name, {beforeExpr: true, binop: prec})\n}\nvar beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};\n\n// Map keyword names to token types.\n\nvar keywords$1 = {};\n\n// Succinct definitions of keyword token types\nfunction kw(name, options) {\n if ( options === void 0 ) options = {};\n\n options.keyword = name;\n return keywords$1[name] = new TokenType(name, options)\n}\n\nvar types = {\n num: new TokenType(\"num\", startsExpr),\n regexp: new TokenType(\"regexp\", startsExpr),\n string: new TokenType(\"string\", startsExpr),\n name: new TokenType(\"name\", startsExpr),\n privateId: new TokenType(\"privateId\", startsExpr),\n eof: new TokenType(\"eof\"),\n\n // Punctuation token types.\n bracketL: new TokenType(\"[\", {beforeExpr: true, startsExpr: true}),\n bracketR: new TokenType(\"]\"),\n braceL: new TokenType(\"{\", {beforeExpr: true, startsExpr: true}),\n braceR: new TokenType(\"}\"),\n parenL: new TokenType(\"(\", {beforeExpr: true, startsExpr: true}),\n parenR: new TokenType(\")\"),\n comma: new TokenType(\",\", beforeExpr),\n semi: new TokenType(\";\", beforeExpr),\n colon: new TokenType(\":\", beforeExpr),\n dot: new TokenType(\".\"),\n question: new TokenType(\"?\", beforeExpr),\n questionDot: new TokenType(\"?.\"),\n arrow: new TokenType(\"=>\", beforeExpr),\n template: new TokenType(\"template\"),\n invalidTemplate: new TokenType(\"invalidTemplate\"),\n ellipsis: new TokenType(\"...\", beforeExpr),\n backQuote: new TokenType(\"`\", startsExpr),\n dollarBraceL: new TokenType(\"${\", {beforeExpr: true, startsExpr: true}),\n\n // Operators. These carry several kinds of properties to help the\n // parser use them properly (the presence of these properties is\n // what categorizes them as operators).\n //\n // `binop`, when present, specifies that this operator is a binary\n // operator, and will refer to its precedence.\n //\n // `prefix` and `postfix` mark the operator as a prefix or postfix\n // unary operator.\n //\n // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as\n // binary operators with a very low precedence, that should result\n // in AssignmentExpression nodes.\n\n eq: new TokenType(\"=\", {beforeExpr: true, isAssign: true}),\n assign: new TokenType(\"_=\", {beforeExpr: true, isAssign: true}),\n incDec: new TokenType(\"++/--\", {prefix: true, postfix: true, startsExpr: true}),\n prefix: new TokenType(\"!/~\", {beforeExpr: true, prefix: true, startsExpr: true}),\n logicalOR: binop(\"||\", 1),\n logicalAND: binop(\"&&\", 2),\n bitwiseOR: binop(\"|\", 3),\n bitwiseXOR: binop(\"^\", 4),\n bitwiseAND: binop(\"&\", 5),\n equality: binop(\"==/!=/===/!==\", 6),\n relational: binop(\"/<=/>=\", 7),\n bitShift: binop(\"<>/>>>\", 8),\n plusMin: new TokenType(\"+/-\", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),\n modulo: binop(\"%\", 10),\n star: binop(\"*\", 10),\n slash: binop(\"/\", 10),\n starstar: new TokenType(\"**\", {beforeExpr: true}),\n coalesce: binop(\"??\", 1),\n\n // Keyword token types.\n _break: kw(\"break\"),\n _case: kw(\"case\", beforeExpr),\n _catch: kw(\"catch\"),\n _continue: kw(\"continue\"),\n _debugger: kw(\"debugger\"),\n _default: kw(\"default\", beforeExpr),\n _do: kw(\"do\", {isLoop: true, beforeExpr: true}),\n _else: kw(\"else\", beforeExpr),\n _finally: kw(\"finally\"),\n _for: kw(\"for\", {isLoop: true}),\n _function: kw(\"function\", startsExpr),\n _if: kw(\"if\"),\n _return: kw(\"return\", beforeExpr),\n _switch: kw(\"switch\"),\n _throw: kw(\"throw\", beforeExpr),\n _try: kw(\"try\"),\n _var: kw(\"var\"),\n _const: kw(\"const\"),\n _while: kw(\"while\", {isLoop: true}),\n _with: kw(\"with\"),\n _new: kw(\"new\", {beforeExpr: true, startsExpr: true}),\n _this: kw(\"this\", startsExpr),\n _super: kw(\"super\", startsExpr),\n _class: kw(\"class\", startsExpr),\n _extends: kw(\"extends\", beforeExpr),\n _export: kw(\"export\"),\n _import: kw(\"import\", startsExpr),\n _null: kw(\"null\", startsExpr),\n _true: kw(\"true\", startsExpr),\n _false: kw(\"false\", startsExpr),\n _in: kw(\"in\", {beforeExpr: true, binop: 7}),\n _instanceof: kw(\"instanceof\", {beforeExpr: true, binop: 7}),\n _typeof: kw(\"typeof\", {beforeExpr: true, prefix: true, startsExpr: true}),\n _void: kw(\"void\", {beforeExpr: true, prefix: true, startsExpr: true}),\n _delete: kw(\"delete\", {beforeExpr: true, prefix: true, startsExpr: true})\n};\n\n// Matches a whole line break (where CRLF is considered a single\n// line break). Used to count lines.\n\nvar lineBreak = /\\r\\n?|\\n|\\u2028|\\u2029/;\nvar lineBreakG = new RegExp(lineBreak.source, \"g\");\n\nfunction isNewLine(code, ecma2019String) {\n return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))\n}\n\nvar nonASCIIwhitespace = /[\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff]/;\n\nvar skipWhiteSpace = /(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g;\n\nvar ref = Object.prototype;\nvar hasOwnProperty = ref.hasOwnProperty;\nvar toString = ref.toString;\n\n// Checks if an object has a property.\n\nfunction has(obj, propName) {\n return hasOwnProperty.call(obj, propName)\n}\n\nvar isArray = Array.isArray || (function (obj) { return (\n toString.call(obj) === \"[object Array]\"\n); });\n\nfunction wordsRegexp(words) {\n return new RegExp(\"^(?:\" + words.replace(/ /g, \"|\") + \")$\")\n}\n\n// These are used when `options.locations` is on, for the\n// `startLoc` and `endLoc` properties.\n\nvar Position = function Position(line, col) {\n this.line = line;\n this.column = col;\n};\n\nPosition.prototype.offset = function offset (n) {\n return new Position(this.line, this.column + n)\n};\n\nvar SourceLocation = function SourceLocation(p, start, end) {\n this.start = start;\n this.end = end;\n if (p.sourceFile !== null) { this.source = p.sourceFile; }\n};\n\n// The `getLineInfo` function is mostly useful when the\n// `locations` option is off (for performance reasons) and you\n// want to find the line/column position for a given character\n// offset. `input` should be the code string that the offset refers\n// into.\n\nfunction getLineInfo(input, offset) {\n for (var line = 1, cur = 0;;) {\n lineBreakG.lastIndex = cur;\n var match = lineBreakG.exec(input);\n if (match && match.index < offset) {\n ++line;\n cur = match.index + match[0].length;\n } else {\n return new Position(line, offset - cur)\n }\n }\n}\n\n// A second argument must be given to configure the parser process.\n// These options are recognized (only `ecmaVersion` is required):\n\nvar defaultOptions = {\n // `ecmaVersion` indicates the ECMAScript version to parse. Must be\n // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10\n // (2019), 11 (2020), 12 (2021), 13 (2022), or `\"latest\"` (the\n // latest version the library supports). This influences support\n // for strict mode, the set of reserved words, and support for\n // new syntax features.\n ecmaVersion: null,\n // `sourceType` indicates the mode the code should be parsed in.\n // Can be either `\"script\"` or `\"module\"`. This influences global\n // strict mode and parsing of `import` and `export` declarations.\n sourceType: \"script\",\n // `onInsertedSemicolon` can be a callback that will be called\n // when a semicolon is automatically inserted. It will be passed\n // the position of the comma as an offset, and if `locations` is\n // enabled, it is given the location as a `{line, column}` object\n // as second argument.\n onInsertedSemicolon: null,\n // `onTrailingComma` is similar to `onInsertedSemicolon`, but for\n // trailing commas.\n onTrailingComma: null,\n // By default, reserved words are only enforced if ecmaVersion >= 5.\n // Set `allowReserved` to a boolean value to explicitly turn this on\n // an off. When this option has the value \"never\", reserved words\n // and keywords can also not be used as property names.\n allowReserved: null,\n // When enabled, a return at the top level is not considered an\n // error.\n allowReturnOutsideFunction: false,\n // When enabled, import/export statements are not constrained to\n // appearing at the top of the program, and an import.meta expression\n // in a script isn't considered an error.\n allowImportExportEverywhere: false,\n // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.\n // When enabled, await identifiers are allowed to appear at the top-level scope,\n // but they are still not allowed in non-async functions.\n allowAwaitOutsideFunction: null,\n // When enabled, super identifiers are not constrained to\n // appearing in methods and do not raise an error when they appear elsewhere.\n allowSuperOutsideMethod: null,\n // When enabled, hashbang directive in the beginning of file\n // is allowed and treated as a line comment.\n allowHashBang: false,\n // When `locations` is on, `loc` properties holding objects with\n // `start` and `end` properties in `{line, column}` form (with\n // line being 1-based and column 0-based) will be attached to the\n // nodes.\n locations: false,\n // A function can be passed as `onToken` option, which will\n // cause Acorn to call that function with object in the same\n // format as tokens returned from `tokenizer().getToken()`. Note\n // that you are not allowed to call the parser from the\n // callback—that will corrupt its internal state.\n onToken: null,\n // A function can be passed as `onComment` option, which will\n // cause Acorn to call that function with `(block, text, start,\n // end)` parameters whenever a comment is skipped. `block` is a\n // boolean indicating whether this is a block (`/* */`) comment,\n // `text` is the content of the comment, and `start` and `end` are\n // character offsets that denote the start and end of the comment.\n // When the `locations` option is on, two more parameters are\n // passed, the full `{line, column}` locations of the start and\n // end of the comments. Note that you are not allowed to call the\n // parser from the callback—that will corrupt its internal state.\n onComment: null,\n // Nodes have their start and end characters offsets recorded in\n // `start` and `end` properties (directly on the node, rather than\n // the `loc` object, which holds line/column data. To also add a\n // [semi-standardized][range] `range` property holding a `[start,\n // end]` array with the same numbers, set the `ranges` option to\n // `true`.\n //\n // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678\n ranges: false,\n // It is possible to parse multiple files into a single AST by\n // passing the tree produced by parsing the first file as\n // `program` option in subsequent parses. This will add the\n // toplevel forms of the parsed file to the `Program` (top) node\n // of an existing parse tree.\n program: null,\n // When `locations` is on, you can pass this to record the source\n // file in every node's `loc` object.\n sourceFile: null,\n // This value, if given, is stored in every node, whether\n // `locations` is on or off.\n directSourceFile: null,\n // When enabled, parenthesized expressions are represented by\n // (non-standard) ParenthesizedExpression nodes\n preserveParens: false\n};\n\n// Interpret and default an options object\n\nvar warnedAboutEcmaVersion = false;\n\nfunction getOptions(opts) {\n var options = {};\n\n for (var opt in defaultOptions)\n { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }\n\n if (options.ecmaVersion === \"latest\") {\n options.ecmaVersion = 1e8;\n } else if (options.ecmaVersion == null) {\n if (!warnedAboutEcmaVersion && typeof console === \"object\" && console.warn) {\n warnedAboutEcmaVersion = true;\n console.warn(\"Since Acorn 8.0.0, options.ecmaVersion is required.\\nDefaulting to 2020, but this will stop working in the future.\");\n }\n options.ecmaVersion = 11;\n } else if (options.ecmaVersion >= 2015) {\n options.ecmaVersion -= 2009;\n }\n\n if (options.allowReserved == null)\n { options.allowReserved = options.ecmaVersion < 5; }\n\n if (isArray(options.onToken)) {\n var tokens = options.onToken;\n options.onToken = function (token) { return tokens.push(token); };\n }\n if (isArray(options.onComment))\n { options.onComment = pushComment(options, options.onComment); }\n\n return options\n}\n\nfunction pushComment(options, array) {\n return function(block, text, start, end, startLoc, endLoc) {\n var comment = {\n type: block ? \"Block\" : \"Line\",\n value: text,\n start: start,\n end: end\n };\n if (options.locations)\n { comment.loc = new SourceLocation(this, startLoc, endLoc); }\n if (options.ranges)\n { comment.range = [start, end]; }\n array.push(comment);\n }\n}\n\n// Each scope gets a bitset that may contain these flags\nvar\n SCOPE_TOP = 1,\n SCOPE_FUNCTION = 2,\n SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,\n SCOPE_ASYNC = 4,\n SCOPE_GENERATOR = 8,\n SCOPE_ARROW = 16,\n SCOPE_SIMPLE_CATCH = 32,\n SCOPE_SUPER = 64,\n SCOPE_DIRECT_SUPER = 128;\n\nfunction functionFlags(async, generator) {\n return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)\n}\n\n// Used in checkLVal* and declareName to determine the type of a binding\nvar\n BIND_NONE = 0, // Not a binding\n BIND_VAR = 1, // Var-style binding\n BIND_LEXICAL = 2, // Let- or const-style binding\n BIND_FUNCTION = 3, // Function declaration\n BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding\n BIND_OUTSIDE = 5; // Special case for function names as bound inside the function\n\nvar Parser = function Parser(options, input, startPos) {\n this.options = options = getOptions(options);\n this.sourceFile = options.sourceFile;\n this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === \"module\" ? \"5module\" : 5]);\n var reserved = \"\";\n if (options.allowReserved !== true) {\n reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];\n if (options.sourceType === \"module\") { reserved += \" await\"; }\n }\n this.reservedWords = wordsRegexp(reserved);\n var reservedStrict = (reserved ? reserved + \" \" : \"\") + reservedWords.strict;\n this.reservedWordsStrict = wordsRegexp(reservedStrict);\n this.reservedWordsStrictBind = wordsRegexp(reservedStrict + \" \" + reservedWords.strictBind);\n this.input = String(input);\n\n // Used to signal to callers of `readWord1` whether the word\n // contained any escape sequences. This is needed because words with\n // escape sequences must not be interpreted as keywords.\n this.containsEsc = false;\n\n // Set up token state\n\n // The current position of the tokenizer in the input.\n if (startPos) {\n this.pos = startPos;\n this.lineStart = this.input.lastIndexOf(\"\\n\", startPos - 1) + 1;\n this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;\n } else {\n this.pos = this.lineStart = 0;\n this.curLine = 1;\n }\n\n // Properties of the current token:\n // Its type\n this.type = types.eof;\n // For tokens that include more information than their type, the value\n this.value = null;\n // Its start and end offset\n this.start = this.end = this.pos;\n // And, if locations are used, the {line, column} object\n // corresponding to those offsets\n this.startLoc = this.endLoc = this.curPosition();\n\n // Position information for the previous token\n this.lastTokEndLoc = this.lastTokStartLoc = null;\n this.lastTokStart = this.lastTokEnd = this.pos;\n\n // The context stack is used to superficially track syntactic\n // context to predict whether a regular expression is allowed in a\n // given position.\n this.context = this.initialContext();\n this.exprAllowed = true;\n\n // Figure out if it's a module code.\n this.inModule = options.sourceType === \"module\";\n this.strict = this.inModule || this.strictDirective(this.pos);\n\n // Used to signify the start of a potential arrow function\n this.potentialArrowAt = -1;\n this.potentialArrowInForAwait = false;\n\n // Positions to delayed-check that yield/await does not exist in default parameters.\n this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;\n // Labels in scope.\n this.labels = [];\n // Thus-far undefined exports.\n this.undefinedExports = Object.create(null);\n\n // If enabled, skip leading hashbang line.\n if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === \"#!\")\n { this.skipLineComment(2); }\n\n // Scope tracking for duplicate variable names (see scope.js)\n this.scopeStack = [];\n this.enterScope(SCOPE_TOP);\n\n // For RegExp validation\n this.regexpState = null;\n\n // The stack of private names.\n // Each element has two properties: 'declared' and 'used'.\n // When it exited from the outermost class definition, all used private names must be declared.\n this.privateNameStack = [];\n};\n\nvar prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };\n\nParser.prototype.parse = function parse () {\n var node = this.options.program || this.startNode();\n this.nextToken();\n return this.parseTopLevel(node)\n};\n\nprototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };\nprototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };\nprototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };\nprototypeAccessors.canAwait.get = function () {\n for (var i = this.scopeStack.length - 1; i >= 0; i--) {\n var scope = this.scopeStack[i];\n if (scope.inClassFieldInit) { return false }\n if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }\n }\n return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction\n};\nprototypeAccessors.allowSuper.get = function () {\n var ref = this.currentThisScope();\n var flags = ref.flags;\n var inClassFieldInit = ref.inClassFieldInit;\n return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod\n};\nprototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };\nprototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };\nprototypeAccessors.inNonArrowFunction.get = function () {\n var ref = this.currentThisScope();\n var flags = ref.flags;\n var inClassFieldInit = ref.inClassFieldInit;\n return (flags & SCOPE_FUNCTION) > 0 || inClassFieldInit\n};\n\nParser.extend = function extend () {\n var plugins = [], len = arguments.length;\n while ( len-- ) plugins[ len ] = arguments[ len ];\n\n var cls = this;\n for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }\n return cls\n};\n\nParser.parse = function parse (input, options) {\n return new this(options, input).parse()\n};\n\nParser.parseExpressionAt = function parseExpressionAt (input, pos, options) {\n var parser = new this(options, input, pos);\n parser.nextToken();\n return parser.parseExpression()\n};\n\nParser.tokenizer = function tokenizer (input, options) {\n return new this(options, input)\n};\n\nObject.defineProperties( Parser.prototype, prototypeAccessors );\n\nvar pp = Parser.prototype;\n\n// ## Parser utilities\n\nvar literal = /^(?:'((?:\\\\.|[^'\\\\])*?)'|\"((?:\\\\.|[^\"\\\\])*?)\")/;\npp.strictDirective = function(start) {\n for (;;) {\n // Try to find string literal.\n skipWhiteSpace.lastIndex = start;\n start += skipWhiteSpace.exec(this.input)[0].length;\n var match = literal.exec(this.input.slice(start));\n if (!match) { return false }\n if ((match[1] || match[2]) === \"use strict\") {\n skipWhiteSpace.lastIndex = start + match[0].length;\n var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;\n var next = this.input.charAt(end);\n return next === \";\" || next === \"}\" ||\n (lineBreak.test(spaceAfter[0]) &&\n !(/[(`.[+\\-/*%<>=,?^&]/.test(next) || next === \"!\" && this.input.charAt(end + 1) === \"=\"))\n }\n start += match[0].length;\n\n // Skip semicolon, if any.\n skipWhiteSpace.lastIndex = start;\n start += skipWhiteSpace.exec(this.input)[0].length;\n if (this.input[start] === \";\")\n { start++; }\n }\n};\n\n// Predicate that tests whether the next token is of the given\n// type, and if yes, consumes it as a side effect.\n\npp.eat = function(type) {\n if (this.type === type) {\n this.next();\n return true\n } else {\n return false\n }\n};\n\n// Tests whether parsed token is a contextual keyword.\n\npp.isContextual = function(name) {\n return this.type === types.name && this.value === name && !this.containsEsc\n};\n\n// Consumes contextual keyword if possible.\n\npp.eatContextual = function(name) {\n if (!this.isContextual(name)) { return false }\n this.next();\n return true\n};\n\n// Asserts that following token is given contextual keyword.\n\npp.expectContextual = function(name) {\n if (!this.eatContextual(name)) { this.unexpected(); }\n};\n\n// Test whether a semicolon can be inserted at the current position.\n\npp.canInsertSemicolon = function() {\n return this.type === types.eof ||\n this.type === types.braceR ||\n lineBreak.test(this.input.slice(this.lastTokEnd, this.start))\n};\n\npp.insertSemicolon = function() {\n if (this.canInsertSemicolon()) {\n if (this.options.onInsertedSemicolon)\n { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }\n return true\n }\n};\n\n// Consume a semicolon, or, failing that, see if we are allowed to\n// pretend that there is a semicolon at this position.\n\npp.semicolon = function() {\n if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }\n};\n\npp.afterTrailingComma = function(tokType, notNext) {\n if (this.type === tokType) {\n if (this.options.onTrailingComma)\n { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }\n if (!notNext)\n { this.next(); }\n return true\n }\n};\n\n// Expect a token of a given type. If found, consume it, otherwise,\n// raise an unexpected token error.\n\npp.expect = function(type) {\n this.eat(type) || this.unexpected();\n};\n\n// Raise an unexpected token error.\n\npp.unexpected = function(pos) {\n this.raise(pos != null ? pos : this.start, \"Unexpected token\");\n};\n\nfunction DestructuringErrors() {\n this.shorthandAssign =\n this.trailingComma =\n this.parenthesizedAssign =\n this.parenthesizedBind =\n this.doubleProto =\n -1;\n}\n\npp.checkPatternErrors = function(refDestructuringErrors, isAssign) {\n if (!refDestructuringErrors) { return }\n if (refDestructuringErrors.trailingComma > -1)\n { this.raiseRecoverable(refDestructuringErrors.trailingComma, \"Comma is not permitted after the rest element\"); }\n var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;\n if (parens > -1) { this.raiseRecoverable(parens, \"Parenthesized pattern\"); }\n};\n\npp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {\n if (!refDestructuringErrors) { return false }\n var shorthandAssign = refDestructuringErrors.shorthandAssign;\n var doubleProto = refDestructuringErrors.doubleProto;\n if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }\n if (shorthandAssign >= 0)\n { this.raise(shorthandAssign, \"Shorthand property assignments are valid only in destructuring patterns\"); }\n if (doubleProto >= 0)\n { this.raiseRecoverable(doubleProto, \"Redefinition of __proto__ property\"); }\n};\n\npp.checkYieldAwaitInDefaultParams = function() {\n if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))\n { this.raise(this.yieldPos, \"Yield expression cannot be a default value\"); }\n if (this.awaitPos)\n { this.raise(this.awaitPos, \"Await expression cannot be a default value\"); }\n};\n\npp.isSimpleAssignTarget = function(expr) {\n if (expr.type === \"ParenthesizedExpression\")\n { return this.isSimpleAssignTarget(expr.expression) }\n return expr.type === \"Identifier\" || expr.type === \"MemberExpression\"\n};\n\nvar pp$1 = Parser.prototype;\n\n// ### Statement parsing\n\n// Parse a program. Initializes the parser, reads any number of\n// statements, and wraps them in a Program node. Optionally takes a\n// `program` argument. If present, the statements will be appended\n// to its body instead of creating a new node.\n\npp$1.parseTopLevel = function(node) {\n var exports = Object.create(null);\n if (!node.body) { node.body = []; }\n while (this.type !== types.eof) {\n var stmt = this.parseStatement(null, true, exports);\n node.body.push(stmt);\n }\n if (this.inModule)\n { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)\n {\n var name = list[i];\n\n this.raiseRecoverable(this.undefinedExports[name].start, (\"Export '\" + name + \"' is not defined\"));\n } }\n this.adaptDirectivePrologue(node.body);\n this.next();\n node.sourceType = this.options.sourceType;\n return this.finishNode(node, \"Program\")\n};\n\nvar loopLabel = {kind: \"loop\"}, switchLabel = {kind: \"switch\"};\n\npp$1.isLet = function(context) {\n if (this.options.ecmaVersion < 6 || !this.isContextual(\"let\")) { return false }\n skipWhiteSpace.lastIndex = this.pos;\n var skip = skipWhiteSpace.exec(this.input);\n var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);\n // For ambiguous cases, determine if a LexicalDeclaration (or only a\n // Statement) is allowed here. If context is not empty then only a Statement\n // is allowed. However, `let [` is an explicit negative lookahead for\n // ExpressionStatement, so special-case it first.\n if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral\n if (context) { return false }\n\n if (nextCh === 123) { return true } // '{'\n if (isIdentifierStart(nextCh, true)) {\n var pos = next + 1;\n while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }\n if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }\n var ident = this.input.slice(next, pos);\n if (!keywordRelationalOperator.test(ident)) { return true }\n }\n return false\n};\n\n// check 'async [no LineTerminator here] function'\n// - 'async /*foo*/ function' is OK.\n// - 'async /*\\n*/ function' is invalid.\npp$1.isAsyncFunction = function() {\n if (this.options.ecmaVersion < 8 || !this.isContextual(\"async\"))\n { return false }\n\n skipWhiteSpace.lastIndex = this.pos;\n var skip = skipWhiteSpace.exec(this.input);\n var next = this.pos + skip[0].length, after;\n return !lineBreak.test(this.input.slice(this.pos, next)) &&\n this.input.slice(next, next + 8) === \"function\" &&\n (next + 8 === this.input.length ||\n !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))\n};\n\n// Parse a single statement.\n//\n// If expecting a statement and finding a slash operator, parse a\n// regular expression literal. This is to handle cases like\n// `if (foo) /blah/.exec(foo)`, where looking at the previous token\n// does not help.\n\npp$1.parseStatement = function(context, topLevel, exports) {\n var starttype = this.type, node = this.startNode(), kind;\n\n if (this.isLet(context)) {\n starttype = types._var;\n kind = \"let\";\n }\n\n // Most types of statements are recognized by the keyword they\n // start with. Many are trivial to parse, some require a bit of\n // complexity.\n\n switch (starttype) {\n case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)\n case types._debugger: return this.parseDebuggerStatement(node)\n case types._do: return this.parseDoStatement(node)\n case types._for: return this.parseForStatement(node)\n case types._function:\n // Function as sole body of either an if statement or a labeled statement\n // works, but not when it is part of a labeled statement that is the sole\n // body of an if statement.\n if ((context && (this.strict || context !== \"if\" && context !== \"label\")) && this.options.ecmaVersion >= 6) { this.unexpected(); }\n return this.parseFunctionStatement(node, false, !context)\n case types._class:\n if (context) { this.unexpected(); }\n return this.parseClass(node, true)\n case types._if: return this.parseIfStatement(node)\n case types._return: return this.parseReturnStatement(node)\n case types._switch: return this.parseSwitchStatement(node)\n case types._throw: return this.parseThrowStatement(node)\n case types._try: return this.parseTryStatement(node)\n case types._const: case types._var:\n kind = kind || this.value;\n if (context && kind !== \"var\") { this.unexpected(); }\n return this.parseVarStatement(node, kind)\n case types._while: return this.parseWhileStatement(node)\n case types._with: return this.parseWithStatement(node)\n case types.braceL: return this.parseBlock(true, node)\n case types.semi: return this.parseEmptyStatement(node)\n case types._export:\n case types._import:\n if (this.options.ecmaVersion > 10 && starttype === types._import) {\n skipWhiteSpace.lastIndex = this.pos;\n var skip = skipWhiteSpace.exec(this.input);\n var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);\n if (nextCh === 40 || nextCh === 46) // '(' or '.'\n { return this.parseExpressionStatement(node, this.parseExpression()) }\n }\n\n if (!this.options.allowImportExportEverywhere) {\n if (!topLevel)\n { this.raise(this.start, \"'import' and 'export' may only appear at the top level\"); }\n if (!this.inModule)\n { this.raise(this.start, \"'import' and 'export' may appear only with 'sourceType: module'\"); }\n }\n return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)\n\n // If the statement does not start with a statement keyword or a\n // brace, it's an ExpressionStatement or LabeledStatement. We\n // simply start parsing an expression, and afterwards, if the\n // next token is a colon and the expression was a simple\n // Identifier node, we switch to interpreting it as a label.\n default:\n if (this.isAsyncFunction()) {\n if (context) { this.unexpected(); }\n this.next();\n return this.parseFunctionStatement(node, true, !context)\n }\n\n var maybeName = this.value, expr = this.parseExpression();\n if (starttype === types.name && expr.type === \"Identifier\" && this.eat(types.colon))\n { return this.parseLabeledStatement(node, maybeName, expr, context) }\n else { return this.parseExpressionStatement(node, expr) }\n }\n};\n\npp$1.parseBreakContinueStatement = function(node, keyword) {\n var isBreak = keyword === \"break\";\n this.next();\n if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }\n else if (this.type !== types.name) { this.unexpected(); }\n else {\n node.label = this.parseIdent();\n this.semicolon();\n }\n\n // Verify that there is an actual destination to break or\n // continue to.\n var i = 0;\n for (; i < this.labels.length; ++i) {\n var lab = this.labels[i];\n if (node.label == null || lab.name === node.label.name) {\n if (lab.kind != null && (isBreak || lab.kind === \"loop\")) { break }\n if (node.label && isBreak) { break }\n }\n }\n if (i === this.labels.length) { this.raise(node.start, \"Unsyntactic \" + keyword); }\n return this.finishNode(node, isBreak ? \"BreakStatement\" : \"ContinueStatement\")\n};\n\npp$1.parseDebuggerStatement = function(node) {\n this.next();\n this.semicolon();\n return this.finishNode(node, \"DebuggerStatement\")\n};\n\npp$1.parseDoStatement = function(node) {\n this.next();\n this.labels.push(loopLabel);\n node.body = this.parseStatement(\"do\");\n this.labels.pop();\n this.expect(types._while);\n node.test = this.parseParenExpression();\n if (this.options.ecmaVersion >= 6)\n { this.eat(types.semi); }\n else\n { this.semicolon(); }\n return this.finishNode(node, \"DoWhileStatement\")\n};\n\n// Disambiguating between a `for` and a `for`/`in` or `for`/`of`\n// loop is non-trivial. Basically, we have to parse the init `var`\n// statement or expression, disallowing the `in` operator (see\n// the second parameter to `parseExpression`), and then check\n// whether the next token is `in` or `of`. When there is no init\n// part (semicolon immediately after the opening parenthesis), it\n// is a regular `for` loop.\n\npp$1.parseForStatement = function(node) {\n this.next();\n var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual(\"await\")) ? this.lastTokStart : -1;\n this.labels.push(loopLabel);\n this.enterScope(0);\n this.expect(types.parenL);\n if (this.type === types.semi) {\n if (awaitAt > -1) { this.unexpected(awaitAt); }\n return this.parseFor(node, null)\n }\n var isLet = this.isLet();\n if (this.type === types._var || this.type === types._const || isLet) {\n var init$1 = this.startNode(), kind = isLet ? \"let\" : this.value;\n this.next();\n this.parseVar(init$1, true, kind);\n this.finishNode(init$1, \"VariableDeclaration\");\n if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual(\"of\"))) && init$1.declarations.length === 1) {\n if (this.options.ecmaVersion >= 9) {\n if (this.type === types._in) {\n if (awaitAt > -1) { this.unexpected(awaitAt); }\n } else { node.await = awaitAt > -1; }\n }\n return this.parseForIn(node, init$1)\n }\n if (awaitAt > -1) { this.unexpected(awaitAt); }\n return this.parseFor(node, init$1)\n }\n var refDestructuringErrors = new DestructuringErrors;\n var init = this.parseExpression(awaitAt > -1 ? \"await\" : true, refDestructuringErrors);\n if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual(\"of\"))) {\n if (this.options.ecmaVersion >= 9) {\n if (this.type === types._in) {\n if (awaitAt > -1) { this.unexpected(awaitAt); }\n } else { node.await = awaitAt > -1; }\n }\n this.toAssignable(init, false, refDestructuringErrors);\n this.checkLValPattern(init);\n return this.parseForIn(node, init)\n } else {\n this.checkExpressionErrors(refDestructuringErrors, true);\n }\n if (awaitAt > -1) { this.unexpected(awaitAt); }\n return this.parseFor(node, init)\n};\n\npp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {\n this.next();\n return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)\n};\n\npp$1.parseIfStatement = function(node) {\n this.next();\n node.test = this.parseParenExpression();\n // allow function declarations in branches, but only in non-strict mode\n node.consequent = this.parseStatement(\"if\");\n node.alternate = this.eat(types._else) ? this.parseStatement(\"if\") : null;\n return this.finishNode(node, \"IfStatement\")\n};\n\npp$1.parseReturnStatement = function(node) {\n if (!this.inFunction && !this.options.allowReturnOutsideFunction)\n { this.raise(this.start, \"'return' outside of function\"); }\n this.next();\n\n // In `return` (and `break`/`continue`), the keywords with\n // optional arguments, we eagerly look for a semicolon or the\n // possibility to insert one.\n\n if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }\n else { node.argument = this.parseExpression(); this.semicolon(); }\n return this.finishNode(node, \"ReturnStatement\")\n};\n\npp$1.parseSwitchStatement = function(node) {\n this.next();\n node.discriminant = this.parseParenExpression();\n node.cases = [];\n this.expect(types.braceL);\n this.labels.push(switchLabel);\n this.enterScope(0);\n\n // Statements under must be grouped (by label) in SwitchCase\n // nodes. `cur` is used to keep the node that we are currently\n // adding statements to.\n\n var cur;\n for (var sawDefault = false; this.type !== types.braceR;) {\n if (this.type === types._case || this.type === types._default) {\n var isCase = this.type === types._case;\n if (cur) { this.finishNode(cur, \"SwitchCase\"); }\n node.cases.push(cur = this.startNode());\n cur.consequent = [];\n this.next();\n if (isCase) {\n cur.test = this.parseExpression();\n } else {\n if (sawDefault) { this.raiseRecoverable(this.lastTokStart, \"Multiple default clauses\"); }\n sawDefault = true;\n cur.test = null;\n }\n this.expect(types.colon);\n } else {\n if (!cur) { this.unexpected(); }\n cur.consequent.push(this.parseStatement(null));\n }\n }\n this.exitScope();\n if (cur) { this.finishNode(cur, \"SwitchCase\"); }\n this.next(); // Closing brace\n this.labels.pop();\n return this.finishNode(node, \"SwitchStatement\")\n};\n\npp$1.parseThrowStatement = function(node) {\n this.next();\n if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))\n { this.raise(this.lastTokEnd, \"Illegal newline after throw\"); }\n node.argument = this.parseExpression();\n this.semicolon();\n return this.finishNode(node, \"ThrowStatement\")\n};\n\n// Reused empty array added for node fields that are always empty.\n\nvar empty = [];\n\npp$1.parseTryStatement = function(node) {\n this.next();\n node.block = this.parseBlock();\n node.handler = null;\n if (this.type === types._catch) {\n var clause = this.startNode();\n this.next();\n if (this.eat(types.parenL)) {\n clause.param = this.parseBindingAtom();\n var simple = clause.param.type === \"Identifier\";\n this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);\n this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);\n this.expect(types.parenR);\n } else {\n if (this.options.ecmaVersion < 10) { this.unexpected(); }\n clause.param = null;\n this.enterScope(0);\n }\n clause.body = this.parseBlock(false);\n this.exitScope();\n node.handler = this.finishNode(clause, \"CatchClause\");\n }\n node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;\n if (!node.handler && !node.finalizer)\n { this.raise(node.start, \"Missing catch or finally clause\"); }\n return this.finishNode(node, \"TryStatement\")\n};\n\npp$1.parseVarStatement = function(node, kind) {\n this.next();\n this.parseVar(node, false, kind);\n this.semicolon();\n return this.finishNode(node, \"VariableDeclaration\")\n};\n\npp$1.parseWhileStatement = function(node) {\n this.next();\n node.test = this.parseParenExpression();\n this.labels.push(loopLabel);\n node.body = this.parseStatement(\"while\");\n this.labels.pop();\n return this.finishNode(node, \"WhileStatement\")\n};\n\npp$1.parseWithStatement = function(node) {\n if (this.strict) { this.raise(this.start, \"'with' in strict mode\"); }\n this.next();\n node.object = this.parseParenExpression();\n node.body = this.parseStatement(\"with\");\n return this.finishNode(node, \"WithStatement\")\n};\n\npp$1.parseEmptyStatement = function(node) {\n this.next();\n return this.finishNode(node, \"EmptyStatement\")\n};\n\npp$1.parseLabeledStatement = function(node, maybeName, expr, context) {\n for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)\n {\n var label = list[i$1];\n\n if (label.name === maybeName)\n { this.raise(expr.start, \"Label '\" + maybeName + \"' is already declared\");\n } }\n var kind = this.type.isLoop ? \"loop\" : this.type === types._switch ? \"switch\" : null;\n for (var i = this.labels.length - 1; i >= 0; i--) {\n var label$1 = this.labels[i];\n if (label$1.statementStart === node.start) {\n // Update information about previous labels on this node\n label$1.statementStart = this.start;\n label$1.kind = kind;\n } else { break }\n }\n this.labels.push({name: maybeName, kind: kind, statementStart: this.start});\n node.body = this.parseStatement(context ? context.indexOf(\"label\") === -1 ? context + \"label\" : context : \"label\");\n this.labels.pop();\n node.label = expr;\n return this.finishNode(node, \"LabeledStatement\")\n};\n\npp$1.parseExpressionStatement = function(node, expr) {\n node.expression = expr;\n this.semicolon();\n return this.finishNode(node, \"ExpressionStatement\")\n};\n\n// Parse a semicolon-enclosed block of statements, handling `\"use\n// strict\"` declarations when `allowStrict` is true (used for\n// function bodies).\n\npp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {\n if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;\n if ( node === void 0 ) node = this.startNode();\n\n node.body = [];\n this.expect(types.braceL);\n if (createNewLexicalScope) { this.enterScope(0); }\n while (this.type !== types.braceR) {\n var stmt = this.parseStatement(null);\n node.body.push(stmt);\n }\n if (exitStrict) { this.strict = false; }\n this.next();\n if (createNewLexicalScope) { this.exitScope(); }\n return this.finishNode(node, \"BlockStatement\")\n};\n\n// Parse a regular `for` loop. The disambiguation code in\n// `parseStatement` will already have parsed the init statement or\n// expression.\n\npp$1.parseFor = function(node, init) {\n node.init = init;\n this.expect(types.semi);\n node.test = this.type === types.semi ? null : this.parseExpression();\n this.expect(types.semi);\n node.update = this.type === types.parenR ? null : this.parseExpression();\n this.expect(types.parenR);\n node.body = this.parseStatement(\"for\");\n this.exitScope();\n this.labels.pop();\n return this.finishNode(node, \"ForStatement\")\n};\n\n// Parse a `for`/`in` and `for`/`of` loop, which are almost\n// same from parser's perspective.\n\npp$1.parseForIn = function(node, init) {\n var isForIn = this.type === types._in;\n this.next();\n\n if (\n init.type === \"VariableDeclaration\" &&\n init.declarations[0].init != null &&\n (\n !isForIn ||\n this.options.ecmaVersion < 8 ||\n this.strict ||\n init.kind !== \"var\" ||\n init.declarations[0].id.type !== \"Identifier\"\n )\n ) {\n this.raise(\n init.start,\n ((isForIn ? \"for-in\" : \"for-of\") + \" loop variable declaration may not have an initializer\")\n );\n }\n node.left = init;\n node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();\n this.expect(types.parenR);\n node.body = this.parseStatement(\"for\");\n this.exitScope();\n this.labels.pop();\n return this.finishNode(node, isForIn ? \"ForInStatement\" : \"ForOfStatement\")\n};\n\n// Parse a list of variable declarations.\n\npp$1.parseVar = function(node, isFor, kind) {\n node.declarations = [];\n node.kind = kind;\n for (;;) {\n var decl = this.startNode();\n this.parseVarId(decl, kind);\n if (this.eat(types.eq)) {\n decl.init = this.parseMaybeAssign(isFor);\n } else if (kind === \"const\" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual(\"of\")))) {\n this.unexpected();\n } else if (decl.id.type !== \"Identifier\" && !(isFor && (this.type === types._in || this.isContextual(\"of\")))) {\n this.raise(this.lastTokEnd, \"Complex binding patterns require an initialization value\");\n } else {\n decl.init = null;\n }\n node.declarations.push(this.finishNode(decl, \"VariableDeclarator\"));\n if (!this.eat(types.comma)) { break }\n }\n return node\n};\n\npp$1.parseVarId = function(decl, kind) {\n decl.id = this.parseBindingAtom();\n this.checkLValPattern(decl.id, kind === \"var\" ? BIND_VAR : BIND_LEXICAL, false);\n};\n\nvar FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;\n\n// Parse a function declaration or literal (depending on the\n// `statement & FUNC_STATEMENT`).\n\n// Remove `allowExpressionBody` for 7.0.0, as it is only called with false\npp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {\n this.initFunction(node);\n if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {\n if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))\n { this.unexpected(); }\n node.generator = this.eat(types.star);\n }\n if (this.options.ecmaVersion >= 8)\n { node.async = !!isAsync; }\n\n if (statement & FUNC_STATEMENT) {\n node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();\n if (node.id && !(statement & FUNC_HANGING_STATEMENT))\n // If it is a regular function declaration in sloppy mode, then it is\n // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding\n // mode depends on properties of the current scope (see\n // treatFunctionsAsVar).\n { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }\n }\n\n var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;\n this.yieldPos = 0;\n this.awaitPos = 0;\n this.awaitIdentPos = 0;\n this.enterScope(functionFlags(node.async, node.generator));\n\n if (!(statement & FUNC_STATEMENT))\n { node.id = this.type === types.name ? this.parseIdent() : null; }\n\n this.parseFunctionParams(node);\n this.parseFunctionBody(node, allowExpressionBody, false);\n\n this.yieldPos = oldYieldPos;\n this.awaitPos = oldAwaitPos;\n this.awaitIdentPos = oldAwaitIdentPos;\n return this.finishNode(node, (statement & FUNC_STATEMENT) ? \"FunctionDeclaration\" : \"FunctionExpression\")\n};\n\npp$1.parseFunctionParams = function(node) {\n this.expect(types.parenL);\n node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);\n this.checkYieldAwaitInDefaultParams();\n};\n\n// Parse a class declaration or literal (depending on the\n// `isStatement` parameter).\n\npp$1.parseClass = function(node, isStatement) {\n this.next();\n\n // ecma-262 14.6 Class Definitions\n // A class definition is always strict mode code.\n var oldStrict = this.strict;\n this.strict = true;\n\n this.parseClassId(node, isStatement);\n this.parseClassSuper(node);\n var privateNameMap = this.enterClassBody();\n var classBody = this.startNode();\n var hadConstructor = false;\n classBody.body = [];\n this.expect(types.braceL);\n while (this.type !== types.braceR) {\n var element = this.parseClassElement(node.superClass !== null);\n if (element) {\n classBody.body.push(element);\n if (element.type === \"MethodDefinition\" && element.kind === \"constructor\") {\n if (hadConstructor) { this.raise(element.start, \"Duplicate constructor in the same class\"); }\n hadConstructor = true;\n } else if (element.key.type === \"PrivateIdentifier\" && isPrivateNameConflicted(privateNameMap, element)) {\n this.raiseRecoverable(element.key.start, (\"Identifier '#\" + (element.key.name) + \"' has already been declared\"));\n }\n }\n }\n this.strict = oldStrict;\n this.next();\n node.body = this.finishNode(classBody, \"ClassBody\");\n this.exitClassBody();\n return this.finishNode(node, isStatement ? \"ClassDeclaration\" : \"ClassExpression\")\n};\n\npp$1.parseClassElement = function(constructorAllowsSuper) {\n if (this.eat(types.semi)) { return null }\n\n var ecmaVersion = this.options.ecmaVersion;\n var node = this.startNode();\n var keyName = \"\";\n var isGenerator = false;\n var isAsync = false;\n var kind = \"method\";\n\n // Parse modifiers\n node.static = false;\n if (this.eatContextual(\"static\")) {\n if (this.isClassElementNameStart() || this.type === types.star) {\n node.static = true;\n } else {\n keyName = \"static\";\n }\n }\n if (!keyName && ecmaVersion >= 8 && this.eatContextual(\"async\")) {\n if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) {\n isAsync = true;\n } else {\n keyName = \"async\";\n }\n }\n if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) {\n isGenerator = true;\n }\n if (!keyName && !isAsync && !isGenerator) {\n var lastValue = this.value;\n if (this.eatContextual(\"get\") || this.eatContextual(\"set\")) {\n if (this.isClassElementNameStart()) {\n kind = lastValue;\n } else {\n keyName = lastValue;\n }\n }\n }\n\n // Parse element name\n if (keyName) {\n // 'async', 'get', 'set', or 'static' were not a keyword contextually.\n // The last token is any of those. Make it the element name.\n node.computed = false;\n node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);\n node.key.name = keyName;\n this.finishNode(node.key, \"Identifier\");\n } else {\n this.parseClassElementName(node);\n }\n\n // Parse element value\n if (ecmaVersion < 13 || this.type === types.parenL || kind !== \"method\" || isGenerator || isAsync) {\n var isConstructor = !node.static && checkKeyName(node, \"constructor\");\n var allowsDirectSuper = isConstructor && constructorAllowsSuper;\n // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.\n if (isConstructor && kind !== \"method\") { this.raise(node.key.start, \"Constructor can't have get/set modifier\"); }\n node.kind = isConstructor ? \"constructor\" : kind;\n this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);\n } else {\n this.parseClassField(node);\n }\n\n return node\n};\n\npp$1.isClassElementNameStart = function() {\n return (\n this.type === types.name ||\n this.type === types.privateId ||\n this.type === types.num ||\n this.type === types.string ||\n this.type === types.bracketL ||\n this.type.keyword\n )\n};\n\npp$1.parseClassElementName = function(element) {\n if (this.type === types.privateId) {\n if (this.value === \"constructor\") {\n this.raise(this.start, \"Classes can't have an element named '#constructor'\");\n }\n element.computed = false;\n element.key = this.parsePrivateIdent();\n } else {\n this.parsePropertyName(element);\n }\n};\n\npp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {\n // Check key and flags\n var key = method.key;\n if (method.kind === \"constructor\") {\n if (isGenerator) { this.raise(key.start, \"Constructor can't be a generator\"); }\n if (isAsync) { this.raise(key.start, \"Constructor can't be an async method\"); }\n } else if (method.static && checkKeyName(method, \"prototype\")) {\n this.raise(key.start, \"Classes may not have a static property named prototype\");\n }\n\n // Parse value\n var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);\n\n // Check value\n if (method.kind === \"get\" && value.params.length !== 0)\n { this.raiseRecoverable(value.start, \"getter should have no params\"); }\n if (method.kind === \"set\" && value.params.length !== 1)\n { this.raiseRecoverable(value.start, \"setter should have exactly one param\"); }\n if (method.kind === \"set\" && value.params[0].type === \"RestElement\")\n { this.raiseRecoverable(value.params[0].start, \"Setter cannot use rest params\"); }\n\n return this.finishNode(method, \"MethodDefinition\")\n};\n\npp$1.parseClassField = function(field) {\n if (checkKeyName(field, \"constructor\")) {\n this.raise(field.key.start, \"Classes can't have a field named 'constructor'\");\n } else if (field.static && checkKeyName(field, \"prototype\")) {\n this.raise(field.key.start, \"Classes can't have a static field named 'prototype'\");\n }\n\n if (this.eat(types.eq)) {\n // To raise SyntaxError if 'arguments' exists in the initializer.\n var scope = this.currentThisScope();\n var inClassFieldInit = scope.inClassFieldInit;\n scope.inClassFieldInit = true;\n field.value = this.parseMaybeAssign();\n scope.inClassFieldInit = inClassFieldInit;\n } else {\n field.value = null;\n }\n this.semicolon();\n\n return this.finishNode(field, \"PropertyDefinition\")\n};\n\npp$1.parseClassId = function(node, isStatement) {\n if (this.type === types.name) {\n node.id = this.parseIdent();\n if (isStatement)\n { this.checkLValSimple(node.id, BIND_LEXICAL, false); }\n } else {\n if (isStatement === true)\n { this.unexpected(); }\n node.id = null;\n }\n};\n\npp$1.parseClassSuper = function(node) {\n node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;\n};\n\npp$1.enterClassBody = function() {\n var element = {declared: Object.create(null), used: []};\n this.privateNameStack.push(element);\n return element.declared\n};\n\npp$1.exitClassBody = function() {\n var ref = this.privateNameStack.pop();\n var declared = ref.declared;\n var used = ref.used;\n var len = this.privateNameStack.length;\n var parent = len === 0 ? null : this.privateNameStack[len - 1];\n for (var i = 0; i < used.length; ++i) {\n var id = used[i];\n if (!has(declared, id.name)) {\n if (parent) {\n parent.used.push(id);\n } else {\n this.raiseRecoverable(id.start, (\"Private field '#\" + (id.name) + \"' must be declared in an enclosing class\"));\n }\n }\n }\n};\n\nfunction isPrivateNameConflicted(privateNameMap, element) {\n var name = element.key.name;\n var curr = privateNameMap[name];\n\n var next = \"true\";\n if (element.type === \"MethodDefinition\" && (element.kind === \"get\" || element.kind === \"set\")) {\n next = (element.static ? \"s\" : \"i\") + element.kind;\n }\n\n // `class { get #a(){}; static set #a(_){} }` is also conflict.\n if (\n curr === \"iget\" && next === \"iset\" ||\n curr === \"iset\" && next === \"iget\" ||\n curr === \"sget\" && next === \"sset\" ||\n curr === \"sset\" && next === \"sget\"\n ) {\n privateNameMap[name] = \"true\";\n return false\n } else if (!curr) {\n privateNameMap[name] = next;\n return false\n } else {\n return true\n }\n}\n\nfunction checkKeyName(node, name) {\n var computed = node.computed;\n var key = node.key;\n return !computed && (\n key.type === \"Identifier\" && key.name === name ||\n key.type === \"Literal\" && key.value === name\n )\n}\n\n// Parses module export declaration.\n\npp$1.parseExport = function(node, exports) {\n this.next();\n // export * from '...'\n if (this.eat(types.star)) {\n if (this.options.ecmaVersion >= 11) {\n if (this.eatContextual(\"as\")) {\n node.exported = this.parseIdent(true);\n this.checkExport(exports, node.exported.name, this.lastTokStart);\n } else {\n node.exported = null;\n }\n }\n this.expectContextual(\"from\");\n if (this.type !== types.string) { this.unexpected(); }\n node.source = this.parseExprAtom();\n this.semicolon();\n return this.finishNode(node, \"ExportAllDeclaration\")\n }\n if (this.eat(types._default)) { // export default ...\n this.checkExport(exports, \"default\", this.lastTokStart);\n var isAsync;\n if (this.type === types._function || (isAsync = this.isAsyncFunction())) {\n var fNode = this.startNode();\n this.next();\n if (isAsync) { this.next(); }\n node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);\n } else if (this.type === types._class) {\n var cNode = this.startNode();\n node.declaration = this.parseClass(cNode, \"nullableID\");\n } else {\n node.declaration = this.parseMaybeAssign();\n this.semicolon();\n }\n return this.finishNode(node, \"ExportDefaultDeclaration\")\n }\n // export var|const|let|function|class ...\n if (this.shouldParseExportStatement()) {\n node.declaration = this.parseStatement(null);\n if (node.declaration.type === \"VariableDeclaration\")\n { this.checkVariableExport(exports, node.declaration.declarations); }\n else\n { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }\n node.specifiers = [];\n node.source = null;\n } else { // export { x, y as z } [from '...']\n node.declaration = null;\n node.specifiers = this.parseExportSpecifiers(exports);\n if (this.eatContextual(\"from\")) {\n if (this.type !== types.string) { this.unexpected(); }\n node.source = this.parseExprAtom();\n } else {\n for (var i = 0, list = node.specifiers; i < list.length; i += 1) {\n // check for keywords used as local names\n var spec = list[i];\n\n this.checkUnreserved(spec.local);\n // check if export is defined\n this.checkLocalExport(spec.local);\n }\n\n node.source = null;\n }\n this.semicolon();\n }\n return this.finishNode(node, \"ExportNamedDeclaration\")\n};\n\npp$1.checkExport = function(exports, name, pos) {\n if (!exports) { return }\n if (has(exports, name))\n { this.raiseRecoverable(pos, \"Duplicate export '\" + name + \"'\"); }\n exports[name] = true;\n};\n\npp$1.checkPatternExport = function(exports, pat) {\n var type = pat.type;\n if (type === \"Identifier\")\n { this.checkExport(exports, pat.name, pat.start); }\n else if (type === \"ObjectPattern\")\n { for (var i = 0, list = pat.properties; i < list.length; i += 1)\n {\n var prop = list[i];\n\n this.checkPatternExport(exports, prop);\n } }\n else if (type === \"ArrayPattern\")\n { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {\n var elt = list$1[i$1];\n\n if (elt) { this.checkPatternExport(exports, elt); }\n } }\n else if (type === \"Property\")\n { this.checkPatternExport(exports, pat.value); }\n else if (type === \"AssignmentPattern\")\n { this.checkPatternExport(exports, pat.left); }\n else if (type === \"RestElement\")\n { this.checkPatternExport(exports, pat.argument); }\n else if (type === \"ParenthesizedExpression\")\n { this.checkPatternExport(exports, pat.expression); }\n};\n\npp$1.checkVariableExport = function(exports, decls) {\n if (!exports) { return }\n for (var i = 0, list = decls; i < list.length; i += 1)\n {\n var decl = list[i];\n\n this.checkPatternExport(exports, decl.id);\n }\n};\n\npp$1.shouldParseExportStatement = function() {\n return this.type.keyword === \"var\" ||\n this.type.keyword === \"const\" ||\n this.type.keyword === \"class\" ||\n this.type.keyword === \"function\" ||\n this.isLet() ||\n this.isAsyncFunction()\n};\n\n// Parses a comma-separated list of module exports.\n\npp$1.parseExportSpecifiers = function(exports) {\n var nodes = [], first = true;\n // export { x, y as z } [from '...']\n this.expect(types.braceL);\n while (!this.eat(types.braceR)) {\n if (!first) {\n this.expect(types.comma);\n if (this.afterTrailingComma(types.braceR)) { break }\n } else { first = false; }\n\n var node = this.startNode();\n node.local = this.parseIdent(true);\n node.exported = this.eatContextual(\"as\") ? this.parseIdent(true) : node.local;\n this.checkExport(exports, node.exported.name, node.exported.start);\n nodes.push(this.finishNode(node, \"ExportSpecifier\"));\n }\n return nodes\n};\n\n// Parses import declaration.\n\npp$1.parseImport = function(node) {\n this.next();\n // import '...'\n if (this.type === types.string) {\n node.specifiers = empty;\n node.source = this.parseExprAtom();\n } else {\n node.specifiers = this.parseImportSpecifiers();\n this.expectContextual(\"from\");\n node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();\n }\n this.semicolon();\n return this.finishNode(node, \"ImportDeclaration\")\n};\n\n// Parses a comma-separated list of module imports.\n\npp$1.parseImportSpecifiers = function() {\n var nodes = [], first = true;\n if (this.type === types.name) {\n // import defaultObj, { x, y as z } from '...'\n var node = this.startNode();\n node.local = this.parseIdent();\n this.checkLValSimple(node.local, BIND_LEXICAL);\n nodes.push(this.finishNode(node, \"ImportDefaultSpecifier\"));\n if (!this.eat(types.comma)) { return nodes }\n }\n if (this.type === types.star) {\n var node$1 = this.startNode();\n this.next();\n this.expectContextual(\"as\");\n node$1.local = this.parseIdent();\n this.checkLValSimple(node$1.local, BIND_LEXICAL);\n nodes.push(this.finishNode(node$1, \"ImportNamespaceSpecifier\"));\n return nodes\n }\n this.expect(types.braceL);\n while (!this.eat(types.braceR)) {\n if (!first) {\n this.expect(types.comma);\n if (this.afterTrailingComma(types.braceR)) { break }\n } else { first = false; }\n\n var node$2 = this.startNode();\n node$2.imported = this.parseIdent(true);\n if (this.eatContextual(\"as\")) {\n node$2.local = this.parseIdent();\n } else {\n this.checkUnreserved(node$2.imported);\n node$2.local = node$2.imported;\n }\n this.checkLValSimple(node$2.local, BIND_LEXICAL);\n nodes.push(this.finishNode(node$2, \"ImportSpecifier\"));\n }\n return nodes\n};\n\n// Set `ExpressionStatement#directive` property for directive prologues.\npp$1.adaptDirectivePrologue = function(statements) {\n for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {\n statements[i].directive = statements[i].expression.raw.slice(1, -1);\n }\n};\npp$1.isDirectiveCandidate = function(statement) {\n return (\n statement.type === \"ExpressionStatement\" &&\n statement.expression.type === \"Literal\" &&\n typeof statement.expression.value === \"string\" &&\n // Reject parenthesized strings.\n (this.input[statement.start] === \"\\\"\" || this.input[statement.start] === \"'\")\n )\n};\n\nvar pp$2 = Parser.prototype;\n\n// Convert existing expression atom to assignable pattern\n// if possible.\n\npp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {\n if (this.options.ecmaVersion >= 6 && node) {\n switch (node.type) {\n case \"Identifier\":\n if (this.inAsync && node.name === \"await\")\n { this.raise(node.start, \"Cannot use 'await' as identifier inside an async function\"); }\n break\n\n case \"ObjectPattern\":\n case \"ArrayPattern\":\n case \"AssignmentPattern\":\n case \"RestElement\":\n break\n\n case \"ObjectExpression\":\n node.type = \"ObjectPattern\";\n if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }\n for (var i = 0, list = node.properties; i < list.length; i += 1) {\n var prop = list[i];\n\n this.toAssignable(prop, isBinding);\n // Early error:\n // AssignmentRestProperty[Yield, Await] :\n // `...` DestructuringAssignmentTarget[Yield, Await]\n //\n // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.\n if (\n prop.type === \"RestElement\" &&\n (prop.argument.type === \"ArrayPattern\" || prop.argument.type === \"ObjectPattern\")\n ) {\n this.raise(prop.argument.start, \"Unexpected token\");\n }\n }\n break\n\n case \"Property\":\n // AssignmentProperty has type === \"Property\"\n if (node.kind !== \"init\") { this.raise(node.key.start, \"Object pattern can't contain getter or setter\"); }\n this.toAssignable(node.value, isBinding);\n break\n\n case \"ArrayExpression\":\n node.type = \"ArrayPattern\";\n if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }\n this.toAssignableList(node.elements, isBinding);\n break\n\n case \"SpreadElement\":\n node.type = \"RestElement\";\n this.toAssignable(node.argument, isBinding);\n if (node.argument.type === \"AssignmentPattern\")\n { this.raise(node.argument.start, \"Rest elements cannot have a default value\"); }\n break\n\n case \"AssignmentExpression\":\n if (node.operator !== \"=\") { this.raise(node.left.end, \"Only '=' operator can be used for specifying default value.\"); }\n node.type = \"AssignmentPattern\";\n delete node.operator;\n this.toAssignable(node.left, isBinding);\n break\n\n case \"ParenthesizedExpression\":\n this.toAssignable(node.expression, isBinding, refDestructuringErrors);\n break\n\n case \"ChainExpression\":\n this.raiseRecoverable(node.start, \"Optional chaining cannot appear in left-hand side\");\n break\n\n case \"MemberExpression\":\n if (!isBinding) { break }\n\n default:\n this.raise(node.start, \"Assigning to rvalue\");\n }\n } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }\n return node\n};\n\n// Convert list of expression atoms to binding list.\n\npp$2.toAssignableList = function(exprList, isBinding) {\n var end = exprList.length;\n for (var i = 0; i < end; i++) {\n var elt = exprList[i];\n if (elt) { this.toAssignable(elt, isBinding); }\n }\n if (end) {\n var last = exprList[end - 1];\n if (this.options.ecmaVersion === 6 && isBinding && last && last.type === \"RestElement\" && last.argument.type !== \"Identifier\")\n { this.unexpected(last.argument.start); }\n }\n return exprList\n};\n\n// Parses spread element.\n\npp$2.parseSpread = function(refDestructuringErrors) {\n var node = this.startNode();\n this.next();\n node.argument = this.parseMaybeAssign(false, refDestructuringErrors);\n return this.finishNode(node, \"SpreadElement\")\n};\n\npp$2.parseRestBinding = function() {\n var node = this.startNode();\n this.next();\n\n // RestElement inside of a function parameter must be an identifier\n if (this.options.ecmaVersion === 6 && this.type !== types.name)\n { this.unexpected(); }\n\n node.argument = this.parseBindingAtom();\n\n return this.finishNode(node, \"RestElement\")\n};\n\n// Parses lvalue (assignable) atom.\n\npp$2.parseBindingAtom = function() {\n if (this.options.ecmaVersion >= 6) {\n switch (this.type) {\n case types.bracketL:\n var node = this.startNode();\n this.next();\n node.elements = this.parseBindingList(types.bracketR, true, true);\n return this.finishNode(node, \"ArrayPattern\")\n\n case types.braceL:\n return this.parseObj(true)\n }\n }\n return this.parseIdent()\n};\n\npp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {\n var elts = [], first = true;\n while (!this.eat(close)) {\n if (first) { first = false; }\n else { this.expect(types.comma); }\n if (allowEmpty && this.type === types.comma) {\n elts.push(null);\n } else if (allowTrailingComma && this.afterTrailingComma(close)) {\n break\n } else if (this.type === types.ellipsis) {\n var rest = this.parseRestBinding();\n this.parseBindingListItem(rest);\n elts.push(rest);\n if (this.type === types.comma) { this.raise(this.start, \"Comma is not permitted after the rest element\"); }\n this.expect(close);\n break\n } else {\n var elem = this.parseMaybeDefault(this.start, this.startLoc);\n this.parseBindingListItem(elem);\n elts.push(elem);\n }\n }\n return elts\n};\n\npp$2.parseBindingListItem = function(param) {\n return param\n};\n\n// Parses assignment pattern around given atom if possible.\n\npp$2.parseMaybeDefault = function(startPos, startLoc, left) {\n left = left || this.parseBindingAtom();\n if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }\n var node = this.startNodeAt(startPos, startLoc);\n node.left = left;\n node.right = this.parseMaybeAssign();\n return this.finishNode(node, \"AssignmentPattern\")\n};\n\n// The following three functions all verify that a node is an lvalue —\n// something that can be bound, or assigned to. In order to do so, they perform\n// a variety of checks:\n//\n// - Check that none of the bound/assigned-to identifiers are reserved words.\n// - Record name declarations for bindings in the appropriate scope.\n// - Check duplicate argument names, if checkClashes is set.\n//\n// If a complex binding pattern is encountered (e.g., object and array\n// destructuring), the entire pattern is recursively checked.\n//\n// There are three versions of checkLVal*() appropriate for different\n// circumstances:\n//\n// - checkLValSimple() shall be used if the syntactic construct supports\n// nothing other than identifiers and member expressions. Parenthesized\n// expressions are also correctly handled. This is generally appropriate for\n// constructs for which the spec says\n//\n// > It is a Syntax Error if AssignmentTargetType of [the production] is not\n// > simple.\n//\n// It is also appropriate for checking if an identifier is valid and not\n// defined elsewhere, like import declarations or function/class identifiers.\n//\n// Examples where this is used include:\n// a += …;\n// import a from '…';\n// where a is the node to be checked.\n//\n// - checkLValPattern() shall be used if the syntactic construct supports\n// anything checkLValSimple() supports, as well as object and array\n// destructuring patterns. This is generally appropriate for constructs for\n// which the spec says\n//\n// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor\n// > an ArrayLiteral and AssignmentTargetType of [the production] is not\n// > simple.\n//\n// Examples where this is used include:\n// (a = …);\n// const a = …;\n// try { … } catch (a) { … }\n// where a is the node to be checked.\n//\n// - checkLValInnerPattern() shall be used if the syntactic construct supports\n// anything checkLValPattern() supports, as well as default assignment\n// patterns, rest elements, and other constructs that may appear within an\n// object or array destructuring pattern.\n//\n// As a special case, function parameters also use checkLValInnerPattern(),\n// as they also support defaults and rest constructs.\n//\n// These functions deliberately support both assignment and binding constructs,\n// as the logic for both is exceedingly similar. If the node is the target of\n// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it\n// should be set to the appropriate BIND_* constant, like BIND_VAR or\n// BIND_LEXICAL.\n//\n// If the function is called with a non-BIND_NONE bindingType, then\n// additionally a checkClashes object may be specified to allow checking for\n// duplicate argument names. checkClashes is ignored if the provided construct\n// is an assignment (i.e., bindingType is BIND_NONE).\n\npp$2.checkLValSimple = function(expr, bindingType, checkClashes) {\n if ( bindingType === void 0 ) bindingType = BIND_NONE;\n\n var isBind = bindingType !== BIND_NONE;\n\n switch (expr.type) {\n case \"Identifier\":\n if (this.strict && this.reservedWordsStrictBind.test(expr.name))\n { this.raiseRecoverable(expr.start, (isBind ? \"Binding \" : \"Assigning to \") + expr.name + \" in strict mode\"); }\n if (isBind) {\n if (bindingType === BIND_LEXICAL && expr.name === \"let\")\n { this.raiseRecoverable(expr.start, \"let is disallowed as a lexically bound name\"); }\n if (checkClashes) {\n if (has(checkClashes, expr.name))\n { this.raiseRecoverable(expr.start, \"Argument name clash\"); }\n checkClashes[expr.name] = true;\n }\n if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }\n }\n break\n\n case \"ChainExpression\":\n this.raiseRecoverable(expr.start, \"Optional chaining cannot appear in left-hand side\");\n break\n\n case \"MemberExpression\":\n if (isBind) { this.raiseRecoverable(expr.start, \"Binding member expression\"); }\n break\n\n case \"ParenthesizedExpression\":\n if (isBind) { this.raiseRecoverable(expr.start, \"Binding parenthesized expression\"); }\n return this.checkLValSimple(expr.expression, bindingType, checkClashes)\n\n default:\n this.raise(expr.start, (isBind ? \"Binding\" : \"Assigning to\") + \" rvalue\");\n }\n};\n\npp$2.checkLValPattern = function(expr, bindingType, checkClashes) {\n if ( bindingType === void 0 ) bindingType = BIND_NONE;\n\n switch (expr.type) {\n case \"ObjectPattern\":\n for (var i = 0, list = expr.properties; i < list.length; i += 1) {\n var prop = list[i];\n\n this.checkLValInnerPattern(prop, bindingType, checkClashes);\n }\n break\n\n case \"ArrayPattern\":\n for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {\n var elem = list$1[i$1];\n\n if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }\n }\n break\n\n default:\n this.checkLValSimple(expr, bindingType, checkClashes);\n }\n};\n\npp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {\n if ( bindingType === void 0 ) bindingType = BIND_NONE;\n\n switch (expr.type) {\n case \"Property\":\n // AssignmentProperty has type === \"Property\"\n this.checkLValInnerPattern(expr.value, bindingType, checkClashes);\n break\n\n case \"AssignmentPattern\":\n this.checkLValPattern(expr.left, bindingType, checkClashes);\n break\n\n case \"RestElement\":\n this.checkLValPattern(expr.argument, bindingType, checkClashes);\n break\n\n default:\n this.checkLValPattern(expr, bindingType, checkClashes);\n }\n};\n\n// A recursive descent parser operates by defining functions for all\n\nvar pp$3 = Parser.prototype;\n\n// Check if property name clashes with already added.\n// Object/class getters and setters are not allowed to clash —\n// either with each other or with an init property — and in\n// strict mode, init properties are also not allowed to be repeated.\n\npp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {\n if (this.options.ecmaVersion >= 9 && prop.type === \"SpreadElement\")\n { return }\n if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))\n { return }\n var key = prop.key;\n var name;\n switch (key.type) {\n case \"Identifier\": name = key.name; break\n case \"Literal\": name = String(key.value); break\n default: return\n }\n var kind = prop.kind;\n if (this.options.ecmaVersion >= 6) {\n if (name === \"__proto__\" && kind === \"init\") {\n if (propHash.proto) {\n if (refDestructuringErrors) {\n if (refDestructuringErrors.doubleProto < 0)\n { refDestructuringErrors.doubleProto = key.start; }\n // Backwards-compat kludge. Can be removed in version 6.0\n } else { this.raiseRecoverable(key.start, \"Redefinition of __proto__ property\"); }\n }\n propHash.proto = true;\n }\n return\n }\n name = \"$\" + name;\n var other = propHash[name];\n if (other) {\n var redefinition;\n if (kind === \"init\") {\n redefinition = this.strict && other.init || other.get || other.set;\n } else {\n redefinition = other.init || other[kind];\n }\n if (redefinition)\n { this.raiseRecoverable(key.start, \"Redefinition of property\"); }\n } else {\n other = propHash[name] = {\n init: false,\n get: false,\n set: false\n };\n }\n other[kind] = true;\n};\n\n// ### Expression parsing\n\n// These nest, from the most general expression type at the top to\n// 'atomic', nondivisible expression types at the bottom. Most of\n// the functions will simply let the function(s) below them parse,\n// and, *if* the syntactic construct they handle is present, wrap\n// the AST node that the inner parser gave them in another node.\n\n// Parse a full expression. The optional arguments are used to\n// forbid the `in` operator (in for loops initalization expressions)\n// and provide reference for storing '=' operator inside shorthand\n// property assignment in contexts where both object expression\n// and object pattern might appear (so it's possible to raise\n// delayed syntax error at correct position).\n\npp$3.parseExpression = function(forInit, refDestructuringErrors) {\n var startPos = this.start, startLoc = this.startLoc;\n var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);\n if (this.type === types.comma) {\n var node = this.startNodeAt(startPos, startLoc);\n node.expressions = [expr];\n while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }\n return this.finishNode(node, \"SequenceExpression\")\n }\n return expr\n};\n\n// Parse an assignment expression. This includes applications of\n// operators like `+=`.\n\npp$3.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {\n if (this.isContextual(\"yield\")) {\n if (this.inGenerator) { return this.parseYield(forInit) }\n // The tokenizer will assume an expression is allowed after\n // `yield`, but this isn't that kind of yield\n else { this.exprAllowed = false; }\n }\n\n var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;\n if (refDestructuringErrors) {\n oldParenAssign = refDestructuringErrors.parenthesizedAssign;\n oldTrailingComma = refDestructuringErrors.trailingComma;\n refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;\n } else {\n refDestructuringErrors = new DestructuringErrors;\n ownDestructuringErrors = true;\n }\n\n var startPos = this.start, startLoc = this.startLoc;\n if (this.type === types.parenL || this.type === types.name) {\n this.potentialArrowAt = this.start;\n this.potentialArrowInForAwait = forInit === \"await\";\n }\n var left = this.parseMaybeConditional(forInit, refDestructuringErrors);\n if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }\n if (this.type.isAssign) {\n var node = this.startNodeAt(startPos, startLoc);\n node.operator = this.value;\n if (this.type === types.eq)\n { left = this.toAssignable(left, false, refDestructuringErrors); }\n if (!ownDestructuringErrors) {\n refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;\n }\n if (refDestructuringErrors.shorthandAssign >= left.start)\n { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly\n if (this.type === types.eq)\n { this.checkLValPattern(left); }\n else\n { this.checkLValSimple(left); }\n node.left = left;\n this.next();\n node.right = this.parseMaybeAssign(forInit);\n return this.finishNode(node, \"AssignmentExpression\")\n } else {\n if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }\n }\n if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }\n if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }\n return left\n};\n\n// Parse a ternary conditional (`?:`) operator.\n\npp$3.parseMaybeConditional = function(forInit, refDestructuringErrors) {\n var startPos = this.start, startLoc = this.startLoc;\n var expr = this.parseExprOps(forInit, refDestructuringErrors);\n if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }\n if (this.eat(types.question)) {\n var node = this.startNodeAt(startPos, startLoc);\n node.test = expr;\n node.consequent = this.parseMaybeAssign();\n this.expect(types.colon);\n node.alternate = this.parseMaybeAssign(forInit);\n return this.finishNode(node, \"ConditionalExpression\")\n }\n return expr\n};\n\n// Start the precedence parser.\n\npp$3.parseExprOps = function(forInit, refDestructuringErrors) {\n var startPos = this.start, startLoc = this.startLoc;\n var expr = this.parseMaybeUnary(refDestructuringErrors, false);\n if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }\n return expr.start === startPos && expr.type === \"ArrowFunctionExpression\" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)\n};\n\n// Parse binary operators with the operator precedence parsing\n// algorithm. `left` is the left-hand side of the operator.\n// `minPrec` provides context that allows the function to stop and\n// defer further parser to one of its callers when it encounters an\n// operator that has a lower precedence than the set it is parsing.\n\npp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {\n var prec = this.type.binop;\n if (prec != null && (!forInit || this.type !== types._in)) {\n if (prec > minPrec) {\n var logical = this.type === types.logicalOR || this.type === types.logicalAND;\n var coalesce = this.type === types.coalesce;\n if (coalesce) {\n // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.\n // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.\n prec = types.logicalAND.binop;\n }\n var op = this.value;\n this.next();\n var startPos = this.start, startLoc = this.startLoc;\n var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit);\n var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);\n if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {\n this.raiseRecoverable(this.start, \"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses\");\n }\n return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)\n }\n }\n return left\n};\n\npp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {\n var node = this.startNodeAt(startPos, startLoc);\n node.left = left;\n node.operator = op;\n node.right = right;\n return this.finishNode(node, logical ? \"LogicalExpression\" : \"BinaryExpression\")\n};\n\n// Parse unary operators, both prefix and postfix.\n\npp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) {\n var startPos = this.start, startLoc = this.startLoc, expr;\n if (this.isContextual(\"await\") && this.canAwait) {\n expr = this.parseAwait();\n sawUnary = true;\n } else if (this.type.prefix) {\n var node = this.startNode(), update = this.type === types.incDec;\n node.operator = this.value;\n node.prefix = true;\n this.next();\n node.argument = this.parseMaybeUnary(null, true, update);\n this.checkExpressionErrors(refDestructuringErrors, true);\n if (update) { this.checkLValSimple(node.argument); }\n else if (this.strict && node.operator === \"delete\" &&\n node.argument.type === \"Identifier\")\n { this.raiseRecoverable(node.start, \"Deleting local variable in strict mode\"); }\n else if (node.operator === \"delete\" && isPrivateFieldAccess(node.argument))\n { this.raiseRecoverable(node.start, \"Private fields can not be deleted\"); }\n else { sawUnary = true; }\n expr = this.finishNode(node, update ? \"UpdateExpression\" : \"UnaryExpression\");\n } else {\n expr = this.parseExprSubscripts(refDestructuringErrors);\n if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }\n while (this.type.postfix && !this.canInsertSemicolon()) {\n var node$1 = this.startNodeAt(startPos, startLoc);\n node$1.operator = this.value;\n node$1.prefix = false;\n node$1.argument = expr;\n this.checkLValSimple(expr);\n this.next();\n expr = this.finishNode(node$1, \"UpdateExpression\");\n }\n }\n\n if (!incDec && this.eat(types.starstar)) {\n if (sawUnary)\n { this.unexpected(this.lastTokStart); }\n else\n { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), \"**\", false) }\n } else {\n return expr\n }\n};\n\nfunction isPrivateFieldAccess(node) {\n return (\n node.type === \"MemberExpression\" && node.property.type === \"PrivateIdentifier\" ||\n node.type === \"ChainExpression\" && isPrivateFieldAccess(node.expression)\n )\n}\n\n// Parse call, dot, and `[]`-subscript expressions.\n\npp$3.parseExprSubscripts = function(refDestructuringErrors) {\n var startPos = this.start, startLoc = this.startLoc;\n var expr = this.parseExprAtom(refDestructuringErrors);\n if (expr.type === \"ArrowFunctionExpression\" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== \")\")\n { return expr }\n var result = this.parseSubscripts(expr, startPos, startLoc);\n if (refDestructuringErrors && result.type === \"MemberExpression\") {\n if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }\n if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }\n if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }\n }\n return result\n};\n\npp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {\n var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === \"Identifier\" && base.name === \"async\" &&\n this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&\n this.potentialArrowAt === base.start;\n var optionalChained = false;\n\n while (true) {\n var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);\n\n if (element.optional) { optionalChained = true; }\n if (element === base || element.type === \"ArrowFunctionExpression\") {\n if (optionalChained) {\n var chainNode = this.startNodeAt(startPos, startLoc);\n chainNode.expression = element;\n element = this.finishNode(chainNode, \"ChainExpression\");\n }\n return element\n }\n\n base = element;\n }\n};\n\npp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {\n var optionalSupported = this.options.ecmaVersion >= 11;\n var optional = optionalSupported && this.eat(types.questionDot);\n if (noCalls && optional) { this.raise(this.lastTokStart, \"Optional chaining cannot appear in the callee of new expressions\"); }\n\n var computed = this.eat(types.bracketL);\n if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {\n var node = this.startNodeAt(startPos, startLoc);\n node.object = base;\n if (computed) {\n node.property = this.parseExpression();\n this.expect(types.bracketR);\n } else if (this.type === types.privateId && base.type !== \"Super\") {\n node.property = this.parsePrivateIdent();\n } else {\n node.property = this.parseIdent(this.options.allowReserved !== \"never\");\n }\n node.computed = !!computed;\n if (optionalSupported) {\n node.optional = optional;\n }\n base = this.finishNode(node, \"MemberExpression\");\n } else if (!noCalls && this.eat(types.parenL)) {\n var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;\n this.yieldPos = 0;\n this.awaitPos = 0;\n this.awaitIdentPos = 0;\n var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);\n if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {\n this.checkPatternErrors(refDestructuringErrors, false);\n this.checkYieldAwaitInDefaultParams();\n if (this.awaitIdentPos > 0)\n { this.raise(this.awaitIdentPos, \"Cannot use 'await' as identifier inside an async function\"); }\n this.yieldPos = oldYieldPos;\n this.awaitPos = oldAwaitPos;\n this.awaitIdentPos = oldAwaitIdentPos;\n return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)\n }\n this.checkExpressionErrors(refDestructuringErrors, true);\n this.yieldPos = oldYieldPos || this.yieldPos;\n this.awaitPos = oldAwaitPos || this.awaitPos;\n this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;\n var node$1 = this.startNodeAt(startPos, startLoc);\n node$1.callee = base;\n node$1.arguments = exprList;\n if (optionalSupported) {\n node$1.optional = optional;\n }\n base = this.finishNode(node$1, \"CallExpression\");\n } else if (this.type === types.backQuote) {\n if (optional || optionalChained) {\n this.raise(this.start, \"Optional chaining cannot appear in the tag of tagged template expressions\");\n }\n var node$2 = this.startNodeAt(startPos, startLoc);\n node$2.tag = base;\n node$2.quasi = this.parseTemplate({isTagged: true});\n base = this.finishNode(node$2, \"TaggedTemplateExpression\");\n }\n return base\n};\n\n// Parse an atomic expression — either a single token that is an\n// expression, an expression started by a keyword like `function` or\n// `new`, or an expression wrapped in punctuation like `()`, `[]`,\n// or `{}`.\n\npp$3.parseExprAtom = function(refDestructuringErrors) {\n // If a division operator appears in an expression position, the\n // tokenizer got confused, and we force it to read a regexp instead.\n if (this.type === types.slash) { this.readRegexp(); }\n\n var node, canBeArrow = this.potentialArrowAt === this.start;\n switch (this.type) {\n case types._super:\n if (!this.allowSuper)\n { this.raise(this.start, \"'super' keyword outside a method\"); }\n node = this.startNode();\n this.next();\n if (this.type === types.parenL && !this.allowDirectSuper)\n { this.raise(node.start, \"super() call outside constructor of a subclass\"); }\n // The `super` keyword can appear at below:\n // SuperProperty:\n // super [ Expression ]\n // super . IdentifierName\n // SuperCall:\n // super ( Arguments )\n if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)\n { this.unexpected(); }\n return this.finishNode(node, \"Super\")\n\n case types._this:\n node = this.startNode();\n this.next();\n return this.finishNode(node, \"ThisExpression\")\n\n case types.name:\n var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;\n var id = this.parseIdent(false);\n if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === \"async\" && !this.canInsertSemicolon() && this.eat(types._function))\n { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }\n if (canBeArrow && !this.canInsertSemicolon()) {\n if (this.eat(types.arrow))\n { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }\n if (this.options.ecmaVersion >= 8 && id.name === \"async\" && this.type === types.name && !containsEsc &&\n (!this.potentialArrowInForAwait || this.value !== \"of\" || this.containsEsc)) {\n id = this.parseIdent(false);\n if (this.canInsertSemicolon() || !this.eat(types.arrow))\n { this.unexpected(); }\n return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)\n }\n }\n return id\n\n case types.regexp:\n var value = this.value;\n node = this.parseLiteral(value.value);\n node.regex = {pattern: value.pattern, flags: value.flags};\n return node\n\n case types.num: case types.string:\n return this.parseLiteral(this.value)\n\n case types._null: case types._true: case types._false:\n node = this.startNode();\n node.value = this.type === types._null ? null : this.type === types._true;\n node.raw = this.type.keyword;\n this.next();\n return this.finishNode(node, \"Literal\")\n\n case types.parenL:\n var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);\n if (refDestructuringErrors) {\n if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))\n { refDestructuringErrors.parenthesizedAssign = start; }\n if (refDestructuringErrors.parenthesizedBind < 0)\n { refDestructuringErrors.parenthesizedBind = start; }\n }\n return expr\n\n case types.bracketL:\n node = this.startNode();\n this.next();\n node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);\n return this.finishNode(node, \"ArrayExpression\")\n\n case types.braceL:\n return this.parseObj(false, refDestructuringErrors)\n\n case types._function:\n node = this.startNode();\n this.next();\n return this.parseFunction(node, 0)\n\n case types._class:\n return this.parseClass(this.startNode(), false)\n\n case types._new:\n return this.parseNew()\n\n case types.backQuote:\n return this.parseTemplate()\n\n case types._import:\n if (this.options.ecmaVersion >= 11) {\n return this.parseExprImport()\n } else {\n return this.unexpected()\n }\n\n default:\n this.unexpected();\n }\n};\n\npp$3.parseExprImport = function() {\n var node = this.startNode();\n\n // Consume `import` as an identifier for `import.meta`.\n // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.\n if (this.containsEsc) { this.raiseRecoverable(this.start, \"Escape sequence in keyword import\"); }\n var meta = this.parseIdent(true);\n\n switch (this.type) {\n case types.parenL:\n return this.parseDynamicImport(node)\n case types.dot:\n node.meta = meta;\n return this.parseImportMeta(node)\n default:\n this.unexpected();\n }\n};\n\npp$3.parseDynamicImport = function(node) {\n this.next(); // skip `(`\n\n // Parse node.source.\n node.source = this.parseMaybeAssign();\n\n // Verify ending.\n if (!this.eat(types.parenR)) {\n var errorPos = this.start;\n if (this.eat(types.comma) && this.eat(types.parenR)) {\n this.raiseRecoverable(errorPos, \"Trailing comma is not allowed in import()\");\n } else {\n this.unexpected(errorPos);\n }\n }\n\n return this.finishNode(node, \"ImportExpression\")\n};\n\npp$3.parseImportMeta = function(node) {\n this.next(); // skip `.`\n\n var containsEsc = this.containsEsc;\n node.property = this.parseIdent(true);\n\n if (node.property.name !== \"meta\")\n { this.raiseRecoverable(node.property.start, \"The only valid meta property for import is 'import.meta'\"); }\n if (containsEsc)\n { this.raiseRecoverable(node.start, \"'import.meta' must not contain escaped characters\"); }\n if (this.options.sourceType !== \"module\" && !this.options.allowImportExportEverywhere)\n { this.raiseRecoverable(node.start, \"Cannot use 'import.meta' outside a module\"); }\n\n return this.finishNode(node, \"MetaProperty\")\n};\n\npp$3.parseLiteral = function(value) {\n var node = this.startNode();\n node.value = value;\n node.raw = this.input.slice(this.start, this.end);\n if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, \"\"); }\n this.next();\n return this.finishNode(node, \"Literal\")\n};\n\npp$3.parseParenExpression = function() {\n this.expect(types.parenL);\n var val = this.parseExpression();\n this.expect(types.parenR);\n return val\n};\n\npp$3.parseParenAndDistinguishExpression = function(canBeArrow) {\n var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;\n if (this.options.ecmaVersion >= 6) {\n this.next();\n\n var innerStartPos = this.start, innerStartLoc = this.startLoc;\n var exprList = [], first = true, lastIsComma = false;\n var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;\n this.yieldPos = 0;\n this.awaitPos = 0;\n // Do not save awaitIdentPos to allow checking awaits nested in parameters\n while (this.type !== types.parenR) {\n first ? first = false : this.expect(types.comma);\n if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {\n lastIsComma = true;\n break\n } else if (this.type === types.ellipsis) {\n spreadStart = this.start;\n exprList.push(this.parseParenItem(this.parseRestBinding()));\n if (this.type === types.comma) { this.raise(this.start, \"Comma is not permitted after the rest element\"); }\n break\n } else {\n exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));\n }\n }\n var innerEndPos = this.start, innerEndLoc = this.startLoc;\n this.expect(types.parenR);\n\n if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {\n this.checkPatternErrors(refDestructuringErrors, false);\n this.checkYieldAwaitInDefaultParams();\n this.yieldPos = oldYieldPos;\n this.awaitPos = oldAwaitPos;\n return this.parseParenArrowList(startPos, startLoc, exprList)\n }\n\n if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }\n if (spreadStart) { this.unexpected(spreadStart); }\n this.checkExpressionErrors(refDestructuringErrors, true);\n this.yieldPos = oldYieldPos || this.yieldPos;\n this.awaitPos = oldAwaitPos || this.awaitPos;\n\n if (exprList.length > 1) {\n val = this.startNodeAt(innerStartPos, innerStartLoc);\n val.expressions = exprList;\n this.finishNodeAt(val, \"SequenceExpression\", innerEndPos, innerEndLoc);\n } else {\n val = exprList[0];\n }\n } else {\n val = this.parseParenExpression();\n }\n\n if (this.options.preserveParens) {\n var par = this.startNodeAt(startPos, startLoc);\n par.expression = val;\n return this.finishNode(par, \"ParenthesizedExpression\")\n } else {\n return val\n }\n};\n\npp$3.parseParenItem = function(item) {\n return item\n};\n\npp$3.parseParenArrowList = function(startPos, startLoc, exprList) {\n return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)\n};\n\n// New's precedence is slightly tricky. It must allow its argument to\n// be a `[]` or dot subscript expression, but not a call — at least,\n// not without wrapping it in parentheses. Thus, it uses the noCalls\n// argument to parseSubscripts to prevent it from consuming the\n// argument list.\n\nvar empty$1 = [];\n\npp$3.parseNew = function() {\n if (this.containsEsc) { this.raiseRecoverable(this.start, \"Escape sequence in keyword new\"); }\n var node = this.startNode();\n var meta = this.parseIdent(true);\n if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {\n node.meta = meta;\n var containsEsc = this.containsEsc;\n node.property = this.parseIdent(true);\n if (node.property.name !== \"target\")\n { this.raiseRecoverable(node.property.start, \"The only valid meta property for new is 'new.target'\"); }\n if (containsEsc)\n { this.raiseRecoverable(node.start, \"'new.target' must not contain escaped characters\"); }\n if (!this.inNonArrowFunction)\n { this.raiseRecoverable(node.start, \"'new.target' can only be used in functions\"); }\n return this.finishNode(node, \"MetaProperty\")\n }\n var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;\n node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);\n if (isImport && node.callee.type === \"ImportExpression\") {\n this.raise(startPos, \"Cannot use new with import()\");\n }\n if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }\n else { node.arguments = empty$1; }\n return this.finishNode(node, \"NewExpression\")\n};\n\n// Parse template expression.\n\npp$3.parseTemplateElement = function(ref) {\n var isTagged = ref.isTagged;\n\n var elem = this.startNode();\n if (this.type === types.invalidTemplate) {\n if (!isTagged) {\n this.raiseRecoverable(this.start, \"Bad escape sequence in untagged template literal\");\n }\n elem.value = {\n raw: this.value,\n cooked: null\n };\n } else {\n elem.value = {\n raw: this.input.slice(this.start, this.end).replace(/\\r\\n?/g, \"\\n\"),\n cooked: this.value\n };\n }\n this.next();\n elem.tail = this.type === types.backQuote;\n return this.finishNode(elem, \"TemplateElement\")\n};\n\npp$3.parseTemplate = function(ref) {\n if ( ref === void 0 ) ref = {};\n var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;\n\n var node = this.startNode();\n this.next();\n node.expressions = [];\n var curElt = this.parseTemplateElement({isTagged: isTagged});\n node.quasis = [curElt];\n while (!curElt.tail) {\n if (this.type === types.eof) { this.raise(this.pos, \"Unterminated template literal\"); }\n this.expect(types.dollarBraceL);\n node.expressions.push(this.parseExpression());\n this.expect(types.braceR);\n node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));\n }\n this.next();\n return this.finishNode(node, \"TemplateLiteral\")\n};\n\npp$3.isAsyncProp = function(prop) {\n return !prop.computed && prop.key.type === \"Identifier\" && prop.key.name === \"async\" &&\n (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&\n !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))\n};\n\n// Parse an object literal or binding pattern.\n\npp$3.parseObj = function(isPattern, refDestructuringErrors) {\n var node = this.startNode(), first = true, propHash = {};\n node.properties = [];\n this.next();\n while (!this.eat(types.braceR)) {\n if (!first) {\n this.expect(types.comma);\n if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }\n } else { first = false; }\n\n var prop = this.parseProperty(isPattern, refDestructuringErrors);\n if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }\n node.properties.push(prop);\n }\n return this.finishNode(node, isPattern ? \"ObjectPattern\" : \"ObjectExpression\")\n};\n\npp$3.parseProperty = function(isPattern, refDestructuringErrors) {\n var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;\n if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {\n if (isPattern) {\n prop.argument = this.parseIdent(false);\n if (this.type === types.comma) {\n this.raise(this.start, \"Comma is not permitted after the rest element\");\n }\n return this.finishNode(prop, \"RestElement\")\n }\n // To disallow parenthesized identifier via `this.toAssignable()`.\n if (this.type === types.parenL && refDestructuringErrors) {\n if (refDestructuringErrors.parenthesizedAssign < 0) {\n refDestructuringErrors.parenthesizedAssign = this.start;\n }\n if (refDestructuringErrors.parenthesizedBind < 0) {\n refDestructuringErrors.parenthesizedBind = this.start;\n }\n }\n // Parse argument.\n prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);\n // To disallow trailing comma via `this.toAssignable()`.\n if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {\n refDestructuringErrors.trailingComma = this.start;\n }\n // Finish\n return this.finishNode(prop, \"SpreadElement\")\n }\n if (this.options.ecmaVersion >= 6) {\n prop.method = false;\n prop.shorthand = false;\n if (isPattern || refDestructuringErrors) {\n startPos = this.start;\n startLoc = this.startLoc;\n }\n if (!isPattern)\n { isGenerator = this.eat(types.star); }\n }\n var containsEsc = this.containsEsc;\n this.parsePropertyName(prop);\n if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {\n isAsync = true;\n isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);\n this.parsePropertyName(prop, refDestructuringErrors);\n } else {\n isAsync = false;\n }\n this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);\n return this.finishNode(prop, \"Property\")\n};\n\npp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {\n if ((isGenerator || isAsync) && this.type === types.colon)\n { this.unexpected(); }\n\n if (this.eat(types.colon)) {\n prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);\n prop.kind = \"init\";\n } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {\n if (isPattern) { this.unexpected(); }\n prop.kind = \"init\";\n prop.method = true;\n prop.value = this.parseMethod(isGenerator, isAsync);\n } else if (!isPattern && !containsEsc &&\n this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === \"Identifier\" &&\n (prop.key.name === \"get\" || prop.key.name === \"set\") &&\n (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {\n if (isGenerator || isAsync) { this.unexpected(); }\n prop.kind = prop.key.name;\n this.parsePropertyName(prop);\n prop.value = this.parseMethod(false);\n var paramCount = prop.kind === \"get\" ? 0 : 1;\n if (prop.value.params.length !== paramCount) {\n var start = prop.value.start;\n if (prop.kind === \"get\")\n { this.raiseRecoverable(start, \"getter should have no params\"); }\n else\n { this.raiseRecoverable(start, \"setter should have exactly one param\"); }\n } else {\n if (prop.kind === \"set\" && prop.value.params[0].type === \"RestElement\")\n { this.raiseRecoverable(prop.value.params[0].start, \"Setter cannot use rest params\"); }\n }\n } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === \"Identifier\") {\n if (isGenerator || isAsync) { this.unexpected(); }\n this.checkUnreserved(prop.key);\n if (prop.key.name === \"await\" && !this.awaitIdentPos)\n { this.awaitIdentPos = startPos; }\n prop.kind = \"init\";\n if (isPattern) {\n prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));\n } else if (this.type === types.eq && refDestructuringErrors) {\n if (refDestructuringErrors.shorthandAssign < 0)\n { refDestructuringErrors.shorthandAssign = this.start; }\n prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));\n } else {\n prop.value = this.copyNode(prop.key);\n }\n prop.shorthand = true;\n } else { this.unexpected(); }\n};\n\npp$3.parsePropertyName = function(prop) {\n if (this.options.ecmaVersion >= 6) {\n if (this.eat(types.bracketL)) {\n prop.computed = true;\n prop.key = this.parseMaybeAssign();\n this.expect(types.bracketR);\n return prop.key\n } else {\n prop.computed = false;\n }\n }\n return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== \"never\")\n};\n\n// Initialize empty function node.\n\npp$3.initFunction = function(node) {\n node.id = null;\n if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }\n if (this.options.ecmaVersion >= 8) { node.async = false; }\n};\n\n// Parse object or class method.\n\npp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {\n var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;\n\n this.initFunction(node);\n if (this.options.ecmaVersion >= 6)\n { node.generator = isGenerator; }\n if (this.options.ecmaVersion >= 8)\n { node.async = !!isAsync; }\n\n this.yieldPos = 0;\n this.awaitPos = 0;\n this.awaitIdentPos = 0;\n this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));\n\n this.expect(types.parenL);\n node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);\n this.checkYieldAwaitInDefaultParams();\n this.parseFunctionBody(node, false, true);\n\n this.yieldPos = oldYieldPos;\n this.awaitPos = oldAwaitPos;\n this.awaitIdentPos = oldAwaitIdentPos;\n return this.finishNode(node, \"FunctionExpression\")\n};\n\n// Parse arrow function expression with given parameters.\n\npp$3.parseArrowExpression = function(node, params, isAsync) {\n var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;\n\n this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);\n this.initFunction(node);\n if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }\n\n this.yieldPos = 0;\n this.awaitPos = 0;\n this.awaitIdentPos = 0;\n\n node.params = this.toAssignableList(params, true);\n this.parseFunctionBody(node, true, false);\n\n this.yieldPos = oldYieldPos;\n this.awaitPos = oldAwaitPos;\n this.awaitIdentPos = oldAwaitIdentPos;\n return this.finishNode(node, \"ArrowFunctionExpression\")\n};\n\n// Parse function body and check parameters.\n\npp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {\n var isExpression = isArrowFunction && this.type !== types.braceL;\n var oldStrict = this.strict, useStrict = false;\n\n if (isExpression) {\n node.body = this.parseMaybeAssign();\n node.expression = true;\n this.checkParams(node, false);\n } else {\n var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);\n if (!oldStrict || nonSimple) {\n useStrict = this.strictDirective(this.end);\n // If this is a strict mode function, verify that argument names\n // are not repeated, and it does not try to bind the words `eval`\n // or `arguments`.\n if (useStrict && nonSimple)\n { this.raiseRecoverable(node.start, \"Illegal 'use strict' directive in function with non-simple parameter list\"); }\n }\n // Start a new scope with regard to labels and the `inFunction`\n // flag (restore them to their old value afterwards).\n var oldLabels = this.labels;\n this.labels = [];\n if (useStrict) { this.strict = true; }\n\n // Add the params to varDeclaredNames to ensure that an error is thrown\n // if a let/const declaration in the function clashes with one of the params.\n this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));\n // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'\n if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }\n node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);\n node.expression = false;\n this.adaptDirectivePrologue(node.body.body);\n this.labels = oldLabels;\n }\n this.exitScope();\n};\n\npp$3.isSimpleParamList = function(params) {\n for (var i = 0, list = params; i < list.length; i += 1)\n {\n var param = list[i];\n\n if (param.type !== \"Identifier\") { return false\n } }\n return true\n};\n\n// Checks function params for various disallowed patterns such as using \"eval\"\n// or \"arguments\" and duplicate parameters.\n\npp$3.checkParams = function(node, allowDuplicates) {\n var nameHash = Object.create(null);\n for (var i = 0, list = node.params; i < list.length; i += 1)\n {\n var param = list[i];\n\n this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);\n }\n};\n\n// Parses a comma-separated list of expressions, and returns them as\n// an array. `close` is the token type that ends the list, and\n// `allowEmpty` can be turned on to allow subsequent commas with\n// nothing in between them to be parsed as `null` (which is needed\n// for array literals).\n\npp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {\n var elts = [], first = true;\n while (!this.eat(close)) {\n if (!first) {\n this.expect(types.comma);\n if (allowTrailingComma && this.afterTrailingComma(close)) { break }\n } else { first = false; }\n\n var elt = (void 0);\n if (allowEmpty && this.type === types.comma)\n { elt = null; }\n else if (this.type === types.ellipsis) {\n elt = this.parseSpread(refDestructuringErrors);\n if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)\n { refDestructuringErrors.trailingComma = this.start; }\n } else {\n elt = this.parseMaybeAssign(false, refDestructuringErrors);\n }\n elts.push(elt);\n }\n return elts\n};\n\npp$3.checkUnreserved = function(ref) {\n var start = ref.start;\n var end = ref.end;\n var name = ref.name;\n\n if (this.inGenerator && name === \"yield\")\n { this.raiseRecoverable(start, \"Cannot use 'yield' as identifier inside a generator\"); }\n if (this.inAsync && name === \"await\")\n { this.raiseRecoverable(start, \"Cannot use 'await' as identifier inside an async function\"); }\n if (this.currentThisScope().inClassFieldInit && name === \"arguments\")\n { this.raiseRecoverable(start, \"Cannot use 'arguments' in class field initializer\"); }\n if (this.keywords.test(name))\n { this.raise(start, (\"Unexpected keyword '\" + name + \"'\")); }\n if (this.options.ecmaVersion < 6 &&\n this.input.slice(start, end).indexOf(\"\\\\\") !== -1) { return }\n var re = this.strict ? this.reservedWordsStrict : this.reservedWords;\n if (re.test(name)) {\n if (!this.inAsync && name === \"await\")\n { this.raiseRecoverable(start, \"Cannot use keyword 'await' outside an async function\"); }\n this.raiseRecoverable(start, (\"The keyword '\" + name + \"' is reserved\"));\n }\n};\n\n// Parse the next token as an identifier. If `liberal` is true (used\n// when parsing properties), it will also convert keywords into\n// identifiers.\n\npp$3.parseIdent = function(liberal, isBinding) {\n var node = this.startNode();\n if (this.type === types.name) {\n node.name = this.value;\n } else if (this.type.keyword) {\n node.name = this.type.keyword;\n\n // To fix https://github.com/acornjs/acorn/issues/575\n // `class` and `function` keywords push new context into this.context.\n // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.\n // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword\n if ((node.name === \"class\" || node.name === \"function\") &&\n (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {\n this.context.pop();\n }\n } else {\n this.unexpected();\n }\n this.next(!!liberal);\n this.finishNode(node, \"Identifier\");\n if (!liberal) {\n this.checkUnreserved(node);\n if (node.name === \"await\" && !this.awaitIdentPos)\n { this.awaitIdentPos = node.start; }\n }\n return node\n};\n\npp$3.parsePrivateIdent = function() {\n var node = this.startNode();\n if (this.type === types.privateId) {\n node.name = this.value;\n } else {\n this.unexpected();\n }\n this.next();\n this.finishNode(node, \"PrivateIdentifier\");\n\n // For validating existence\n if (this.privateNameStack.length === 0) {\n this.raise(node.start, (\"Private field '#\" + (node.name) + \"' must be declared in an enclosing class\"));\n } else {\n this.privateNameStack[this.privateNameStack.length - 1].used.push(node);\n }\n\n return node\n};\n\n// Parses yield expression inside generator.\n\npp$3.parseYield = function(forInit) {\n if (!this.yieldPos) { this.yieldPos = this.start; }\n\n var node = this.startNode();\n this.next();\n if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {\n node.delegate = false;\n node.argument = null;\n } else {\n node.delegate = this.eat(types.star);\n node.argument = this.parseMaybeAssign(forInit);\n }\n return this.finishNode(node, \"YieldExpression\")\n};\n\npp$3.parseAwait = function() {\n if (!this.awaitPos) { this.awaitPos = this.start; }\n\n var node = this.startNode();\n this.next();\n node.argument = this.parseMaybeUnary(null, true);\n return this.finishNode(node, \"AwaitExpression\")\n};\n\nvar pp$4 = Parser.prototype;\n\n// This function is used to raise exceptions on parse errors. It\n// takes an offset integer (into the current `input`) to indicate\n// the location of the error, attaches the position to the end\n// of the error message, and then raises a `SyntaxError` with that\n// message.\n\npp$4.raise = function(pos, message) {\n var loc = getLineInfo(this.input, pos);\n message += \" (\" + loc.line + \":\" + loc.column + \")\";\n var err = new SyntaxError(message);\n err.pos = pos; err.loc = loc; err.raisedAt = this.pos;\n throw err\n};\n\npp$4.raiseRecoverable = pp$4.raise;\n\npp$4.curPosition = function() {\n if (this.options.locations) {\n return new Position(this.curLine, this.pos - this.lineStart)\n }\n};\n\nvar pp$5 = Parser.prototype;\n\nvar Scope = function Scope(flags) {\n this.flags = flags;\n // A list of var-declared names in the current lexical scope\n this.var = [];\n // A list of lexically-declared names in the current lexical scope\n this.lexical = [];\n // A list of lexically-declared FunctionDeclaration names in the current lexical scope\n this.functions = [];\n // A switch to disallow the identifier reference 'arguments'\n this.inClassFieldInit = false;\n};\n\n// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.\n\npp$5.enterScope = function(flags) {\n this.scopeStack.push(new Scope(flags));\n};\n\npp$5.exitScope = function() {\n this.scopeStack.pop();\n};\n\n// The spec says:\n// > At the top level of a function, or script, function declarations are\n// > treated like var declarations rather than like lexical declarations.\npp$5.treatFunctionsAsVarInScope = function(scope) {\n return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)\n};\n\npp$5.declareName = function(name, bindingType, pos) {\n var redeclared = false;\n if (bindingType === BIND_LEXICAL) {\n var scope = this.currentScope();\n redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;\n scope.lexical.push(name);\n if (this.inModule && (scope.flags & SCOPE_TOP))\n { delete this.undefinedExports[name]; }\n } else if (bindingType === BIND_SIMPLE_CATCH) {\n var scope$1 = this.currentScope();\n scope$1.lexical.push(name);\n } else if (bindingType === BIND_FUNCTION) {\n var scope$2 = this.currentScope();\n if (this.treatFunctionsAsVar)\n { redeclared = scope$2.lexical.indexOf(name) > -1; }\n else\n { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }\n scope$2.functions.push(name);\n } else {\n for (var i = this.scopeStack.length - 1; i >= 0; --i) {\n var scope$3 = this.scopeStack[i];\n if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||\n !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {\n redeclared = true;\n break\n }\n scope$3.var.push(name);\n if (this.inModule && (scope$3.flags & SCOPE_TOP))\n { delete this.undefinedExports[name]; }\n if (scope$3.flags & SCOPE_VAR) { break }\n }\n }\n if (redeclared) { this.raiseRecoverable(pos, (\"Identifier '\" + name + \"' has already been declared\")); }\n};\n\npp$5.checkLocalExport = function(id) {\n // scope.functions must be empty as Module code is always strict.\n if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&\n this.scopeStack[0].var.indexOf(id.name) === -1) {\n this.undefinedExports[id.name] = id;\n }\n};\n\npp$5.currentScope = function() {\n return this.scopeStack[this.scopeStack.length - 1]\n};\n\npp$5.currentVarScope = function() {\n for (var i = this.scopeStack.length - 1;; i--) {\n var scope = this.scopeStack[i];\n if (scope.flags & SCOPE_VAR) { return scope }\n }\n};\n\n// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.\npp$5.currentThisScope = function() {\n for (var i = this.scopeStack.length - 1;; i--) {\n var scope = this.scopeStack[i];\n if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }\n }\n};\n\nvar Node = function Node(parser, pos, loc) {\n this.type = \"\";\n this.start = pos;\n this.end = 0;\n if (parser.options.locations)\n { this.loc = new SourceLocation(parser, loc); }\n if (parser.options.directSourceFile)\n { this.sourceFile = parser.options.directSourceFile; }\n if (parser.options.ranges)\n { this.range = [pos, 0]; }\n};\n\n// Start an AST node, attaching a start offset.\n\nvar pp$6 = Parser.prototype;\n\npp$6.startNode = function() {\n return new Node(this, this.start, this.startLoc)\n};\n\npp$6.startNodeAt = function(pos, loc) {\n return new Node(this, pos, loc)\n};\n\n// Finish an AST node, adding `type` and `end` properties.\n\nfunction finishNodeAt(node, type, pos, loc) {\n node.type = type;\n node.end = pos;\n if (this.options.locations)\n { node.loc.end = loc; }\n if (this.options.ranges)\n { node.range[1] = pos; }\n return node\n}\n\npp$6.finishNode = function(node, type) {\n return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)\n};\n\n// Finish node at given position\n\npp$6.finishNodeAt = function(node, type, pos, loc) {\n return finishNodeAt.call(this, node, type, pos, loc)\n};\n\npp$6.copyNode = function(node) {\n var newNode = new Node(this, node.start, this.startLoc);\n for (var prop in node) { newNode[prop] = node[prop]; }\n return newNode\n};\n\n// The algorithm used to determine whether a regexp can appear at a\n\nvar TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {\n this.token = token;\n this.isExpr = !!isExpr;\n this.preserveSpace = !!preserveSpace;\n this.override = override;\n this.generator = !!generator;\n};\n\nvar types$1 = {\n b_stat: new TokContext(\"{\", false),\n b_expr: new TokContext(\"{\", true),\n b_tmpl: new TokContext(\"${\", false),\n p_stat: new TokContext(\"(\", false),\n p_expr: new TokContext(\"(\", true),\n q_tmpl: new TokContext(\"`\", true, true, function (p) { return p.tryReadTemplateToken(); }),\n f_stat: new TokContext(\"function\", false),\n f_expr: new TokContext(\"function\", true),\n f_expr_gen: new TokContext(\"function\", true, false, null, true),\n f_gen: new TokContext(\"function\", false, false, null, true)\n};\n\nvar pp$7 = Parser.prototype;\n\npp$7.initialContext = function() {\n return [types$1.b_stat]\n};\n\npp$7.braceIsBlock = function(prevType) {\n var parent = this.curContext();\n if (parent === types$1.f_expr || parent === types$1.f_stat)\n { return true }\n if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))\n { return !parent.isExpr }\n\n // The check for `tt.name && exprAllowed` detects whether we are\n // after a `yield` or `of` construct. See the `updateContext` for\n // `tt.name`.\n if (prevType === types._return || prevType === types.name && this.exprAllowed)\n { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }\n if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)\n { return true }\n if (prevType === types.braceL)\n { return parent === types$1.b_stat }\n if (prevType === types._var || prevType === types._const || prevType === types.name)\n { return false }\n return !this.exprAllowed\n};\n\npp$7.inGeneratorContext = function() {\n for (var i = this.context.length - 1; i >= 1; i--) {\n var context = this.context[i];\n if (context.token === \"function\")\n { return context.generator }\n }\n return false\n};\n\npp$7.updateContext = function(prevType) {\n var update, type = this.type;\n if (type.keyword && prevType === types.dot)\n { this.exprAllowed = false; }\n else if (update = type.updateContext)\n { update.call(this, prevType); }\n else\n { this.exprAllowed = type.beforeExpr; }\n};\n\n// Token-specific context update code\n\ntypes.parenR.updateContext = types.braceR.updateContext = function() {\n if (this.context.length === 1) {\n this.exprAllowed = true;\n return\n }\n var out = this.context.pop();\n if (out === types$1.b_stat && this.curContext().token === \"function\") {\n out = this.context.pop();\n }\n this.exprAllowed = !out.isExpr;\n};\n\ntypes.braceL.updateContext = function(prevType) {\n this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);\n this.exprAllowed = true;\n};\n\ntypes.dollarBraceL.updateContext = function() {\n this.context.push(types$1.b_tmpl);\n this.exprAllowed = true;\n};\n\ntypes.parenL.updateContext = function(prevType) {\n var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;\n this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);\n this.exprAllowed = true;\n};\n\ntypes.incDec.updateContext = function() {\n // tokExprAllowed stays unchanged\n};\n\ntypes._function.updateContext = types._class.updateContext = function(prevType) {\n if (prevType.beforeExpr && prevType !== types._else &&\n !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&\n !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&\n !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))\n { this.context.push(types$1.f_expr); }\n else\n { this.context.push(types$1.f_stat); }\n this.exprAllowed = false;\n};\n\ntypes.backQuote.updateContext = function() {\n if (this.curContext() === types$1.q_tmpl)\n { this.context.pop(); }\n else\n { this.context.push(types$1.q_tmpl); }\n this.exprAllowed = false;\n};\n\ntypes.star.updateContext = function(prevType) {\n if (prevType === types._function) {\n var index = this.context.length - 1;\n if (this.context[index] === types$1.f_expr)\n { this.context[index] = types$1.f_expr_gen; }\n else\n { this.context[index] = types$1.f_gen; }\n }\n this.exprAllowed = true;\n};\n\ntypes.name.updateContext = function(prevType) {\n var allowed = false;\n if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {\n if (this.value === \"of\" && !this.exprAllowed ||\n this.value === \"yield\" && this.inGeneratorContext())\n { allowed = true; }\n }\n this.exprAllowed = allowed;\n};\n\n// This file contains Unicode properties extracted from the ECMAScript\n// specification. The lists are extracted like so:\n// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)\n\n// #table-binary-unicode-properties\nvar ecma9BinaryProperties = \"ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS\";\nvar ecma10BinaryProperties = ecma9BinaryProperties + \" Extended_Pictographic\";\nvar ecma11BinaryProperties = ecma10BinaryProperties;\nvar ecma12BinaryProperties = ecma11BinaryProperties + \" EBase EComp EMod EPres ExtPict\";\nvar unicodeBinaryProperties = {\n 9: ecma9BinaryProperties,\n 10: ecma10BinaryProperties,\n 11: ecma11BinaryProperties,\n 12: ecma12BinaryProperties\n};\n\n// #table-unicode-general-category-values\nvar unicodeGeneralCategoryValues = \"Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu\";\n\n// #table-unicode-script-values\nvar ecma9ScriptValues = \"Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb\";\nvar ecma10ScriptValues = ecma9ScriptValues + \" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd\";\nvar ecma11ScriptValues = ecma10ScriptValues + \" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho\";\nvar ecma12ScriptValues = ecma11ScriptValues + \" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi\";\nvar unicodeScriptValues = {\n 9: ecma9ScriptValues,\n 10: ecma10ScriptValues,\n 11: ecma11ScriptValues,\n 12: ecma12ScriptValues\n};\n\nvar data = {};\nfunction buildUnicodeData(ecmaVersion) {\n var d = data[ecmaVersion] = {\n binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + \" \" + unicodeGeneralCategoryValues),\n nonBinary: {\n General_Category: wordsRegexp(unicodeGeneralCategoryValues),\n Script: wordsRegexp(unicodeScriptValues[ecmaVersion])\n }\n };\n d.nonBinary.Script_Extensions = d.nonBinary.Script;\n\n d.nonBinary.gc = d.nonBinary.General_Category;\n d.nonBinary.sc = d.nonBinary.Script;\n d.nonBinary.scx = d.nonBinary.Script_Extensions;\n}\nbuildUnicodeData(9);\nbuildUnicodeData(10);\nbuildUnicodeData(11);\nbuildUnicodeData(12);\n\nvar pp$8 = Parser.prototype;\n\nvar RegExpValidationState = function RegExpValidationState(parser) {\n this.parser = parser;\n this.validFlags = \"gim\" + (parser.options.ecmaVersion >= 6 ? \"uy\" : \"\") + (parser.options.ecmaVersion >= 9 ? \"s\" : \"\") + (parser.options.ecmaVersion >= 13 ? \"d\" : \"\");\n this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];\n this.source = \"\";\n this.flags = \"\";\n this.start = 0;\n this.switchU = false;\n this.switchN = false;\n this.pos = 0;\n this.lastIntValue = 0;\n this.lastStringValue = \"\";\n this.lastAssertionIsQuantifiable = false;\n this.numCapturingParens = 0;\n this.maxBackReference = 0;\n this.groupNames = [];\n this.backReferenceNames = [];\n};\n\nRegExpValidationState.prototype.reset = function reset (start, pattern, flags) {\n var unicode = flags.indexOf(\"u\") !== -1;\n this.start = start | 0;\n this.source = pattern + \"\";\n this.flags = flags;\n this.switchU = unicode && this.parser.options.ecmaVersion >= 6;\n this.switchN = unicode && this.parser.options.ecmaVersion >= 9;\n};\n\nRegExpValidationState.prototype.raise = function raise (message) {\n this.parser.raiseRecoverable(this.start, (\"Invalid regular expression: /\" + (this.source) + \"/: \" + message));\n};\n\n// If u flag is given, this returns the code point at the index (it combines a surrogate pair).\n// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).\nRegExpValidationState.prototype.at = function at (i, forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n var s = this.source;\n var l = s.length;\n if (i >= l) {\n return -1\n }\n var c = s.charCodeAt(i);\n if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {\n return c\n }\n var next = s.charCodeAt(i + 1);\n return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c\n};\n\nRegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n var s = this.source;\n var l = s.length;\n if (i >= l) {\n return l\n }\n var c = s.charCodeAt(i), next;\n if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||\n (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {\n return i + 1\n }\n return i + 2\n};\n\nRegExpValidationState.prototype.current = function current (forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n return this.at(this.pos, forceU)\n};\n\nRegExpValidationState.prototype.lookahead = function lookahead (forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n return this.at(this.nextIndex(this.pos, forceU), forceU)\n};\n\nRegExpValidationState.prototype.advance = function advance (forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n this.pos = this.nextIndex(this.pos, forceU);\n};\n\nRegExpValidationState.prototype.eat = function eat (ch, forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n if (this.current(forceU) === ch) {\n this.advance(forceU);\n return true\n }\n return false\n};\n\nfunction codePointToString(ch) {\n if (ch <= 0xFFFF) { return String.fromCharCode(ch) }\n ch -= 0x10000;\n return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)\n}\n\n/**\n * Validate the flags part of a given RegExpLiteral.\n *\n * @param {RegExpValidationState} state The state to validate RegExp.\n * @returns {void}\n */\npp$8.validateRegExpFlags = function(state) {\n var validFlags = state.validFlags;\n var flags = state.flags;\n\n for (var i = 0; i < flags.length; i++) {\n var flag = flags.charAt(i);\n if (validFlags.indexOf(flag) === -1) {\n this.raise(state.start, \"Invalid regular expression flag\");\n }\n if (flags.indexOf(flag, i + 1) > -1) {\n this.raise(state.start, \"Duplicate regular expression flag\");\n }\n }\n};\n\n/**\n * Validate the pattern part of a given RegExpLiteral.\n *\n * @param {RegExpValidationState} state The state to validate RegExp.\n * @returns {void}\n */\npp$8.validateRegExpPattern = function(state) {\n this.regexp_pattern(state);\n\n // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of\n // parsing contains a |GroupName|, reparse with the goal symbol\n // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*\n // exception if _P_ did not conform to the grammar, if any elements of _P_\n // were not matched by the parse, or if any Early Error conditions exist.\n if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {\n state.switchN = true;\n this.regexp_pattern(state);\n }\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern\npp$8.regexp_pattern = function(state) {\n state.pos = 0;\n state.lastIntValue = 0;\n state.lastStringValue = \"\";\n state.lastAssertionIsQuantifiable = false;\n state.numCapturingParens = 0;\n state.maxBackReference = 0;\n state.groupNames.length = 0;\n state.backReferenceNames.length = 0;\n\n this.regexp_disjunction(state);\n\n if (state.pos !== state.source.length) {\n // Make the same messages as V8.\n if (state.eat(0x29 /* ) */)) {\n state.raise(\"Unmatched ')'\");\n }\n if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {\n state.raise(\"Lone quantifier brackets\");\n }\n }\n if (state.maxBackReference > state.numCapturingParens) {\n state.raise(\"Invalid escape\");\n }\n for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {\n var name = list[i];\n\n if (state.groupNames.indexOf(name) === -1) {\n state.raise(\"Invalid named capture referenced\");\n }\n }\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction\npp$8.regexp_disjunction = function(state) {\n this.regexp_alternative(state);\n while (state.eat(0x7C /* | */)) {\n this.regexp_alternative(state);\n }\n\n // Make the same message as V8.\n if (this.regexp_eatQuantifier(state, true)) {\n state.raise(\"Nothing to repeat\");\n }\n if (state.eat(0x7B /* { */)) {\n state.raise(\"Lone quantifier brackets\");\n }\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative\npp$8.regexp_alternative = function(state) {\n while (state.pos < state.source.length && this.regexp_eatTerm(state))\n { }\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term\npp$8.regexp_eatTerm = function(state) {\n if (this.regexp_eatAssertion(state)) {\n // Handle `QuantifiableAssertion Quantifier` alternative.\n // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion\n // is a QuantifiableAssertion.\n if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {\n // Make the same message as V8.\n if (state.switchU) {\n state.raise(\"Invalid quantifier\");\n }\n }\n return true\n }\n\n if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {\n this.regexp_eatQuantifier(state);\n return true\n }\n\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion\npp$8.regexp_eatAssertion = function(state) {\n var start = state.pos;\n state.lastAssertionIsQuantifiable = false;\n\n // ^, $\n if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {\n return true\n }\n\n // \\b \\B\n if (state.eat(0x5C /* \\ */)) {\n if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {\n return true\n }\n state.pos = start;\n }\n\n // Lookahead / Lookbehind\n if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {\n var lookbehind = false;\n if (this.options.ecmaVersion >= 9) {\n lookbehind = state.eat(0x3C /* < */);\n }\n if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {\n this.regexp_disjunction(state);\n if (!state.eat(0x29 /* ) */)) {\n state.raise(\"Unterminated group\");\n }\n state.lastAssertionIsQuantifiable = !lookbehind;\n return true\n }\n }\n\n state.pos = start;\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier\npp$8.regexp_eatQuantifier = function(state, noError) {\n if ( noError === void 0 ) noError = false;\n\n if (this.regexp_eatQuantifierPrefix(state, noError)) {\n state.eat(0x3F /* ? */);\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix\npp$8.regexp_eatQuantifierPrefix = function(state, noError) {\n return (\n state.eat(0x2A /* * */) ||\n state.eat(0x2B /* + */) ||\n state.eat(0x3F /* ? */) ||\n this.regexp_eatBracedQuantifier(state, noError)\n )\n};\npp$8.regexp_eatBracedQuantifier = function(state, noError) {\n var start = state.pos;\n if (state.eat(0x7B /* { */)) {\n var min = 0, max = -1;\n if (this.regexp_eatDecimalDigits(state)) {\n min = state.lastIntValue;\n if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {\n max = state.lastIntValue;\n }\n if (state.eat(0x7D /* } */)) {\n // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term\n if (max !== -1 && max < min && !noError) {\n state.raise(\"numbers out of order in {} quantifier\");\n }\n return true\n }\n }\n if (state.switchU && !noError) {\n state.raise(\"Incomplete quantifier\");\n }\n state.pos = start;\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom\npp$8.regexp_eatAtom = function(state) {\n return (\n this.regexp_eatPatternCharacters(state) ||\n state.eat(0x2E /* . */) ||\n this.regexp_eatReverseSolidusAtomEscape(state) ||\n this.regexp_eatCharacterClass(state) ||\n this.regexp_eatUncapturingGroup(state) ||\n this.regexp_eatCapturingGroup(state)\n )\n};\npp$8.regexp_eatReverseSolidusAtomEscape = function(state) {\n var start = state.pos;\n if (state.eat(0x5C /* \\ */)) {\n if (this.regexp_eatAtomEscape(state)) {\n return true\n }\n state.pos = start;\n }\n return false\n};\npp$8.regexp_eatUncapturingGroup = function(state) {\n var start = state.pos;\n if (state.eat(0x28 /* ( */)) {\n if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {\n this.regexp_disjunction(state);\n if (state.eat(0x29 /* ) */)) {\n return true\n }\n state.raise(\"Unterminated group\");\n }\n state.pos = start;\n }\n return false\n};\npp$8.regexp_eatCapturingGroup = function(state) {\n if (state.eat(0x28 /* ( */)) {\n if (this.options.ecmaVersion >= 9) {\n this.regexp_groupSpecifier(state);\n } else if (state.current() === 0x3F /* ? */) {\n state.raise(\"Invalid group\");\n }\n this.regexp_disjunction(state);\n if (state.eat(0x29 /* ) */)) {\n state.numCapturingParens += 1;\n return true\n }\n state.raise(\"Unterminated group\");\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom\npp$8.regexp_eatExtendedAtom = function(state) {\n return (\n state.eat(0x2E /* . */) ||\n this.regexp_eatReverseSolidusAtomEscape(state) ||\n this.regexp_eatCharacterClass(state) ||\n this.regexp_eatUncapturingGroup(state) ||\n this.regexp_eatCapturingGroup(state) ||\n this.regexp_eatInvalidBracedQuantifier(state) ||\n this.regexp_eatExtendedPatternCharacter(state)\n )\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier\npp$8.regexp_eatInvalidBracedQuantifier = function(state) {\n if (this.regexp_eatBracedQuantifier(state, true)) {\n state.raise(\"Nothing to repeat\");\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter\npp$8.regexp_eatSyntaxCharacter = function(state) {\n var ch = state.current();\n if (isSyntaxCharacter(ch)) {\n state.lastIntValue = ch;\n state.advance();\n return true\n }\n return false\n};\nfunction isSyntaxCharacter(ch) {\n return (\n ch === 0x24 /* $ */ ||\n ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||\n ch === 0x2E /* . */ ||\n ch === 0x3F /* ? */ ||\n ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||\n ch >= 0x7B /* { */ && ch <= 0x7D /* } */\n )\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter\n// But eat eager.\npp$8.regexp_eatPatternCharacters = function(state) {\n var start = state.pos;\n var ch = 0;\n while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {\n state.advance();\n }\n return state.pos !== start\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter\npp$8.regexp_eatExtendedPatternCharacter = function(state) {\n var ch = state.current();\n if (\n ch !== -1 &&\n ch !== 0x24 /* $ */ &&\n !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&\n ch !== 0x2E /* . */ &&\n ch !== 0x3F /* ? */ &&\n ch !== 0x5B /* [ */ &&\n ch !== 0x5E /* ^ */ &&\n ch !== 0x7C /* | */\n ) {\n state.advance();\n return true\n }\n return false\n};\n\n// GroupSpecifier ::\n// [empty]\n// `?` GroupName\npp$8.regexp_groupSpecifier = function(state) {\n if (state.eat(0x3F /* ? */)) {\n if (this.regexp_eatGroupName(state)) {\n if (state.groupNames.indexOf(state.lastStringValue) !== -1) {\n state.raise(\"Duplicate capture group name\");\n }\n state.groupNames.push(state.lastStringValue);\n return\n }\n state.raise(\"Invalid group\");\n }\n};\n\n// GroupName ::\n// `<` RegExpIdentifierName `>`\n// Note: this updates `state.lastStringValue` property with the eaten name.\npp$8.regexp_eatGroupName = function(state) {\n state.lastStringValue = \"\";\n if (state.eat(0x3C /* < */)) {\n if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {\n return true\n }\n state.raise(\"Invalid capture group name\");\n }\n return false\n};\n\n// RegExpIdentifierName ::\n// RegExpIdentifierStart\n// RegExpIdentifierName RegExpIdentifierPart\n// Note: this updates `state.lastStringValue` property with the eaten name.\npp$8.regexp_eatRegExpIdentifierName = function(state) {\n state.lastStringValue = \"\";\n if (this.regexp_eatRegExpIdentifierStart(state)) {\n state.lastStringValue += codePointToString(state.lastIntValue);\n while (this.regexp_eatRegExpIdentifierPart(state)) {\n state.lastStringValue += codePointToString(state.lastIntValue);\n }\n return true\n }\n return false\n};\n\n// RegExpIdentifierStart ::\n// UnicodeIDStart\n// `$`\n// `_`\n// `\\` RegExpUnicodeEscapeSequence[+U]\npp$8.regexp_eatRegExpIdentifierStart = function(state) {\n var start = state.pos;\n var forceU = this.options.ecmaVersion >= 11;\n var ch = state.current(forceU);\n state.advance(forceU);\n\n if (ch === 0x5C /* \\ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {\n ch = state.lastIntValue;\n }\n if (isRegExpIdentifierStart(ch)) {\n state.lastIntValue = ch;\n return true\n }\n\n state.pos = start;\n return false\n};\nfunction isRegExpIdentifierStart(ch) {\n return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */\n}\n\n// RegExpIdentifierPart ::\n// UnicodeIDContinue\n// `$`\n// `_`\n// `\\` RegExpUnicodeEscapeSequence[+U]\n// \n// \npp$8.regexp_eatRegExpIdentifierPart = function(state) {\n var start = state.pos;\n var forceU = this.options.ecmaVersion >= 11;\n var ch = state.current(forceU);\n state.advance(forceU);\n\n if (ch === 0x5C /* \\ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {\n ch = state.lastIntValue;\n }\n if (isRegExpIdentifierPart(ch)) {\n state.lastIntValue = ch;\n return true\n }\n\n state.pos = start;\n return false\n};\nfunction isRegExpIdentifierPart(ch) {\n return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape\npp$8.regexp_eatAtomEscape = function(state) {\n if (\n this.regexp_eatBackReference(state) ||\n this.regexp_eatCharacterClassEscape(state) ||\n this.regexp_eatCharacterEscape(state) ||\n (state.switchN && this.regexp_eatKGroupName(state))\n ) {\n return true\n }\n if (state.switchU) {\n // Make the same message as V8.\n if (state.current() === 0x63 /* c */) {\n state.raise(\"Invalid unicode escape\");\n }\n state.raise(\"Invalid escape\");\n }\n return false\n};\npp$8.regexp_eatBackReference = function(state) {\n var start = state.pos;\n if (this.regexp_eatDecimalEscape(state)) {\n var n = state.lastIntValue;\n if (state.switchU) {\n // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape\n if (n > state.maxBackReference) {\n state.maxBackReference = n;\n }\n return true\n }\n if (n <= state.numCapturingParens) {\n return true\n }\n state.pos = start;\n }\n return false\n};\npp$8.regexp_eatKGroupName = function(state) {\n if (state.eat(0x6B /* k */)) {\n if (this.regexp_eatGroupName(state)) {\n state.backReferenceNames.push(state.lastStringValue);\n return true\n }\n state.raise(\"Invalid named reference\");\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape\npp$8.regexp_eatCharacterEscape = function(state) {\n return (\n this.regexp_eatControlEscape(state) ||\n this.regexp_eatCControlLetter(state) ||\n this.regexp_eatZero(state) ||\n this.regexp_eatHexEscapeSequence(state) ||\n this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||\n (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||\n this.regexp_eatIdentityEscape(state)\n )\n};\npp$8.regexp_eatCControlLetter = function(state) {\n var start = state.pos;\n if (state.eat(0x63 /* c */)) {\n if (this.regexp_eatControlLetter(state)) {\n return true\n }\n state.pos = start;\n }\n return false\n};\npp$8.regexp_eatZero = function(state) {\n if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {\n state.lastIntValue = 0;\n state.advance();\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape\npp$8.regexp_eatControlEscape = function(state) {\n var ch = state.current();\n if (ch === 0x74 /* t */) {\n state.lastIntValue = 0x09; /* \\t */\n state.advance();\n return true\n }\n if (ch === 0x6E /* n */) {\n state.lastIntValue = 0x0A; /* \\n */\n state.advance();\n return true\n }\n if (ch === 0x76 /* v */) {\n state.lastIntValue = 0x0B; /* \\v */\n state.advance();\n return true\n }\n if (ch === 0x66 /* f */) {\n state.lastIntValue = 0x0C; /* \\f */\n state.advance();\n return true\n }\n if (ch === 0x72 /* r */) {\n state.lastIntValue = 0x0D; /* \\r */\n state.advance();\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter\npp$8.regexp_eatControlLetter = function(state) {\n var ch = state.current();\n if (isControlLetter(ch)) {\n state.lastIntValue = ch % 0x20;\n state.advance();\n return true\n }\n return false\n};\nfunction isControlLetter(ch) {\n return (\n (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||\n (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)\n )\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence\npp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {\n if ( forceU === void 0 ) forceU = false;\n\n var start = state.pos;\n var switchU = forceU || state.switchU;\n\n if (state.eat(0x75 /* u */)) {\n if (this.regexp_eatFixedHexDigits(state, 4)) {\n var lead = state.lastIntValue;\n if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {\n var leadSurrogateEnd = state.pos;\n if (state.eat(0x5C /* \\ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {\n var trail = state.lastIntValue;\n if (trail >= 0xDC00 && trail <= 0xDFFF) {\n state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;\n return true\n }\n }\n state.pos = leadSurrogateEnd;\n state.lastIntValue = lead;\n }\n return true\n }\n if (\n switchU &&\n state.eat(0x7B /* { */) &&\n this.regexp_eatHexDigits(state) &&\n state.eat(0x7D /* } */) &&\n isValidUnicode(state.lastIntValue)\n ) {\n return true\n }\n if (switchU) {\n state.raise(\"Invalid unicode escape\");\n }\n state.pos = start;\n }\n\n return false\n};\nfunction isValidUnicode(ch) {\n return ch >= 0 && ch <= 0x10FFFF\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape\npp$8.regexp_eatIdentityEscape = function(state) {\n if (state.switchU) {\n if (this.regexp_eatSyntaxCharacter(state)) {\n return true\n }\n if (state.eat(0x2F /* / */)) {\n state.lastIntValue = 0x2F; /* / */\n return true\n }\n return false\n }\n\n var ch = state.current();\n if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {\n state.lastIntValue = ch;\n state.advance();\n return true\n }\n\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape\npp$8.regexp_eatDecimalEscape = function(state) {\n state.lastIntValue = 0;\n var ch = state.current();\n if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {\n do {\n state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);\n state.advance();\n } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape\npp$8.regexp_eatCharacterClassEscape = function(state) {\n var ch = state.current();\n\n if (isCharacterClassEscape(ch)) {\n state.lastIntValue = -1;\n state.advance();\n return true\n }\n\n if (\n state.switchU &&\n this.options.ecmaVersion >= 9 &&\n (ch === 0x50 /* P */ || ch === 0x70 /* p */)\n ) {\n state.lastIntValue = -1;\n state.advance();\n if (\n state.eat(0x7B /* { */) &&\n this.regexp_eatUnicodePropertyValueExpression(state) &&\n state.eat(0x7D /* } */)\n ) {\n return true\n }\n state.raise(\"Invalid property name\");\n }\n\n return false\n};\nfunction isCharacterClassEscape(ch) {\n return (\n ch === 0x64 /* d */ ||\n ch === 0x44 /* D */ ||\n ch === 0x73 /* s */ ||\n ch === 0x53 /* S */ ||\n ch === 0x77 /* w */ ||\n ch === 0x57 /* W */\n )\n}\n\n// UnicodePropertyValueExpression ::\n// UnicodePropertyName `=` UnicodePropertyValue\n// LoneUnicodePropertyNameOrValue\npp$8.regexp_eatUnicodePropertyValueExpression = function(state) {\n var start = state.pos;\n\n // UnicodePropertyName `=` UnicodePropertyValue\n if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {\n var name = state.lastStringValue;\n if (this.regexp_eatUnicodePropertyValue(state)) {\n var value = state.lastStringValue;\n this.regexp_validateUnicodePropertyNameAndValue(state, name, value);\n return true\n }\n }\n state.pos = start;\n\n // LoneUnicodePropertyNameOrValue\n if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {\n var nameOrValue = state.lastStringValue;\n this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);\n return true\n }\n return false\n};\npp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {\n if (!has(state.unicodeProperties.nonBinary, name))\n { state.raise(\"Invalid property name\"); }\n if (!state.unicodeProperties.nonBinary[name].test(value))\n { state.raise(\"Invalid property value\"); }\n};\npp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {\n if (!state.unicodeProperties.binary.test(nameOrValue))\n { state.raise(\"Invalid property name\"); }\n};\n\n// UnicodePropertyName ::\n// UnicodePropertyNameCharacters\npp$8.regexp_eatUnicodePropertyName = function(state) {\n var ch = 0;\n state.lastStringValue = \"\";\n while (isUnicodePropertyNameCharacter(ch = state.current())) {\n state.lastStringValue += codePointToString(ch);\n state.advance();\n }\n return state.lastStringValue !== \"\"\n};\nfunction isUnicodePropertyNameCharacter(ch) {\n return isControlLetter(ch) || ch === 0x5F /* _ */\n}\n\n// UnicodePropertyValue ::\n// UnicodePropertyValueCharacters\npp$8.regexp_eatUnicodePropertyValue = function(state) {\n var ch = 0;\n state.lastStringValue = \"\";\n while (isUnicodePropertyValueCharacter(ch = state.current())) {\n state.lastStringValue += codePointToString(ch);\n state.advance();\n }\n return state.lastStringValue !== \"\"\n};\nfunction isUnicodePropertyValueCharacter(ch) {\n return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)\n}\n\n// LoneUnicodePropertyNameOrValue ::\n// UnicodePropertyValueCharacters\npp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {\n return this.regexp_eatUnicodePropertyValue(state)\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass\npp$8.regexp_eatCharacterClass = function(state) {\n if (state.eat(0x5B /* [ */)) {\n state.eat(0x5E /* ^ */);\n this.regexp_classRanges(state);\n if (state.eat(0x5D /* ] */)) {\n return true\n }\n // Unreachable since it threw \"unterminated regular expression\" error before.\n state.raise(\"Unterminated character class\");\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges\n// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges\n// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash\npp$8.regexp_classRanges = function(state) {\n while (this.regexp_eatClassAtom(state)) {\n var left = state.lastIntValue;\n if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {\n var right = state.lastIntValue;\n if (state.switchU && (left === -1 || right === -1)) {\n state.raise(\"Invalid character class\");\n }\n if (left !== -1 && right !== -1 && left > right) {\n state.raise(\"Range out of order in character class\");\n }\n }\n }\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom\n// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash\npp$8.regexp_eatClassAtom = function(state) {\n var start = state.pos;\n\n if (state.eat(0x5C /* \\ */)) {\n if (this.regexp_eatClassEscape(state)) {\n return true\n }\n if (state.switchU) {\n // Make the same message as V8.\n var ch$1 = state.current();\n if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {\n state.raise(\"Invalid class escape\");\n }\n state.raise(\"Invalid escape\");\n }\n state.pos = start;\n }\n\n var ch = state.current();\n if (ch !== 0x5D /* ] */) {\n state.lastIntValue = ch;\n state.advance();\n return true\n }\n\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape\npp$8.regexp_eatClassEscape = function(state) {\n var start = state.pos;\n\n if (state.eat(0x62 /* b */)) {\n state.lastIntValue = 0x08; /* */\n return true\n }\n\n if (state.switchU && state.eat(0x2D /* - */)) {\n state.lastIntValue = 0x2D; /* - */\n return true\n }\n\n if (!state.switchU && state.eat(0x63 /* c */)) {\n if (this.regexp_eatClassControlLetter(state)) {\n return true\n }\n state.pos = start;\n }\n\n return (\n this.regexp_eatCharacterClassEscape(state) ||\n this.regexp_eatCharacterEscape(state)\n )\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter\npp$8.regexp_eatClassControlLetter = function(state) {\n var ch = state.current();\n if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {\n state.lastIntValue = ch % 0x20;\n state.advance();\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence\npp$8.regexp_eatHexEscapeSequence = function(state) {\n var start = state.pos;\n if (state.eat(0x78 /* x */)) {\n if (this.regexp_eatFixedHexDigits(state, 2)) {\n return true\n }\n if (state.switchU) {\n state.raise(\"Invalid escape\");\n }\n state.pos = start;\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits\npp$8.regexp_eatDecimalDigits = function(state) {\n var start = state.pos;\n var ch = 0;\n state.lastIntValue = 0;\n while (isDecimalDigit(ch = state.current())) {\n state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);\n state.advance();\n }\n return state.pos !== start\n};\nfunction isDecimalDigit(ch) {\n return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits\npp$8.regexp_eatHexDigits = function(state) {\n var start = state.pos;\n var ch = 0;\n state.lastIntValue = 0;\n while (isHexDigit(ch = state.current())) {\n state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);\n state.advance();\n }\n return state.pos !== start\n};\nfunction isHexDigit(ch) {\n return (\n (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||\n (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||\n (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)\n )\n}\nfunction hexToInt(ch) {\n if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {\n return 10 + (ch - 0x41 /* A */)\n }\n if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {\n return 10 + (ch - 0x61 /* a */)\n }\n return ch - 0x30 /* 0 */\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence\n// Allows only 0-377(octal) i.e. 0-255(decimal).\npp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {\n if (this.regexp_eatOctalDigit(state)) {\n var n1 = state.lastIntValue;\n if (this.regexp_eatOctalDigit(state)) {\n var n2 = state.lastIntValue;\n if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {\n state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;\n } else {\n state.lastIntValue = n1 * 8 + n2;\n }\n } else {\n state.lastIntValue = n1;\n }\n return true\n }\n return false\n};\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit\npp$8.regexp_eatOctalDigit = function(state) {\n var ch = state.current();\n if (isOctalDigit(ch)) {\n state.lastIntValue = ch - 0x30; /* 0 */\n state.advance();\n return true\n }\n state.lastIntValue = 0;\n return false\n};\nfunction isOctalDigit(ch) {\n return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */\n}\n\n// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits\n// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit\n// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence\npp$8.regexp_eatFixedHexDigits = function(state, length) {\n var start = state.pos;\n state.lastIntValue = 0;\n for (var i = 0; i < length; ++i) {\n var ch = state.current();\n if (!isHexDigit(ch)) {\n state.pos = start;\n return false\n }\n state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);\n state.advance();\n }\n return true\n};\n\n// Object type used to represent tokens. Note that normally, tokens\n// simply exist as properties on the parser object. This is only\n// used for the onToken callback and the external tokenizer.\n\nvar Token = function Token(p) {\n this.type = p.type;\n this.value = p.value;\n this.start = p.start;\n this.end = p.end;\n if (p.options.locations)\n { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }\n if (p.options.ranges)\n { this.range = [p.start, p.end]; }\n};\n\n// ## Tokenizer\n\nvar pp$9 = Parser.prototype;\n\n// Move to the next token\n\npp$9.next = function(ignoreEscapeSequenceInKeyword) {\n if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)\n { this.raiseRecoverable(this.start, \"Escape sequence in keyword \" + this.type.keyword); }\n if (this.options.onToken)\n { this.options.onToken(new Token(this)); }\n\n this.lastTokEnd = this.end;\n this.lastTokStart = this.start;\n this.lastTokEndLoc = this.endLoc;\n this.lastTokStartLoc = this.startLoc;\n this.nextToken();\n};\n\npp$9.getToken = function() {\n this.next();\n return new Token(this)\n};\n\n// If we're in an ES6 environment, make parsers iterable\nif (typeof Symbol !== \"undefined\")\n { pp$9[Symbol.iterator] = function() {\n var this$1 = this;\n\n return {\n next: function () {\n var token = this$1.getToken();\n return {\n done: token.type === types.eof,\n value: token\n }\n }\n }\n }; }\n\n// Toggle strict mode. Re-reads the next number or string to please\n// pedantic tests (`\"use strict\"; 010;` should fail).\n\npp$9.curContext = function() {\n return this.context[this.context.length - 1]\n};\n\n// Read a single token, updating the parser object's token-related\n// properties.\n\npp$9.nextToken = function() {\n var curContext = this.curContext();\n if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }\n\n this.start = this.pos;\n if (this.options.locations) { this.startLoc = this.curPosition(); }\n if (this.pos >= this.input.length) { return this.finishToken(types.eof) }\n\n if (curContext.override) { return curContext.override(this) }\n else { this.readToken(this.fullCharCodeAtPos()); }\n};\n\npp$9.readToken = function(code) {\n // Identifier or keyword. '\\uXXXX' sequences are allowed in\n // identifiers, so '\\' also dispatches to that.\n if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\\' */)\n { return this.readWord() }\n\n return this.getTokenFromCode(code)\n};\n\npp$9.fullCharCodeAtPos = function() {\n var code = this.input.charCodeAt(this.pos);\n if (code <= 0xd7ff || code >= 0xdc00) { return code }\n var next = this.input.charCodeAt(this.pos + 1);\n return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00\n};\n\npp$9.skipBlockComment = function() {\n var startLoc = this.options.onComment && this.curPosition();\n var start = this.pos, end = this.input.indexOf(\"*/\", this.pos += 2);\n if (end === -1) { this.raise(this.pos - 2, \"Unterminated comment\"); }\n this.pos = end + 2;\n if (this.options.locations) {\n lineBreakG.lastIndex = start;\n var match;\n while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {\n ++this.curLine;\n this.lineStart = match.index + match[0].length;\n }\n }\n if (this.options.onComment)\n { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,\n startLoc, this.curPosition()); }\n};\n\npp$9.skipLineComment = function(startSkip) {\n var start = this.pos;\n var startLoc = this.options.onComment && this.curPosition();\n var ch = this.input.charCodeAt(this.pos += startSkip);\n while (this.pos < this.input.length && !isNewLine(ch)) {\n ch = this.input.charCodeAt(++this.pos);\n }\n if (this.options.onComment)\n { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,\n startLoc, this.curPosition()); }\n};\n\n// Called at the start of the parse and after every token. Skips\n// whitespace and comments, and.\n\npp$9.skipSpace = function() {\n loop: while (this.pos < this.input.length) {\n var ch = this.input.charCodeAt(this.pos);\n switch (ch) {\n case 32: case 160: // ' '\n ++this.pos;\n break\n case 13:\n if (this.input.charCodeAt(this.pos + 1) === 10) {\n ++this.pos;\n }\n case 10: case 8232: case 8233:\n ++this.pos;\n if (this.options.locations) {\n ++this.curLine;\n this.lineStart = this.pos;\n }\n break\n case 47: // '/'\n switch (this.input.charCodeAt(this.pos + 1)) {\n case 42: // '*'\n this.skipBlockComment();\n break\n case 47:\n this.skipLineComment(2);\n break\n default:\n break loop\n }\n break\n default:\n if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {\n ++this.pos;\n } else {\n break loop\n }\n }\n }\n};\n\n// Called at the end of every token. Sets `end`, `val`, and\n// maintains `context` and `exprAllowed`, and skips the space after\n// the token, so that the next one's `start` will point at the\n// right position.\n\npp$9.finishToken = function(type, val) {\n this.end = this.pos;\n if (this.options.locations) { this.endLoc = this.curPosition(); }\n var prevType = this.type;\n this.type = type;\n this.value = val;\n\n this.updateContext(prevType);\n};\n\n// ### Token reading\n\n// This is the function that is called to fetch the next token. It\n// is somewhat obscure, because it works in character codes rather\n// than characters, and because operator parsing has been inlined\n// into it.\n//\n// All in the name of speed.\n//\npp$9.readToken_dot = function() {\n var next = this.input.charCodeAt(this.pos + 1);\n if (next >= 48 && next <= 57) { return this.readNumber(true) }\n var next2 = this.input.charCodeAt(this.pos + 2);\n if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'\n this.pos += 3;\n return this.finishToken(types.ellipsis)\n } else {\n ++this.pos;\n return this.finishToken(types.dot)\n }\n};\n\npp$9.readToken_slash = function() { // '/'\n var next = this.input.charCodeAt(this.pos + 1);\n if (this.exprAllowed) { ++this.pos; return this.readRegexp() }\n if (next === 61) { return this.finishOp(types.assign, 2) }\n return this.finishOp(types.slash, 1)\n};\n\npp$9.readToken_mult_modulo_exp = function(code) { // '%*'\n var next = this.input.charCodeAt(this.pos + 1);\n var size = 1;\n var tokentype = code === 42 ? types.star : types.modulo;\n\n // exponentiation operator ** and **=\n if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {\n ++size;\n tokentype = types.starstar;\n next = this.input.charCodeAt(this.pos + 2);\n }\n\n if (next === 61) { return this.finishOp(types.assign, size + 1) }\n return this.finishOp(tokentype, size)\n};\n\npp$9.readToken_pipe_amp = function(code) { // '|&'\n var next = this.input.charCodeAt(this.pos + 1);\n if (next === code) {\n if (this.options.ecmaVersion >= 12) {\n var next2 = this.input.charCodeAt(this.pos + 2);\n if (next2 === 61) { return this.finishOp(types.assign, 3) }\n }\n return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)\n }\n if (next === 61) { return this.finishOp(types.assign, 2) }\n return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)\n};\n\npp$9.readToken_caret = function() { // '^'\n var next = this.input.charCodeAt(this.pos + 1);\n if (next === 61) { return this.finishOp(types.assign, 2) }\n return this.finishOp(types.bitwiseXOR, 1)\n};\n\npp$9.readToken_plus_min = function(code) { // '+-'\n var next = this.input.charCodeAt(this.pos + 1);\n if (next === code) {\n if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&\n (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {\n // A `-->` line comment\n this.skipLineComment(3);\n this.skipSpace();\n return this.nextToken()\n }\n return this.finishOp(types.incDec, 2)\n }\n if (next === 61) { return this.finishOp(types.assign, 2) }\n return this.finishOp(types.plusMin, 1)\n};\n\npp$9.readToken_lt_gt = function(code) { // '<>'\n var next = this.input.charCodeAt(this.pos + 1);\n var size = 1;\n if (next === code) {\n size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;\n if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }\n return this.finishOp(types.bitShift, size)\n }\n if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&\n this.input.charCodeAt(this.pos + 3) === 45) {\n // `/\nconst srcRE = /\\bsrc\\s*=\\s*(?:\"([^\"]+)\"|'([^']+)'|([^\\s'\">]+))/im\nconst typeRE = /\\btype\\s*=\\s*(?:\"([^\"]+)\"|'([^']+)'|([^\\s'\">]+))/im\nconst langRE = /\\blang\\s*=\\s*(?:\"([^\"]+)\"|'([^']+)'|([^\\s'\">]+))/im\n\nfunction esbuildScanPlugin(\n config: ResolvedConfig,\n container: PluginContainer,\n depImports: Record,\n missing: Record,\n entries: string[]\n): Plugin {\n const seen = new Map()\n\n const resolve = async (id: string, importer?: string) => {\n const key = id + (importer && path.dirname(importer))\n if (seen.has(key)) {\n return seen.get(key)\n }\n const resolved = await container.resolveId(\n id,\n importer && normalizePath(importer)\n )\n const res = resolved?.id\n seen.set(key, res)\n return res\n }\n\n const include = config.optimizeDeps?.include\n const exclude = [\n ...(config.optimizeDeps?.exclude || []),\n '@vite/client',\n '@vite/env'\n ]\n\n const externalUnlessEntry = ({ path }: { path: string }) => ({\n path,\n external: !entries.includes(path)\n })\n\n return {\n name: 'vite:dep-scan',\n setup(build) {\n // external urls\n build.onResolve({ filter: externalRE }, ({ path }) => ({\n path,\n external: true\n }))\n\n // data urls\n build.onResolve({ filter: dataUrlRE }, ({ path }) => ({\n path,\n external: true\n }))\n\n // html types: extract script contents -----------------------------------\n build.onResolve({ filter: htmlTypesRE }, async ({ path, importer }) => {\n return {\n path: await resolve(path, importer),\n namespace: 'html'\n }\n })\n\n // extract scripts inside HTML-like files and treat it as a js module\n build.onLoad(\n { filter: htmlTypesRE, namespace: 'html' },\n async ({ path }) => {\n let raw = fs.readFileSync(path, 'utf-8')\n // Avoid matching the content of the comment\n raw = raw.replace(commentRE, '')\n const isHtml = path.endsWith('.html')\n const regex = isHtml ? scriptModuleRE : scriptRE\n regex.lastIndex = 0\n let js = ''\n let loader: Loader = 'js'\n let match: RegExpExecArray | null\n while ((match = regex.exec(raw))) {\n const [, openTag, content] = match\n const srcMatch = openTag.match(srcRE)\n const typeMatch = openTag.match(typeRE)\n const langMatch = openTag.match(langRE)\n const type =\n typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3])\n const lang =\n langMatch && (langMatch[1] || langMatch[2] || langMatch[3])\n // skip type=\"application/ld+json\" and other non-JS types\n if (\n type &&\n !(\n type.includes('javascript') ||\n type.includes('ecmascript') ||\n type === 'module'\n )\n ) {\n continue\n }\n if (lang === 'ts' || lang === 'tsx' || lang === 'jsx') {\n loader = lang\n }\n if (srcMatch) {\n const src = srcMatch[1] || srcMatch[2] || srcMatch[3]\n js += `import ${JSON.stringify(src)}\\n`\n } else if (content.trim()) {\n js += content + '\\n'\n }\n }\n // empty singleline & multiline comments to avoid matching comments\n const code = js\n .replace(multilineCommentsRE, '/* */')\n .replace(singlelineCommentsRE, '')\n\n if (\n loader.startsWith('ts') &&\n (path.endsWith('.svelte') ||\n (path.endsWith('.vue') && /) or Svelte, imports may seem\n // unused to esbuild and dropped in the build output, which prevents\n // esbuild from crawling further.\n // the solution is to add `import 'x'` for every source to force\n // esbuild to keep crawling due to potential side effects.\n let m\n while ((m = importsRE.exec(code)) != null) {\n // This is necessary to avoid infinite loops with zero-width matches\n if (m.index === importsRE.lastIndex) {\n importsRE.lastIndex++\n }\n js += `\\nimport ${m[1]}`\n }\n }\n\n if (!code.includes(`export default`)) {\n js += `\\nexport default {}`\n }\n\n if (code.includes('import.meta.glob')) {\n return {\n // transformGlob already transforms to js\n loader: 'js',\n contents: await transformGlob(js, path, config.root, loader)\n }\n }\n\n return {\n loader,\n contents: js\n }\n }\n )\n\n // bare imports: record and externalize ----------------------------------\n build.onResolve(\n {\n // avoid matching windows volume\n filter: /^[\\w@][^:]/\n },\n async ({ path: id, importer }) => {\n if (exclude?.some((e) => e === id || id.startsWith(e + '/'))) {\n return externalUnlessEntry({ path: id })\n }\n if (depImports[id]) {\n return externalUnlessEntry({ path: id })\n }\n const resolved = await resolve(id, importer)\n if (resolved) {\n if (shouldExternalizeDep(resolved, id)) {\n return externalUnlessEntry({ path: id })\n }\n if (resolved.includes('node_modules') || include?.includes(id)) {\n // dependency or forced included, externalize and stop crawling\n if (OPTIMIZABLE_ENTRY_RE.test(resolved)) {\n depImports[id] = resolved\n }\n return externalUnlessEntry({ path: id })\n } else {\n const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined\n // linked package, keep crawling\n return {\n path: path.resolve(resolved),\n namespace\n }\n }\n } else {\n missing[id] = normalizePath(importer)\n }\n }\n )\n\n // Externalized file types -----------------------------------------------\n // these are done on raw ids using esbuild's native regex filter so it\n // should be faster than doing it in the catch-all via js\n // they are done after the bare import resolve because a package name\n // may end with these extensions\n\n // css & json\n build.onResolve(\n {\n filter: /\\.(css|less|sass|scss|styl|stylus|pcss|postcss|json)$/\n },\n externalUnlessEntry\n )\n\n // known asset types\n build.onResolve(\n {\n filter: new RegExp(`\\\\.(${KNOWN_ASSET_TYPES.join('|')})$`)\n },\n externalUnlessEntry\n )\n\n // known vite query types: ?worker, ?raw\n build.onResolve({ filter: SPECIAL_QUERY_RE }, ({ path }) => ({\n path,\n external: true\n }))\n\n // catch all -------------------------------------------------------------\n\n build.onResolve(\n {\n filter: /.*/\n },\n async ({ path: id, importer }) => {\n // use vite resolver to support urls and omitted extensions\n const resolved = await resolve(id, importer)\n if (resolved) {\n if (shouldExternalizeDep(resolved, id)) {\n return externalUnlessEntry({ path: id })\n }\n\n const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined\n\n return {\n path: path.resolve(cleanUrl(resolved)),\n namespace\n }\n } else {\n // resolve failed... probably unsupported type\n return externalUnlessEntry({ path: id })\n }\n }\n )\n\n // for jsx/tsx, we need to access the content and check for\n // presence of import.meta.glob, since it results in import relationships\n // but isn't crawled by esbuild.\n build.onLoad({ filter: JS_TYPES_RE }, ({ path: id }) => {\n let ext = path.extname(id).slice(1)\n if (ext === 'mjs') ext = 'js'\n\n let contents = fs.readFileSync(id, 'utf-8')\n if (ext.endsWith('x') && config.esbuild && config.esbuild.jsxInject) {\n contents = config.esbuild.jsxInject + `\\n` + contents\n }\n\n if (contents.includes('import.meta.glob')) {\n return transformGlob(contents, id, config.root, ext as Loader).then(\n (contents) => ({\n loader: ext as Loader,\n contents\n })\n )\n }\n return {\n loader: ext as Loader,\n contents\n }\n })\n }\n }\n}\n\nasync function transformGlob(\n source: string,\n importer: string,\n root: string,\n loader: Loader\n) {\n // transform the content first since es-module-lexer can't handle non-js\n if (loader !== 'js') {\n source = (await transform(source, { loader })).code\n }\n\n await init\n const imports = parse(source)[0]\n const s = new MagicString(source)\n for (let index = 0; index < imports.length; index++) {\n const { s: start, e: end, ss: expStart } = imports[index]\n const url = source.slice(start, end)\n if (url !== 'import.meta') continue\n if (source.slice(end, end + 5) !== '.glob') continue\n const { importsString, exp, endIndex } = await transformImportGlob(\n source,\n start,\n normalizePath(importer),\n index,\n root\n )\n s.prepend(importsString)\n s.overwrite(expStart, endIndex, exp)\n }\n return s.toString()\n}\n\nexport function shouldExternalizeDep(\n resolvedId: string,\n rawId: string\n): boolean {\n // not a valid file path\n if (!path.isAbsolute(resolvedId)) {\n return true\n }\n // virtual id\n if (resolvedId === rawId || resolvedId.includes('\\0')) {\n return true\n }\n // resolved is not a scannable type\n if (!JS_TYPES_RE.test(resolvedId) && !htmlTypesRE.test(resolvedId)) {\n return true\n }\n return false\n}\n","import { Plugin } from '../plugin'\nimport MagicString from 'magic-string'\nimport path from 'path'\nimport { fileToUrl } from './asset'\nimport { ResolvedConfig } from '../config'\nimport { multilineCommentsRE, singlelineCommentsRE } from '../utils'\n\n/**\n * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL\n *\n * Supports tempalte string with dynamic segments:\n * ```\n * new URL(`./dir/${name}.png`, import.meta.url)\n * // transformed to\n * import.meta.globEager('./dir/**.png')[`./dir/${name}.png`].default\n * ```\n */\nexport function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin {\n return {\n name: 'asset-import-meta-url',\n async transform(code, id, ssr) {\n if (code.includes('new URL') && code.includes(`import.meta.url`)) {\n const importMetaUrlRE =\n /\\bnew\\s+URL\\s*\\(\\s*('[^']+'|\"[^\"]+\"|`[^`]+`)\\s*,\\s*import\\.meta\\.url\\s*\\)/g\n const noCommentsCode = code\n .replace(multilineCommentsRE, (m) => ' '.repeat(m.length))\n .replace(singlelineCommentsRE, (m) => ' '.repeat(m.length))\n let s: MagicString | null = null\n let match: RegExpExecArray | null\n while ((match = importMetaUrlRE.exec(noCommentsCode))) {\n const { 0: exp, 1: rawUrl, index } = match\n\n if (ssr) {\n this.error(\n `\\`new URL(url, import.meta.url)\\` is not supported in SSR.`,\n index\n )\n }\n\n if (!s) s = new MagicString(code)\n\n // potential dynamic template string\n if (rawUrl[0] === '`' && /\\$\\{/.test(rawUrl)) {\n const ast = this.parse(rawUrl)\n const templateLiteral = (ast as any).body[0].expression\n if (templateLiteral.expressions.length) {\n const pattern = buildGlobPattern(templateLiteral)\n // Note: native import.meta.url is not supported in the baseline\n // target so we use window.location here -\n s.overwrite(\n index,\n index + exp.length,\n `new URL(import.meta.globEagerDefault(${JSON.stringify(\n pattern\n )})[${rawUrl}], window.location)`\n )\n continue\n }\n }\n\n const url = rawUrl.slice(1, -1)\n const file = path.resolve(path.dirname(id), url)\n const builtUrl = await fileToUrl(file, config, this)\n s.overwrite(\n index,\n index + exp.length,\n `new URL(${JSON.stringify(builtUrl)}, window.location)`\n )\n }\n if (s) {\n return {\n code: s.toString(),\n map: config.build.sourcemap ? s.generateMap({ hires: true }) : null\n }\n }\n }\n return null\n }\n }\n}\n\nfunction buildGlobPattern(ast: any) {\n let pattern = ''\n let lastElementIndex = -1\n for (const exp of ast.expressions) {\n for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {\n const el = ast.quasis[i]\n if (el.end < exp.start) {\n pattern += el.value.raw\n lastElementIndex = i\n }\n }\n pattern += '**'\n }\n for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {\n pattern += ast.quasis[i].value.raw\n }\n return pattern\n}\n","import { promises as fs } from 'fs'\nimport { Plugin } from '..'\nimport { cleanUrl } from '../utils'\n\nexport function loadFallbackPlugin(): Plugin {\n return {\n name: 'load-fallback',\n async load(id) {\n try {\n return fs.readFile(cleanUrl(id), 'utf-8')\n } catch (e) {\n return fs.readFile(id, 'utf-8')\n }\n }\n }\n}\n","import fs from 'fs'\nimport path from 'path'\nimport chalk from 'chalk'\nimport { resolveConfig, InlineConfig, ResolvedConfig } from './config'\nimport Rollup, {\n Plugin,\n RollupBuild,\n RollupOptions,\n RollupWarning,\n WarningHandler,\n OutputOptions,\n RollupOutput,\n ExternalOption,\n GetManualChunk,\n GetModuleInfo,\n WatcherOptions,\n RollupWatcher,\n RollupError,\n ModuleFormat\n} from 'rollup'\nimport { buildReporterPlugin } from './plugins/reporter'\nimport { buildHtmlPlugin } from './plugins/html'\nimport { buildEsbuildPlugin } from './plugins/esbuild'\nimport { terserPlugin } from './plugins/terser'\nimport { Terser } from 'types/terser'\nimport { copyDir, emptyDir, lookupFile, normalizePath } from './utils'\nimport { manifestPlugin } from './plugins/manifest'\nimport commonjsPlugin from '@rollup/plugin-commonjs'\nimport { RollupCommonJSOptions } from 'types/commonjs'\nimport dynamicImportVars from '@rollup/plugin-dynamic-import-vars'\nimport { RollupDynamicImportVarsOptions } from 'types/dynamicImportVars'\nimport { Logger } from './logger'\nimport { TransformOptions } from 'esbuild'\nimport { dataURIPlugin } from './plugins/dataUri'\nimport { buildImportAnalysisPlugin } from './plugins/importAnalysisBuild'\nimport { resolveSSRExternal, shouldExternalizeForSSR } from './ssr/ssrExternal'\nimport { ssrManifestPlugin } from './ssr/ssrManifestPlugin'\nimport { isCSSRequest } from './plugins/css'\nimport { DepOptimizationMetadata } from './optimizer'\nimport { scanImports } from './optimizer/scan'\nimport { assetImportMetaUrlPlugin } from './plugins/assetImportMetaUrl'\nimport { loadFallbackPlugin } from './plugins/loadFallback'\n\nexport interface BuildOptions {\n /**\n * Base public path when served in production.\n * @deprecated `base` is now a root-level config option.\n */\n base?: string\n /**\n * Compatibility transform target. The transform is performed with esbuild\n * and the lowest supported target is es2015/es6. Note this only handles\n * syntax transformation and does not cover polyfills (except for dynamic\n * import)\n *\n * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,\n * transpile targeting browsers that natively support dynamic es module imports.\n * https://caniuse.com/es6-module-dynamic-import\n *\n * Another special value is 'esnext' - which only performs minimal transpiling\n * (for minification compat) and assumes native dynamic imports support.\n *\n * For custom targets, see https://esbuild.github.io/api/#target and\n * https://esbuild.github.io/content-types/#javascript for more details.\n */\n target?: 'modules' | TransformOptions['target'] | false\n /**\n * whether to inject module preload polyfill.\n * Note: does not apply to library mode.\n * @default true\n */\n polyfillModulePreload?: boolean\n /**\n * whether to inject dynamic import polyfill.\n * Note: does not apply to library mode.\n * @default false\n * @deprecated use plugin-legacy for browsers that don't support dynamic import\n */\n polyfillDynamicImport?: boolean\n /**\n * Directory relative from `root` where build output will be placed. If the\n * directory exists, it will be removed before the build.\n * @default 'dist'\n */\n outDir?: string\n /**\n * Directory relative from `outDir` where the built js/css/image assets will\n * be placed.\n * @default 'assets'\n */\n assetsDir?: string\n /**\n * Static asset files smaller than this number (in bytes) will be inlined as\n * base64 strings. Default limit is `4096` (4kb). Set to `0` to disable.\n * @default 4096\n */\n assetsInlineLimit?: number\n /**\n * Whether to code-split CSS. When enabled, CSS in async chunks will be\n * inlined as strings in the chunk and inserted via dynamically created\n * style tags when the chunk is loaded.\n * @default true\n */\n cssCodeSplit?: boolean\n /**\n * If `true`, a separate sourcemap file will be created. If 'inline', the\n * sourcemap will be appended to the resulting output file as data URI.\n * 'hidden' works like `true` except that the corresponding sourcemap\n * comments in the bundled files are suppressed.\n * @default false\n */\n sourcemap?: boolean | 'inline' | 'hidden'\n /**\n * Set to `false` to disable minification, or specify the minifier to use.\n * Available options are 'terser' or 'esbuild'.\n * @default 'terser'\n */\n minify?: boolean | 'terser' | 'esbuild'\n /**\n * Options for terser\n * https://terser.org/docs/api-reference#minify-options\n */\n terserOptions?: Terser.MinifyOptions\n /**\n * @deprecated Vite now uses esbuild for CSS minification.\n */\n cleanCssOptions?: any\n /**\n * Will be merged with internal rollup options.\n * https://rollupjs.org/guide/en/#big-list-of-options\n */\n rollupOptions?: RollupOptions\n /**\n * Options to pass on to `@rollup/plugin-commonjs`\n */\n commonjsOptions?: RollupCommonJSOptions\n /**\n * Options to pass on to `@rollup/plugin-dynamic-import-vars`\n */\n dynamicImportVarsOptions?: RollupDynamicImportVarsOptions\n /**\n * Whether to write bundle to disk\n * @default true\n */\n write?: boolean\n /**\n * Empty outDir on write.\n * @default true when outDir is a sub directory of project root\n */\n emptyOutDir?: boolean | null\n /**\n * Whether to emit a manifest.json under assets dir to map hash-less filenames\n * to their hashed versions. Useful when you want to generate your own HTML\n * instead of using the one generated by Vite.\n *\n * Example:\n *\n * ```json\n * {\n * \"main.js\": {\n * \"file\": \"main.68fe3fad.js\",\n * \"css\": \"main.e6b63442.css\",\n * \"imports\": [...],\n * \"dynamicImports\": [...]\n * }\n * }\n * ```\n * @default false\n */\n manifest?: boolean\n /**\n * Build in library mode. The value should be the global name of the lib in\n * UMD mode. This will produce esm + cjs + umd bundle formats with default\n * configurations that are suitable for distributing libraries.\n */\n lib?: LibraryOptions | false\n /**\n * Produce SSR oriented build. Note this requires specifying SSR entry via\n * `rollupOptions.input`.\n */\n ssr?: boolean | string\n /**\n * Generate SSR manifest for determining style links and asset preload\n * directives in production.\n */\n ssrManifest?: boolean\n /**\n * Set to false to disable brotli compressed size reporting for build.\n * Can slightly improve build speed.\n */\n brotliSize?: boolean\n /**\n * Adjust chunk size warning limit (in kbs).\n * @default 500\n */\n chunkSizeWarningLimit?: number\n /**\n * Rollup watch options\n * https://rollupjs.org/guide/en/#watchoptions\n */\n watch?: WatcherOptions | null\n}\n\nexport interface LibraryOptions {\n entry: string\n name?: string\n formats?: LibraryFormats[]\n fileName?: string | ((format: ModuleFormat) => string)\n}\n\nexport type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife'\n\nexport type ResolvedBuildOptions = Required<\n Omit\n>\n\nexport function resolveBuildOptions(raw?: BuildOptions): ResolvedBuildOptions {\n const resolved: ResolvedBuildOptions = {\n target: 'modules',\n polyfillModulePreload: true,\n outDir: 'dist',\n assetsDir: 'assets',\n assetsInlineLimit: 4096,\n cssCodeSplit: !raw?.lib,\n sourcemap: false,\n rollupOptions: {},\n commonjsOptions: {\n include: [/node_modules/],\n extensions: ['.js', '.cjs'],\n ...raw?.commonjsOptions\n },\n dynamicImportVarsOptions: {\n warnOnError: true,\n exclude: [/node_modules/],\n ...raw?.dynamicImportVarsOptions\n },\n minify: raw?.ssr ? false : 'terser',\n terserOptions: {},\n write: true,\n emptyOutDir: null,\n manifest: false,\n lib: false,\n ssr: false,\n ssrManifest: false,\n brotliSize: true,\n chunkSizeWarningLimit: 500,\n watch: null,\n ...raw\n }\n\n // handle special build targets\n if (resolved.target === 'modules') {\n // Support browserslist\n // \"defaults and supports es6-module and supports es6-module-dynamic-import\",\n resolved.target = [\n 'es2019',\n 'edge88',\n 'firefox78',\n 'chrome87',\n 'safari13.1'\n ]\n } else if (resolved.target === 'esnext' && resolved.minify === 'terser') {\n // esnext + terser: limit to es2019 so it can be minified by terser\n resolved.target = 'es2019'\n }\n\n // normalize false string into actual false\n if ((resolved.minify as any) === 'false') {\n resolved.minify = false\n }\n\n return resolved\n}\n\nexport function resolveBuildPlugins(config: ResolvedConfig): {\n pre: Plugin[]\n post: Plugin[]\n} {\n const options = config.build\n return {\n pre: [\n buildHtmlPlugin(config),\n commonjsPlugin(options.commonjsOptions),\n dataURIPlugin(),\n dynamicImportVars(options.dynamicImportVarsOptions),\n assetImportMetaUrlPlugin(config),\n ...(options.rollupOptions.plugins\n ? (options.rollupOptions.plugins.filter((p) => !!p) as Plugin[])\n : [])\n ],\n post: [\n buildImportAnalysisPlugin(config),\n buildEsbuildPlugin(config),\n ...(options.minify && options.minify !== 'esbuild'\n ? [terserPlugin(options.terserOptions)]\n : []),\n ...(options.manifest ? [manifestPlugin(config)] : []),\n ...(options.ssrManifest ? [ssrManifestPlugin(config)] : []),\n buildReporterPlugin(config),\n loadFallbackPlugin()\n ]\n }\n}\n\n/**\n * Track parallel build calls and only stop the esbuild service when all\n * builds are done. (#1098)\n */\nlet parallelCallCounts = 0\n// we use a separate counter to track since the call may error before the\n// bundle is even pushed.\nconst parallelBuilds: RollupBuild[] = []\n\n/**\n * Bundles the app for production.\n * Returns a Promise containing the build result.\n */\nexport async function build(\n inlineConfig: InlineConfig = {}\n): Promise {\n parallelCallCounts++\n try {\n return await doBuild(inlineConfig)\n } finally {\n parallelCallCounts--\n if (parallelCallCounts <= 0) {\n await Promise.all(parallelBuilds.map((bundle) => bundle.close()))\n parallelBuilds.length = 0\n }\n }\n}\n\nasync function doBuild(\n inlineConfig: InlineConfig = {}\n): Promise {\n const config = await resolveConfig(inlineConfig, 'build', 'production')\n const options = config.build\n const ssr = !!options.ssr\n const libOptions = options.lib\n\n config.logger.info(\n chalk.cyan(\n `vite v${require('vite/package.json').version} ${chalk.green(\n `building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`\n )}`\n )\n )\n\n const resolve = (p: string) => path.resolve(config.root, p)\n const input = libOptions\n ? resolve(libOptions.entry)\n : typeof options.ssr === 'string'\n ? resolve(options.ssr)\n : options.rollupOptions?.input || resolve('index.html')\n\n if (ssr && typeof input === 'string' && input.endsWith('.html')) {\n throw new Error(\n `rollupOptions.input should not be an html file when building for SSR. ` +\n `Please specify a dedicated SSR entry.`\n )\n }\n\n const outDir = resolve(options.outDir)\n\n // inject ssr arg to plugin load/transform hooks\n const plugins = (\n ssr ? config.plugins.map((p) => injectSsrFlagToHooks(p)) : config.plugins\n ) as Plugin[]\n\n // inject ssrExternal if present\n const userExternal = options.rollupOptions?.external\n let external = userExternal\n if (ssr) {\n // see if we have cached deps data available\n let knownImports: string[] | undefined\n if (config.cacheDir) {\n const dataPath = path.join(config.cacheDir, '_metadata.json')\n try {\n const data = JSON.parse(\n fs.readFileSync(dataPath, 'utf-8')\n ) as DepOptimizationMetadata\n knownImports = Object.keys(data.optimized)\n } catch (e) {}\n }\n if (!knownImports) {\n // no dev deps optimization data, do a fresh scan\n knownImports = Object.keys((await scanImports(config)).deps)\n }\n external = resolveExternal(\n resolveSSRExternal(config, knownImports),\n userExternal\n )\n }\n\n const rollup = require('rollup') as typeof Rollup\n const rollupOptions: RollupOptions = {\n input,\n preserveEntrySignatures: ssr\n ? 'allow-extension'\n : libOptions\n ? 'strict'\n : false,\n ...options.rollupOptions,\n plugins,\n external,\n onwarn(warning, warn) {\n onRollupWarning(warning, warn, config)\n }\n }\n\n const outputBuildError = (e: RollupError) => {\n let msg = chalk.red((e.plugin ? `[${e.plugin}] ` : '') + e.message)\n if (e.id) {\n msg += `\\nfile: ${chalk.cyan(\n e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : '')\n )}`\n }\n if (e.frame) {\n msg += `\\n` + chalk.yellow(e.frame)\n }\n config.logger.error(msg, { error: e })\n }\n\n try {\n const pkgName = libOptions && getPkgName(config.root)\n\n const buildOutputOptions = (output: OutputOptions = {}): OutputOptions => {\n return {\n dir: outDir,\n format: ssr ? 'cjs' : 'es',\n exports: ssr ? 'named' : 'auto',\n sourcemap: options.sourcemap,\n name: libOptions ? libOptions.name : undefined,\n entryFileNames: ssr\n ? `[name].js`\n : libOptions\n ? resolveLibFilename(libOptions, output.format || 'es', pkgName)\n : path.posix.join(options.assetsDir, `[name].[hash].js`),\n chunkFileNames: libOptions\n ? `[name].js`\n : path.posix.join(options.assetsDir, `[name].[hash].js`),\n assetFileNames: libOptions\n ? `[name].[ext]`\n : path.posix.join(options.assetsDir, `[name].[hash].[ext]`),\n // #764 add `Symbol.toStringTag` when build es module into cjs chunk\n // #1048 add `Symbol.toStringTag` for module default export\n namespaceToStringTag: true,\n inlineDynamicImports: ssr && typeof input === 'string',\n manualChunks:\n !ssr &&\n !libOptions &&\n output?.format !== 'umd' &&\n output?.format !== 'iife'\n ? createMoveToVendorChunkFn(config)\n : undefined,\n ...output\n }\n }\n\n // resolve lib mode outputs\n const outputs = resolveBuildOutputs(\n options.rollupOptions?.output,\n libOptions,\n config.logger\n )\n\n // watch file changes with rollup\n if (config.build.watch) {\n config.logger.info(chalk.cyanBright(`\\nwatching for file changes...`))\n\n const output: OutputOptions[] = []\n if (Array.isArray(outputs)) {\n for (const resolvedOutput of outputs) {\n output.push(buildOutputOptions(resolvedOutput))\n }\n } else {\n output.push(buildOutputOptions(outputs))\n }\n\n const watcherOptions = config.build.watch\n const watcher = rollup.watch({\n ...rollupOptions,\n output,\n watch: {\n ...watcherOptions,\n chokidar: {\n ignored: [\n '**/node_modules/**',\n '**/.git/**',\n ...(watcherOptions?.chokidar?.ignored || [])\n ],\n ignoreInitial: true,\n ignorePermissionErrors: true,\n ...watcherOptions.chokidar\n }\n }\n })\n\n watcher.on('event', (event) => {\n if (event.code === 'BUNDLE_START') {\n config.logger.info(chalk.cyanBright(`\\nbuild started...`))\n if (options.write) {\n prepareOutDir(outDir, options.emptyOutDir, config)\n }\n } else if (event.code === 'BUNDLE_END') {\n event.result.close()\n config.logger.info(chalk.cyanBright(`built in ${event.duration}ms.`))\n } else if (event.code === 'ERROR') {\n outputBuildError(event.error)\n }\n })\n\n // stop watching\n watcher.close()\n\n return watcher\n }\n\n // write or generate files with rollup\n const bundle = await rollup.rollup(rollupOptions)\n parallelBuilds.push(bundle)\n\n const generate = (output: OutputOptions = {}) => {\n return bundle[options.write ? 'write' : 'generate'](\n buildOutputOptions(output)\n )\n }\n\n if (options.write) {\n prepareOutDir(outDir, options.emptyOutDir, config)\n }\n\n if (Array.isArray(outputs)) {\n const res = []\n for (const output of outputs) {\n res.push(await generate(output))\n }\n return res\n } else {\n return await generate(outputs)\n }\n } catch (e) {\n outputBuildError(e)\n throw e\n }\n}\n\nfunction prepareOutDir(\n outDir: string,\n emptyOutDir: boolean | null,\n config: ResolvedConfig\n) {\n if (fs.existsSync(outDir)) {\n if (\n emptyOutDir == null &&\n !normalizePath(outDir).startsWith(config.root + '/')\n ) {\n // warn if outDir is outside of root\n config.logger.warn(\n chalk.yellow(\n `\\n${chalk.bold(`(!)`)} outDir ${chalk.white.dim(\n outDir\n )} is not inside project root and will not be emptied.\\n` +\n `Use --emptyOutDir to override.\\n`\n )\n )\n } else if (emptyOutDir !== false) {\n emptyDir(outDir, ['.git'])\n }\n }\n if (config.publicDir && fs.existsSync(config.publicDir)) {\n copyDir(config.publicDir, outDir)\n }\n}\n\nfunction getPkgName(root: string) {\n const { name } = JSON.parse(lookupFile(root, ['package.json']) || `{}`)\n\n if (!name) throw new Error('no name found in package.json')\n\n return name.startsWith('@') ? name.split('/')[1] : name\n}\n\nfunction createMoveToVendorChunkFn(config: ResolvedConfig): GetManualChunk {\n const cache = new Map()\n return (id, { getModuleInfo }) => {\n if (\n id.includes('node_modules') &&\n !isCSSRequest(id) &&\n staticImportedByEntry(id, getModuleInfo, cache)\n ) {\n return 'vendor'\n }\n }\n}\n\nfunction staticImportedByEntry(\n id: string,\n getModuleInfo: GetModuleInfo,\n cache: Map,\n importStack: string[] = []\n): boolean {\n if (cache.has(id)) {\n return cache.get(id) as boolean\n }\n if (importStack.includes(id)) {\n // circular deps!\n cache.set(id, false)\n return false\n }\n const mod = getModuleInfo(id)\n if (!mod) {\n cache.set(id, false)\n return false\n }\n\n if (mod.isEntry) {\n cache.set(id, true)\n return true\n }\n const someImporterIs = mod.importers.some((importer) =>\n staticImportedByEntry(\n importer,\n getModuleInfo,\n cache,\n importStack.concat(id)\n )\n )\n cache.set(id, someImporterIs)\n return someImporterIs\n}\n\nexport function resolveLibFilename(\n libOptions: LibraryOptions,\n format: ModuleFormat,\n pkgName: string\n): string {\n return typeof libOptions.fileName === 'function'\n ? libOptions.fileName(format)\n : `${libOptions.fileName || pkgName}.${format}.js`\n}\n\nfunction resolveBuildOutputs(\n outputs: OutputOptions | OutputOptions[] | undefined,\n libOptions: LibraryOptions | false,\n logger: Logger\n): OutputOptions | OutputOptions[] | undefined {\n if (libOptions) {\n const formats = libOptions.formats || ['es', 'umd']\n if (\n (formats.includes('umd') || formats.includes('iife')) &&\n !libOptions.name\n ) {\n throw new Error(\n `Option \"build.lib.name\" is required when output formats ` +\n `include \"umd\" or \"iife\".`\n )\n }\n if (!outputs) {\n return formats.map((format) => ({ format }))\n } else if (!Array.isArray(outputs)) {\n return formats.map((format) => ({ ...outputs, format }))\n } else if (libOptions.formats) {\n // user explicitly specifying own output array\n logger.warn(\n chalk.yellow(\n `\"build.lib.formats\" will be ignored because ` +\n `\"build.rollupOptions.output\" is already an array format`\n )\n )\n }\n }\n return outputs\n}\n\nconst warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]\nconst dynamicImportWarningIgnoreList = [\n `Unsupported expression`,\n `statically analyzed`\n]\n\nexport function onRollupWarning(\n warning: RollupWarning,\n warn: WarningHandler,\n config: ResolvedConfig\n): void {\n if (warning.code === 'UNRESOLVED_IMPORT') {\n const id = warning.source\n const importer = warning.importer\n // throw unless it's commonjs external...\n if (!importer || !/\\?commonjs-external$/.test(importer)) {\n throw new Error(\n `[vite]: Rollup failed to resolve import \"${id}\" from \"${importer}\".\\n` +\n `This is most likely unintended because it can break your application at runtime.\\n` +\n `If you do want to externalize this module explicitly add it to\\n` +\n `\\`build.rollupOptions.external\\``\n )\n }\n }\n\n if (\n warning.plugin === 'rollup-plugin-dynamic-import-variables' &&\n dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg))\n ) {\n return\n }\n\n if (!warningIgnoreList.includes(warning.code!)) {\n const userOnWarn = config.build.rollupOptions?.onwarn\n if (userOnWarn) {\n userOnWarn(warning, warn)\n } else if (warning.code === 'PLUGIN_WARNING') {\n config.logger.warn(\n `${chalk.bold.yellow(`[plugin:${warning.plugin}]`)} ${chalk.yellow(\n warning.message\n )}`\n )\n } else {\n warn(warning)\n }\n }\n}\n\nfunction resolveExternal(\n ssrExternals: string[],\n user: ExternalOption | undefined\n): ExternalOption {\n return ((id, parentId, isResolved) => {\n if (shouldExternalizeForSSR(id, ssrExternals)) {\n return true\n }\n if (user) {\n if (typeof user === 'function') {\n return user(id, parentId, isResolved)\n } else if (Array.isArray(user)) {\n return user.some((test) => isExternal(id, test))\n } else {\n return isExternal(id, user)\n }\n }\n }) as ExternalOption\n}\n\nfunction isExternal(id: string, test: string | RegExp) {\n if (typeof test === 'string') {\n return id === test\n } else {\n return test.test(id)\n }\n}\n\nfunction injectSsrFlagToHooks(p: Plugin): Plugin {\n const { resolveId, load, transform } = p\n return {\n ...p,\n resolveId: wrapSsrHook(resolveId),\n load: wrapSsrHook(load),\n transform: wrapSsrHook(transform)\n }\n}\n\nfunction wrapSsrHook(fn: Function | undefined) {\n if (!fn) return\n return function (this: any, ...args: any[]) {\n return fn.call(this, ...args, true)\n }\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\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' && isNaN(val) === false) {\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|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 '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 if (ms >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (ms >= 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 return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return;\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name;\n }\n return Math.ceil(ms / n) + ' ' + name + 's';\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n","/**\n * This is the web browser implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = 'undefined' != typeof chrome\n && 'undefined' != typeof chrome.storage\n ? chrome.storage.local\n : localstorage();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n 'lightseagreen',\n 'forestgreen',\n 'goldenrod',\n 'dodgerblue',\n 'darkorchid',\n 'crimson'\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\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\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 try {\n return window.localStorage;\n } catch (e) {}\n}\n","/**\n * Module dependencies.\n */\n\nvar tty = require('tty');\nvar util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(function (key) {\n return /^debug_/i.test(key);\n}).reduce(function (obj, key) {\n // camel-case\n var prop = key\n .substring(6)\n .toLowerCase()\n .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });\n\n // coerce string value into JS value\n var val = process.env[key];\n if (/^(yes|on|true|enabled)$/i.test(val)) val = true;\n else if (/^(no|off|false|disabled)$/i.test(val)) val = false;\n else if (val === 'null') val = null;\n else val = Number(val);\n\n obj[prop] = val;\n return obj;\n}, {});\n\n/**\n * The file descriptor to write the `debug()` calls to.\n * Set the `DEBUG_FD` env variable to override with another value. i.e.:\n *\n * $ DEBUG_FD=3 node script.js 3>debug.log\n */\n\nvar fd = parseInt(process.env.DEBUG_FD, 10) || 2;\n\nif (1 !== fd && 2 !== fd) {\n util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')()\n}\n\nvar stream = 1 === fd ? process.stdout :\n 2 === fd ? process.stderr :\n createWritableStdioStream(fd);\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n return 'colors' in exports.inspectOpts\n ? Boolean(exports.inspectOpts.colors)\n : tty.isatty(fd);\n}\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nexports.formatters.o = function(v) {\n this.inspectOpts.colors = this.useColors;\n return util.inspect(v, this.inspectOpts)\n .split('\\n').map(function(str) {\n return str.trim()\n }).join(' ');\n};\n\n/**\n * Map %o to `util.inspect()`, allowing multiple lines if needed.\n */\n\nexports.formatters.O = function(v) {\n this.inspectOpts.colors = this.useColors;\n return util.inspect(v, this.inspectOpts);\n};\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var name = this.namespace;\n var useColors = this.useColors;\n\n if (useColors) {\n var c = this.color;\n var prefix = ' \\u001b[3' + c + ';1m' + name + ' ' + '\\u001b[0m';\n\n args[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n args.push('\\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\\u001b[0m');\n } else {\n args[0] = new Date().toUTCString()\n + ' ' + name + ' ' + args[0];\n }\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to `stream`.\n */\n\nfunction log() {\n return stream.write(util.format.apply(util, arguments) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n if (null == namespaces) {\n // If you set a process.env field to null or undefined, it gets cast to the\n // string 'null' or 'undefined'. Just delete instead.\n delete process.env.DEBUG;\n } else {\n process.env.DEBUG = namespaces;\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n return process.env.DEBUG;\n}\n\n/**\n * Copied from `node/src/node.js`.\n *\n * XXX: It's lame that node doesn't expose this API out-of-the-box. It also\n * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.\n */\n\nfunction createWritableStdioStream (fd) {\n var stream;\n var tty_wrap = process.binding('tty_wrap');\n\n // Note stream._type is used for test-module-load-list.js\n\n switch (tty_wrap.guessHandleType(fd)) {\n case 'TTY':\n stream = new tty.WriteStream(fd);\n stream._type = 'tty';\n\n // Hack to have stream not keep the event loop alive.\n // See https://github.com/joyent/node/issues/1726\n if (stream._handle && stream._handle.unref) {\n stream._handle.unref();\n }\n break;\n\n case 'FILE':\n var fs = require('fs');\n stream = new fs.SyncWriteStream(fd, { autoClose: false });\n stream._type = 'fs';\n break;\n\n case 'PIPE':\n case 'TCP':\n var net = require('net');\n stream = new net.Socket({\n fd: fd,\n readable: false,\n writable: true\n });\n\n // FIXME Should probably have an option in net.Socket to create a\n // stream from an existing fd which is writable only. But for now\n // we'll just add this hack and set the `readable` member to false.\n // Test: ./node test/fixtures/echo.js < /etc/passwd\n stream.readable = false;\n stream.read = null;\n stream._type = 'pipe';\n\n // FIXME Hack to have stream not keep the event loop alive.\n // See https://github.com/joyent/node/issues/1726\n if (stream._handle && stream._handle.unref) {\n stream._handle.unref();\n }\n break;\n\n default:\n // Probably an error on in uv_guess_handle()\n throw new Error('Implement me. Unknown stream file type!');\n }\n\n // For supporting legacy API we put the FD here.\n stream.fd = fd;\n\n stream._isStdio = true;\n\n return stream;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init (debug) {\n debug.inspectOpts = {};\n\n var keys = Object.keys(exports.inspectOpts);\n for (var i = 0; i < keys.length; i++) {\n debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n }\n}\n\n/**\n * Enable namespaces listed in `process.env.DEBUG` initially.\n */\n\nexports.enable(load());\n","/**\n * Detect Electron renderer process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process !== 'undefined' && process.type === 'renderer') {\n module.exports = require('./browser.js');\n} else {\n module.exports = require('./node.js');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n","/**\n * This is the web browser implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = 'undefined' != typeof chrome\n && 'undefined' != typeof chrome.storage\n ? chrome.storage.local\n : localstorage();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n 'lightseagreen',\n 'forestgreen',\n 'goldenrod',\n 'dodgerblue',\n 'darkorchid',\n 'crimson'\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\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\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 try {\n return window.localStorage;\n } catch (e) {}\n}\n","/**\n * Module dependencies.\n */\n\nvar tty = require('tty');\nvar util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(function (key) {\n return /^debug_/i.test(key);\n}).reduce(function (obj, key) {\n // camel-case\n var prop = key\n .substring(6)\n .toLowerCase()\n .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });\n\n // coerce string value into JS value\n var val = process.env[key];\n if (/^(yes|on|true|enabled)$/i.test(val)) val = true;\n else if (/^(no|off|false|disabled)$/i.test(val)) val = false;\n else if (val === 'null') val = null;\n else val = Number(val);\n\n obj[prop] = val;\n return obj;\n}, {});\n\n/**\n * The file descriptor to write the `debug()` calls to.\n * Set the `DEBUG_FD` env variable to override with another value. i.e.:\n *\n * $ DEBUG_FD=3 node script.js 3>debug.log\n */\n\nvar fd = parseInt(process.env.DEBUG_FD, 10) || 2;\n\nif (1 !== fd && 2 !== fd) {\n util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')()\n}\n\nvar stream = 1 === fd ? process.stdout :\n 2 === fd ? process.stderr :\n createWritableStdioStream(fd);\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n return 'colors' in exports.inspectOpts\n ? Boolean(exports.inspectOpts.colors)\n : tty.isatty(fd);\n}\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nexports.formatters.o = function(v) {\n this.inspectOpts.colors = this.useColors;\n return util.inspect(v, this.inspectOpts)\n .split('\\n').map(function(str) {\n return str.trim()\n }).join(' ');\n};\n\n/**\n * Map %o to `util.inspect()`, allowing multiple lines if needed.\n */\n\nexports.formatters.O = function(v) {\n this.inspectOpts.colors = this.useColors;\n return util.inspect(v, this.inspectOpts);\n};\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var name = this.namespace;\n var useColors = this.useColors;\n\n if (useColors) {\n var c = this.color;\n var prefix = ' \\u001b[3' + c + ';1m' + name + ' ' + '\\u001b[0m';\n\n args[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n args.push('\\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\\u001b[0m');\n } else {\n args[0] = new Date().toUTCString()\n + ' ' + name + ' ' + args[0];\n }\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to `stream`.\n */\n\nfunction log() {\n return stream.write(util.format.apply(util, arguments) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n if (null == namespaces) {\n // If you set a process.env field to null or undefined, it gets cast to the\n // string 'null' or 'undefined'. Just delete instead.\n delete process.env.DEBUG;\n } else {\n process.env.DEBUG = namespaces;\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n return process.env.DEBUG;\n}\n\n/**\n * Copied from `node/src/node.js`.\n *\n * XXX: It's lame that node doesn't expose this API out-of-the-box. It also\n * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.\n */\n\nfunction createWritableStdioStream (fd) {\n var stream;\n var tty_wrap = process.binding('tty_wrap');\n\n // Note stream._type is used for test-module-load-list.js\n\n switch (tty_wrap.guessHandleType(fd)) {\n case 'TTY':\n stream = new tty.WriteStream(fd);\n stream._type = 'tty';\n\n // Hack to have stream not keep the event loop alive.\n // See https://github.com/joyent/node/issues/1726\n if (stream._handle && stream._handle.unref) {\n stream._handle.unref();\n }\n break;\n\n case 'FILE':\n var fs = require('fs');\n stream = new fs.SyncWriteStream(fd, { autoClose: false });\n stream._type = 'fs';\n break;\n\n case 'PIPE':\n case 'TCP':\n var net = require('net');\n stream = new net.Socket({\n fd: fd,\n readable: false,\n writable: true\n });\n\n // FIXME Should probably have an option in net.Socket to create a\n // stream from an existing fd which is writable only. But for now\n // we'll just add this hack and set the `readable` member to false.\n // Test: ./node test/fixtures/echo.js < /etc/passwd\n stream.readable = false;\n stream.read = null;\n stream._type = 'pipe';\n\n // FIXME Hack to have stream not keep the event loop alive.\n // See https://github.com/joyent/node/issues/1726\n if (stream._handle && stream._handle.unref) {\n stream._handle.unref();\n }\n break;\n\n default:\n // Probably an error on in uv_guess_handle()\n throw new Error('Implement me. Unknown stream file type!');\n }\n\n // For supporting legacy API we put the FD here.\n stream.fd = fd;\n\n stream._isStdio = true;\n\n return stream;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init (debug) {\n debug.inspectOpts = {};\n\n var keys = Object.keys(exports.inspectOpts);\n for (var i = 0; i < keys.length; i++) {\n debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n }\n}\n\n/**\n * Enable namespaces listed in `process.env.DEBUG` initially.\n */\n\nexports.enable(load());\n","/**\n * Detect Electron renderer process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process !== 'undefined' && process.type === 'renderer') {\n module.exports = require('./browser.js');\n} else {\n module.exports = require('./node.js');\n}\n","/*!\n * encodeurl\n * Copyright(c) 2016 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = encodeUrl\n\n/**\n * RegExp to match non-URL code points, *after* encoding (i.e. not including \"%\")\n * and including invalid escape sequences.\n * @private\n */\n\nvar ENCODE_CHARS_REGEXP = /(?:[^\\x21\\x25\\x26-\\x3B\\x3D\\x3F-\\x5B\\x5D\\x5F\\x61-\\x7A\\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g\n\n/**\n * RegExp to match unmatched surrogate pair.\n * @private\n */\n\nvar UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF]([^\\uDC00-\\uDFFF]|$)/g\n\n/**\n * String to replace unmatched surrogate pair with.\n * @private\n */\n\nvar UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\\uFFFD$2'\n\n/**\n * Encode a URL to a percent-encoded form, excluding already-encoded sequences.\n *\n * This function will take an already-encoded URL and encode all the non-URL\n * code points. This function will not encode the \"%\" character unless it is\n * not part of a valid sequence (`%20` will be left as-is, but `%foo` will\n * be encoded as `%25foo`).\n *\n * This encode is meant to be \"safe\" and does not throw errors. It will try as\n * hard as it can to properly encode the given URL, including replacing any raw,\n * unpaired surrogate pairs with the Unicode replacement character prior to\n * encoding.\n *\n * @param {string} url\n * @return {string}\n * @public\n */\n\nfunction encodeUrl (url) {\n return String(url)\n .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE)\n .replace(ENCODE_CHARS_REGEXP, encodeURI)\n}\n","/*!\n * escape-html\n * Copyright(c) 2012-2013 TJ Holowaychuk\n * Copyright(c) 2015 Andreas Lubbe\n * Copyright(c) 2015 Tiancheng \"Timothy\" Gu\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module variables.\n * @private\n */\n\nvar matchHtmlRegExp = /[\"'&<>]/;\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = escapeHtml;\n\n/**\n * Escape special characters in the given string of html.\n *\n * @param {string} string The string to escape for inserting into HTML\n * @return {string}\n * @public\n */\n\nfunction escapeHtml(string) {\n var str = '' + string;\n var match = matchHtmlRegExp.exec(str);\n\n if (!match) {\n return str;\n }\n\n var escape;\n var html = '';\n var index = 0;\n var lastIndex = 0;\n\n for (index = match.index; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34: // \"\n escape = '"';\n break;\n case 38: // &\n escape = '&';\n break;\n case 39: // '\n escape = ''';\n break;\n case 60: // <\n escape = '<';\n break;\n case 62: // >\n escape = '>';\n break;\n default:\n continue;\n }\n\n if (lastIndex !== index) {\n html += str.substring(lastIndex, index);\n }\n\n lastIndex = index + 1;\n html += escape;\n }\n\n return lastIndex !== index\n ? html + str.substring(lastIndex, index)\n : html;\n}\n","/*!\n * ee-first\n * Copyright(c) 2014 Jonathan Ong\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = first\n\n/**\n * Get the first event in a set of event emitters and event pairs.\n *\n * @param {array} stuff\n * @param {function} done\n * @public\n */\n\nfunction first(stuff, done) {\n if (!Array.isArray(stuff))\n throw new TypeError('arg must be an array of [ee, events...] arrays')\n\n var cleanups = []\n\n for (var i = 0; i < stuff.length; i++) {\n var arr = stuff[i]\n\n if (!Array.isArray(arr) || arr.length < 2)\n throw new TypeError('each array member must be [ee, events...]')\n\n var ee = arr[0]\n\n for (var j = 1; j < arr.length; j++) {\n var event = arr[j]\n var fn = listener(event, callback)\n\n // listen to the event\n ee.on(event, fn)\n // push this listener to the list of cleanups\n cleanups.push({\n ee: ee,\n event: event,\n fn: fn,\n })\n }\n }\n\n function callback() {\n cleanup()\n done.apply(null, arguments)\n }\n\n function cleanup() {\n var x\n for (var i = 0; i < cleanups.length; i++) {\n x = cleanups[i]\n x.ee.removeListener(x.event, x.fn)\n }\n }\n\n function thunk(fn) {\n done = fn\n }\n\n thunk.cancel = cleanup\n\n return thunk\n}\n\n/**\n * Create the event listener.\n * @private\n */\n\nfunction listener(event, done) {\n return function onevent(arg1) {\n var args = new Array(arguments.length)\n var ee = this\n var err = event === 'error'\n ? arg1\n : null\n\n // copy args to prevent arguments escaping scope\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n\n done(err, ee, event, args)\n }\n}\n","/*!\n * on-finished\n * Copyright(c) 2013 Jonathan Ong\n * Copyright(c) 2014 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = onFinished\nmodule.exports.isFinished = isFinished\n\n/**\n * Module dependencies.\n * @private\n */\n\nvar first = require('ee-first')\n\n/**\n * Variables.\n * @private\n */\n\n/* istanbul ignore next */\nvar defer = typeof setImmediate === 'function'\n ? setImmediate\n : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }\n\n/**\n * Invoke callback when the response has finished, useful for\n * cleaning up resources afterwards.\n *\n * @param {object} msg\n * @param {function} listener\n * @return {object}\n * @public\n */\n\nfunction onFinished(msg, listener) {\n if (isFinished(msg) !== false) {\n defer(listener, null, msg)\n return msg\n }\n\n // attach the listener to the message\n attachListener(msg, listener)\n\n return msg\n}\n\n/**\n * Determine if message is already finished.\n *\n * @param {object} msg\n * @return {boolean}\n * @public\n */\n\nfunction isFinished(msg) {\n var socket = msg.socket\n\n if (typeof msg.finished === 'boolean') {\n // OutgoingMessage\n return Boolean(msg.finished || (socket && !socket.writable))\n }\n\n if (typeof msg.complete === 'boolean') {\n // IncomingMessage\n return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable))\n }\n\n // don't know\n return undefined\n}\n\n/**\n * Attach a finished listener to the message.\n *\n * @param {object} msg\n * @param {function} callback\n * @private\n */\n\nfunction attachFinishedListener(msg, callback) {\n var eeMsg\n var eeSocket\n var finished = false\n\n function onFinish(error) {\n eeMsg.cancel()\n eeSocket.cancel()\n\n finished = true\n callback(error)\n }\n\n // finished on first message event\n eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish)\n\n function onSocket(socket) {\n // remove listener\n msg.removeListener('socket', onSocket)\n\n if (finished) return\n if (eeMsg !== eeSocket) return\n\n // finished on first socket event\n eeSocket = first([[socket, 'error', 'close']], onFinish)\n }\n\n if (msg.socket) {\n // socket already assigned\n onSocket(msg.socket)\n return\n }\n\n // wait for socket to be assigned\n msg.on('socket', onSocket)\n\n if (msg.socket === undefined) {\n // node.js 0.8 patch\n patchAssignSocket(msg, onSocket)\n }\n}\n\n/**\n * Attach the listener to the message.\n *\n * @param {object} msg\n * @return {function}\n * @private\n */\n\nfunction attachListener(msg, listener) {\n var attached = msg.__onFinished\n\n // create a private single listener with queue\n if (!attached || !attached.queue) {\n attached = msg.__onFinished = createListener(msg)\n attachFinishedListener(msg, attached)\n }\n\n attached.queue.push(listener)\n}\n\n/**\n * Create listener on message.\n *\n * @param {object} msg\n * @return {function}\n * @private\n */\n\nfunction createListener(msg) {\n function listener(err) {\n if (msg.__onFinished === listener) msg.__onFinished = null\n if (!listener.queue) return\n\n var queue = listener.queue\n listener.queue = null\n\n for (var i = 0; i < queue.length; i++) {\n queue[i](err, msg)\n }\n }\n\n listener.queue = []\n\n return listener\n}\n\n/**\n * Patch ServerResponse.prototype.assignSocket for node.js 0.8.\n *\n * @param {ServerResponse} res\n * @param {function} callback\n * @private\n */\n\nfunction patchAssignSocket(res, callback) {\n var assignSocket = res.assignSocket\n\n if (typeof assignSocket !== 'function') return\n\n // res.on('socket', callback) is broken in 0.8\n res.assignSocket = function _assignSocket(socket) {\n assignSocket.call(this, socket)\n callback(socket)\n }\n}\n","/*!\n * parseurl\n * Copyright(c) 2014 Jonathan Ong\n * Copyright(c) 2014-2017 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * Module dependencies.\n * @private\n */\n\nvar url = require('url')\nvar parse = url.parse\nvar Url = url.Url\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = parseurl\nmodule.exports.original = originalurl\n\n/**\n * Parse the `req` url with memoization.\n *\n * @param {ServerRequest} req\n * @return {Object}\n * @public\n */\n\nfunction parseurl (req) {\n var url = req.url\n\n if (url === undefined) {\n // URL is undefined\n return undefined\n }\n\n var parsed = req._parsedUrl\n\n if (fresh(url, parsed)) {\n // Return cached URL parse\n return parsed\n }\n\n // Parse the URL\n parsed = fastparse(url)\n parsed._raw = url\n\n return (req._parsedUrl = parsed)\n};\n\n/**\n * Parse the `req` original url with fallback and memoization.\n *\n * @param {ServerRequest} req\n * @return {Object}\n * @public\n */\n\nfunction originalurl (req) {\n var url = req.originalUrl\n\n if (typeof url !== 'string') {\n // Fallback\n return parseurl(req)\n }\n\n var parsed = req._parsedOriginalUrl\n\n if (fresh(url, parsed)) {\n // Return cached URL parse\n return parsed\n }\n\n // Parse the URL\n parsed = fastparse(url)\n parsed._raw = url\n\n return (req._parsedOriginalUrl = parsed)\n};\n\n/**\n * Parse the `str` url with fast-path short-cut.\n *\n * @param {string} str\n * @return {Object}\n * @private\n */\n\nfunction fastparse (str) {\n if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) {\n return parse(str)\n }\n\n var pathname = str\n var query = null\n var search = null\n\n // This takes the regexp from https://github.com/joyent/node/pull/7878\n // Which is /^(\\/[^?#\\s]*)(\\?[^#\\s]*)?$/\n // And unrolls it into a for loop\n for (var i = 1; i < str.length; i++) {\n switch (str.charCodeAt(i)) {\n case 0x3f: /* ? */\n if (search === null) {\n pathname = str.substring(0, i)\n query = str.substring(i + 1)\n search = str.substring(i)\n }\n break\n case 0x09: /* \\t */\n case 0x0a: /* \\n */\n case 0x0c: /* \\f */\n case 0x0d: /* \\r */\n case 0x20: /* */\n case 0x23: /* # */\n case 0xa0:\n case 0xfeff:\n return parse(str)\n }\n }\n\n var url = Url !== undefined\n ? new Url()\n : {}\n\n url.path = str\n url.href = str\n url.pathname = pathname\n\n if (search !== null) {\n url.query = query\n url.search = search\n }\n\n return url\n}\n\n/**\n * Determine if parsed is still fresh for url.\n *\n * @param {string} url\n * @param {object} parsedUrl\n * @return {boolean}\n * @private\n */\n\nfunction fresh (url, parsedUrl) {\n return typeof parsedUrl === 'object' &&\n parsedUrl !== null &&\n (Url === undefined || parsedUrl instanceof Url) &&\n parsedUrl._raw === url\n}\n","/*!\n * statuses\n * Copyright(c) 2014 Jonathan Ong\n * Copyright(c) 2016 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * Module dependencies.\n * @private\n */\n\nvar codes = require('./codes.json')\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = status\n\n// status code to message map\nstatus.STATUS_CODES = codes\n\n// array of status codes\nstatus.codes = populateStatusesMap(status, codes)\n\n// status codes for redirects\nstatus.redirect = {\n 300: true,\n 301: true,\n 302: true,\n 303: true,\n 305: true,\n 307: true,\n 308: true\n}\n\n// status codes for empty bodies\nstatus.empty = {\n 204: true,\n 205: true,\n 304: true\n}\n\n// status codes for when you should retry the request\nstatus.retry = {\n 502: true,\n 503: true,\n 504: true\n}\n\n/**\n * Populate the statuses map for given codes.\n * @private\n */\n\nfunction populateStatusesMap (statuses, codes) {\n var arr = []\n\n Object.keys(codes).forEach(function forEachCode (code) {\n var message = codes[code]\n var status = Number(code)\n\n // Populate properties\n statuses[status] = message\n statuses[message] = status\n statuses[message.toLowerCase()] = status\n\n // Add to array\n arr.push(status)\n })\n\n return arr\n}\n\n/**\n * Get the status code.\n *\n * Given a number, this will throw if it is not a known status\n * code, otherwise the code will be returned. Given a string,\n * the string will be parsed for a number and return the code\n * if valid, otherwise will lookup the code assuming this is\n * the status message.\n *\n * @param {string|number} code\n * @returns {number}\n * @public\n */\n\nfunction status (code) {\n if (typeof code === 'number') {\n if (!status[code]) throw new Error('invalid status code: ' + code)\n return code\n }\n\n if (typeof code !== 'string') {\n throw new TypeError('code must be a number or string')\n }\n\n // '403'\n var n = parseInt(code, 10)\n if (!isNaN(n)) {\n if (!status[n]) throw new Error('invalid status code: ' + n)\n return n\n }\n\n n = status[code.toLowerCase()]\n if (!n) throw new Error('invalid status message: \"' + code + '\"')\n return n\n}\n","/*!\n * unpipe\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = unpipe\n\n/**\n * Determine if there are Node.js pipe-like data listeners.\n * @private\n */\n\nfunction hasPipeDataListeners(stream) {\n var listeners = stream.listeners('data')\n\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i].name === 'ondata') {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Unpipe a stream from all destinations.\n *\n * @param {object} stream\n * @public\n */\n\nfunction unpipe(stream) {\n if (!stream) {\n throw new TypeError('argument stream is required')\n }\n\n if (typeof stream.unpipe === 'function') {\n // new-style\n stream.unpipe()\n return\n }\n\n // Node.js 0.8 hack\n if (!hasPipeDataListeners(stream)) {\n return\n }\n\n var listener\n var listeners = stream.listeners('close')\n\n for (var i = 0; i < listeners.length; i++) {\n listener = listeners[i]\n\n if (listener.name !== 'cleanup' && listener.name !== 'onclose') {\n continue\n }\n\n // invoke the listener\n listener.call(stream)\n }\n}\n","/*!\n * finalhandler\n * Copyright(c) 2014-2017 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * Module dependencies.\n * @private\n */\n\nvar debug = require('debug')('finalhandler')\nvar encodeUrl = require('encodeurl')\nvar escapeHtml = require('escape-html')\nvar onFinished = require('on-finished')\nvar parseUrl = require('parseurl')\nvar statuses = require('statuses')\nvar unpipe = require('unpipe')\n\n/**\n * Module variables.\n * @private\n */\n\nvar DOUBLE_SPACE_REGEXP = /\\x20{2}/g\nvar NEWLINE_REGEXP = /\\n/g\n\n/* istanbul ignore next */\nvar defer = typeof setImmediate === 'function'\n ? setImmediate\n : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) }\nvar isFinished = onFinished.isFinished\n\n/**\n * Create a minimal HTML document.\n *\n * @param {string} message\n * @private\n */\n\nfunction createHtmlDocument (message) {\n var body = escapeHtml(message)\n .replace(NEWLINE_REGEXP, '
')\n .replace(DOUBLE_SPACE_REGEXP, '  ')\n\n return '\\n' +\n '\\n' +\n '\\n' +\n '\\n' +\n 'Error\\n' +\n '\\n' +\n '\\n' +\n '
' + body + '
\\n' +\n '\\n' +\n '\\n'\n}\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = finalhandler\n\n/**\n * Create a function to handle the final response.\n *\n * @param {Request} req\n * @param {Response} res\n * @param {Object} [options]\n * @return {Function}\n * @public\n */\n\nfunction finalhandler (req, res, options) {\n var opts = options || {}\n\n // get environment\n var env = opts.env || process.env.NODE_ENV || 'development'\n\n // get error callback\n var onerror = opts.onerror\n\n return function (err) {\n var headers\n var msg\n var status\n\n // ignore 404 on in-flight response\n if (!err && headersSent(res)) {\n debug('cannot 404 after headers sent')\n return\n }\n\n // unhandled error\n if (err) {\n // respect status code from error\n status = getErrorStatusCode(err)\n\n if (status === undefined) {\n // fallback to status code on response\n status = getResponseStatusCode(res)\n } else {\n // respect headers from error\n headers = getErrorHeaders(err)\n }\n\n // get error message\n msg = getErrorMessage(err, status, env)\n } else {\n // not found\n status = 404\n msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req))\n }\n\n debug('default %s', status)\n\n // schedule onerror callback\n if (err && onerror) {\n defer(onerror, err, req, res)\n }\n\n // cannot actually respond\n if (headersSent(res)) {\n debug('cannot %d after headers sent', status)\n req.socket.destroy()\n return\n }\n\n // send response\n send(req, res, status, headers, msg)\n }\n}\n\n/**\n * Get headers from Error object.\n *\n * @param {Error} err\n * @return {object}\n * @private\n */\n\nfunction getErrorHeaders (err) {\n if (!err.headers || typeof err.headers !== 'object') {\n return undefined\n }\n\n var headers = Object.create(null)\n var keys = Object.keys(err.headers)\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i]\n headers[key] = err.headers[key]\n }\n\n return headers\n}\n\n/**\n * Get message from Error object, fallback to status message.\n *\n * @param {Error} err\n * @param {number} status\n * @param {string} env\n * @return {string}\n * @private\n */\n\nfunction getErrorMessage (err, status, env) {\n var msg\n\n if (env !== 'production') {\n // use err.stack, which typically includes err.message\n msg = err.stack\n\n // fallback to err.toString() when possible\n if (!msg && typeof err.toString === 'function') {\n msg = err.toString()\n }\n }\n\n return msg || statuses[status]\n}\n\n/**\n * Get status code from Error object.\n *\n * @param {Error} err\n * @return {number}\n * @private\n */\n\nfunction getErrorStatusCode (err) {\n // check err.status\n if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {\n return err.status\n }\n\n // check err.statusCode\n if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {\n return err.statusCode\n }\n\n return undefined\n}\n\n/**\n * Get resource name for the request.\n *\n * This is typically just the original pathname of the request\n * but will fallback to \"resource\" is that cannot be determined.\n *\n * @param {IncomingMessage} req\n * @return {string}\n * @private\n */\n\nfunction getResourceName (req) {\n try {\n return parseUrl.original(req).pathname\n } catch (e) {\n return 'resource'\n }\n}\n\n/**\n * Get status code from response.\n *\n * @param {OutgoingMessage} res\n * @return {number}\n * @private\n */\n\nfunction getResponseStatusCode (res) {\n var status = res.statusCode\n\n // default status code to 500 if outside valid range\n if (typeof status !== 'number' || status < 400 || status > 599) {\n status = 500\n }\n\n return status\n}\n\n/**\n * Determine if the response headers have been sent.\n *\n * @param {object} res\n * @returns {boolean}\n * @private\n */\n\nfunction headersSent (res) {\n return typeof res.headersSent !== 'boolean'\n ? Boolean(res._header)\n : res.headersSent\n}\n\n/**\n * Send response.\n *\n * @param {IncomingMessage} req\n * @param {OutgoingMessage} res\n * @param {number} status\n * @param {object} headers\n * @param {string} message\n * @private\n */\n\nfunction send (req, res, status, headers, message) {\n function write () {\n // response body\n var body = createHtmlDocument(message)\n\n // response status\n res.statusCode = status\n res.statusMessage = statuses[status]\n\n // response headers\n setHeaders(res, headers)\n\n // security headers\n res.setHeader('Content-Security-Policy', \"default-src 'none'\")\n res.setHeader('X-Content-Type-Options', 'nosniff')\n\n // standard headers\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'))\n\n if (req.method === 'HEAD') {\n res.end()\n return\n }\n\n res.end(body, 'utf8')\n }\n\n if (isFinished(req)) {\n write()\n return\n }\n\n // unpipe everything from the request\n unpipe(req)\n\n // flush the request\n onFinished(req, write)\n req.resume()\n}\n\n/**\n * Set response headers from an object.\n *\n * @param {OutgoingMessage} res\n * @param {object} headers\n * @private\n */\n\nfunction setHeaders (res, headers) {\n if (!headers) {\n return\n }\n\n var keys = Object.keys(headers)\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i]\n res.setHeader(key, headers[key])\n }\n}\n","/**\n * Merge object b with object a.\n *\n * var a = { foo: 'bar' }\n * , b = { bar: 'baz' };\n *\n * merge(a, b);\n * // => { foo: 'bar', bar: 'baz' }\n *\n * @param {Object} a\n * @param {Object} b\n * @return {Object}\n * @api public\n */\n\nexports = module.exports = function(a, b){\n if (a && b) {\n for (var key in b) {\n a[key] = b[key];\n }\n }\n return a;\n};\n","/*!\n * connect\n * Copyright(c) 2010 Sencha Inc.\n * Copyright(c) 2011 TJ Holowaychuk\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module dependencies.\n * @private\n */\n\nvar debug = require('debug')('connect:dispatcher');\nvar EventEmitter = require('events').EventEmitter;\nvar finalhandler = require('finalhandler');\nvar http = require('http');\nvar merge = require('utils-merge');\nvar parseUrl = require('parseurl');\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = createServer;\n\n/**\n * Module variables.\n * @private\n */\n\nvar env = process.env.NODE_ENV || 'development';\nvar proto = {};\n\n/* istanbul ignore next */\nvar defer = typeof setImmediate === 'function'\n ? setImmediate\n : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }\n\n/**\n * Create a new connect server.\n *\n * @return {function}\n * @public\n */\n\nfunction createServer() {\n function app(req, res, next){ app.handle(req, res, next); }\n merge(app, proto);\n merge(app, EventEmitter.prototype);\n app.route = '/';\n app.stack = [];\n return app;\n}\n\n/**\n * Utilize the given middleware `handle` to the given `route`,\n * defaulting to _/_. This \"route\" is the mount-point for the\n * middleware, when given a value other than _/_ the middleware\n * is only effective when that segment is present in the request's\n * pathname.\n *\n * For example if we were to mount a function at _/admin_, it would\n * be invoked on _/admin_, and _/admin/settings_, however it would\n * not be invoked for _/_, or _/posts_.\n *\n * @param {String|Function|Server} route, callback or server\n * @param {Function|Server} callback or server\n * @return {Server} for chaining\n * @public\n */\n\nproto.use = function use(route, fn) {\n var handle = fn;\n var path = route;\n\n // default route to '/'\n if (typeof route !== 'string') {\n handle = route;\n path = '/';\n }\n\n // wrap sub-apps\n if (typeof handle.handle === 'function') {\n var server = handle;\n server.route = path;\n handle = function (req, res, next) {\n server.handle(req, res, next);\n };\n }\n\n // wrap vanilla http.Servers\n if (handle instanceof http.Server) {\n handle = handle.listeners('request')[0];\n }\n\n // strip trailing slash\n if (path[path.length - 1] === '/') {\n path = path.slice(0, -1);\n }\n\n // add the middleware\n debug('use %s %s', path || '/', handle.name || 'anonymous');\n this.stack.push({ route: path, handle: handle });\n\n return this;\n};\n\n/**\n * Handle server requests, punting them down\n * the middleware stack.\n *\n * @private\n */\n\nproto.handle = function handle(req, res, out) {\n var index = 0;\n var protohost = getProtohost(req.url) || '';\n var removed = '';\n var slashAdded = false;\n var stack = this.stack;\n\n // final function handler\n var done = out || finalhandler(req, res, {\n env: env,\n onerror: logerror\n });\n\n // store the original URL\n req.originalUrl = req.originalUrl || req.url;\n\n function next(err) {\n if (slashAdded) {\n req.url = req.url.substr(1);\n slashAdded = false;\n }\n\n if (removed.length !== 0) {\n req.url = protohost + removed + req.url.substr(protohost.length);\n removed = '';\n }\n\n // next callback\n var layer = stack[index++];\n\n // all done\n if (!layer) {\n defer(done, err);\n return;\n }\n\n // route data\n var path = parseUrl(req).pathname || '/';\n var route = layer.route;\n\n // skip this layer if the route doesn't match\n if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {\n return next(err);\n }\n\n // skip if route match does not border \"/\", \".\", or end\n var c = path.length > route.length && path[route.length];\n if (c && c !== '/' && c !== '.') {\n return next(err);\n }\n\n // trim off the part of the url that matches the route\n if (route.length !== 0 && route !== '/') {\n removed = route;\n req.url = protohost + req.url.substr(protohost.length + removed.length);\n\n // ensure leading slash\n if (!protohost && req.url[0] !== '/') {\n req.url = '/' + req.url;\n slashAdded = true;\n }\n }\n\n // call the layer handle\n call(layer.handle, route, err, req, res, next);\n }\n\n next();\n};\n\n/**\n * Listen for connections.\n *\n * This method takes the same arguments\n * as node's `http.Server#listen()`.\n *\n * HTTP and HTTPS:\n *\n * If you run your application both as HTTP\n * and HTTPS you may wrap them individually,\n * since your Connect \"server\" is really just\n * a JavaScript `Function`.\n *\n * var connect = require('connect')\n * , http = require('http')\n * , https = require('https');\n *\n * var app = connect();\n *\n * http.createServer(app).listen(80);\n * https.createServer(options, app).listen(443);\n *\n * @return {http.Server}\n * @api public\n */\n\nproto.listen = function listen() {\n var server = http.createServer(this);\n return server.listen.apply(server, arguments);\n};\n\n/**\n * Invoke a route handle.\n * @private\n */\n\nfunction call(handle, route, err, req, res, next) {\n var arity = handle.length;\n var error = err;\n var hasError = Boolean(err);\n\n debug('%s %s : %s', handle.name || '', route, req.originalUrl);\n\n try {\n if (hasError && arity === 4) {\n // error-handling middleware\n handle(err, req, res, next);\n return;\n } else if (!hasError && arity < 4) {\n // request-handling middleware\n handle(req, res, next);\n return;\n }\n } catch (e) {\n // replace the error\n error = e;\n }\n\n // continue\n next(error);\n}\n\n/**\n * Log error using console.error.\n *\n * @param {Error} err\n * @private\n */\n\nfunction logerror(err) {\n if (env !== 'test') console.error(err.stack || err.toString());\n}\n\n/**\n * Get get protocol + host for a URL.\n *\n * @param {string} url\n * @private\n */\n\nfunction getProtohost(url) {\n if (url.length === 0 || url[0] === '/') {\n return undefined;\n }\n\n var fqdnIndex = url.indexOf('://')\n\n return fqdnIndex !== -1 && url.lastIndexOf('?', fqdnIndex) === -1\n ? url.substr(0, url.indexOf('/', 3 + fqdnIndex))\n : undefined;\n}\n","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n","/*!\n * vary\n * Copyright(c) 2014-2017 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * Module exports.\n */\n\nmodule.exports = vary\nmodule.exports.append = append\n\n/**\n * RegExp to match field-name in RFC 7230 sec 3.2\n *\n * field-name = token\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n * / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n * / DIGIT / ALPHA\n * ; any VCHAR, except delimiters\n */\n\nvar FIELD_NAME_REGEXP = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/\n\n/**\n * Append a field to a vary header.\n *\n * @param {String} header\n * @param {String|Array} field\n * @return {String}\n * @public\n */\n\nfunction append (header, field) {\n if (typeof header !== 'string') {\n throw new TypeError('header argument is required')\n }\n\n if (!field) {\n throw new TypeError('field argument is required')\n }\n\n // get fields array\n var fields = !Array.isArray(field)\n ? parse(String(field))\n : field\n\n // assert on invalid field names\n for (var j = 0; j < fields.length; j++) {\n if (!FIELD_NAME_REGEXP.test(fields[j])) {\n throw new TypeError('field argument contains an invalid header name')\n }\n }\n\n // existing, unspecified vary\n if (header === '*') {\n return header\n }\n\n // enumerate current values\n var val = header\n var vals = parse(header.toLowerCase())\n\n // unspecified vary\n if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {\n return '*'\n }\n\n for (var i = 0; i < fields.length; i++) {\n var fld = fields[i].toLowerCase()\n\n // append value (case-preserving)\n if (vals.indexOf(fld) === -1) {\n vals.push(fld)\n val = val\n ? val + ', ' + fields[i]\n : fields[i]\n }\n }\n\n return val\n}\n\n/**\n * Parse a vary header into an array.\n *\n * @param {String} header\n * @return {Array}\n * @private\n */\n\nfunction parse (header) {\n var end = 0\n var list = []\n var start = 0\n\n // gather tokens\n for (var i = 0, len = header.length; i < len; i++) {\n switch (header.charCodeAt(i)) {\n case 0x20: /* */\n if (start === end) {\n start = end = i + 1\n }\n break\n case 0x2c: /* , */\n list.push(header.substring(start, end))\n start = end = i + 1\n break\n default:\n end = i + 1\n break\n }\n }\n\n // final token\n list.push(header.substring(start, end))\n\n return list\n}\n\n/**\n * Mark that a request is varied on a header field.\n *\n * @param {Object} res\n * @param {String|Array} field\n * @public\n */\n\nfunction vary (res, field) {\n if (!res || !res.getHeader || !res.setHeader) {\n // quack quack\n throw new TypeError('res argument is required')\n }\n\n // get existing header\n var val = res.getHeader('Vary') || ''\n var header = Array.isArray(val)\n ? val.join(', ')\n : String(val)\n\n // set new header\n if ((val = append(header, field))) {\n res.setHeader('Vary', val)\n }\n}\n","(function () {\n\n 'use strict';\n\n var assign = require('object-assign');\n var vary = require('vary');\n\n var defaults = {\n origin: '*',\n methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',\n preflightContinue: false,\n optionsSuccessStatus: 204\n };\n\n function isString(s) {\n return typeof s === 'string' || s instanceof String;\n }\n\n function isOriginAllowed(origin, allowedOrigin) {\n if (Array.isArray(allowedOrigin)) {\n for (var i = 0; i < allowedOrigin.length; ++i) {\n if (isOriginAllowed(origin, allowedOrigin[i])) {\n return true;\n }\n }\n return false;\n } else if (isString(allowedOrigin)) {\n return origin === allowedOrigin;\n } else if (allowedOrigin instanceof RegExp) {\n return allowedOrigin.test(origin);\n } else {\n return !!allowedOrigin;\n }\n }\n\n function configureOrigin(options, req) {\n var requestOrigin = req.headers.origin,\n headers = [],\n isAllowed;\n\n if (!options.origin || options.origin === '*') {\n // allow any origin\n headers.push([{\n key: 'Access-Control-Allow-Origin',\n value: '*'\n }]);\n } else if (isString(options.origin)) {\n // fixed origin\n headers.push([{\n key: 'Access-Control-Allow-Origin',\n value: options.origin\n }]);\n headers.push([{\n key: 'Vary',\n value: 'Origin'\n }]);\n } else {\n isAllowed = isOriginAllowed(requestOrigin, options.origin);\n // reflect origin\n headers.push([{\n key: 'Access-Control-Allow-Origin',\n value: isAllowed ? requestOrigin : false\n }]);\n headers.push([{\n key: 'Vary',\n value: 'Origin'\n }]);\n }\n\n return headers;\n }\n\n function configureMethods(options) {\n var methods = options.methods;\n if (methods.join) {\n methods = options.methods.join(','); // .methods is an array, so turn it into a string\n }\n return {\n key: 'Access-Control-Allow-Methods',\n value: methods\n };\n }\n\n function configureCredentials(options) {\n if (options.credentials === true) {\n return {\n key: 'Access-Control-Allow-Credentials',\n value: 'true'\n };\n }\n return null;\n }\n\n function configureAllowedHeaders(options, req) {\n var allowedHeaders = options.allowedHeaders || options.headers;\n var headers = [];\n\n if (!allowedHeaders) {\n allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers\n headers.push([{\n key: 'Vary',\n value: 'Access-Control-Request-Headers'\n }]);\n } else if (allowedHeaders.join) {\n allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string\n }\n if (allowedHeaders && allowedHeaders.length) {\n headers.push([{\n key: 'Access-Control-Allow-Headers',\n value: allowedHeaders\n }]);\n }\n\n return headers;\n }\n\n function configureExposedHeaders(options) {\n var headers = options.exposedHeaders;\n if (!headers) {\n return null;\n } else if (headers.join) {\n headers = headers.join(','); // .headers is an array, so turn it into a string\n }\n if (headers && headers.length) {\n return {\n key: 'Access-Control-Expose-Headers',\n value: headers\n };\n }\n return null;\n }\n\n function configureMaxAge(options) {\n var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString()\n if (maxAge && maxAge.length) {\n return {\n key: 'Access-Control-Max-Age',\n value: maxAge\n };\n }\n return null;\n }\n\n function applyHeaders(headers, res) {\n for (var i = 0, n = headers.length; i < n; i++) {\n var header = headers[i];\n if (header) {\n if (Array.isArray(header)) {\n applyHeaders(header, res);\n } else if (header.key === 'Vary' && header.value) {\n vary(res, header.value);\n } else if (header.value) {\n res.setHeader(header.key, header.value);\n }\n }\n }\n }\n\n function cors(options, req, res, next) {\n var headers = [],\n method = req.method && req.method.toUpperCase && req.method.toUpperCase();\n\n if (method === 'OPTIONS') {\n // preflight\n headers.push(configureOrigin(options, req));\n headers.push(configureCredentials(options, req));\n headers.push(configureMethods(options, req));\n headers.push(configureAllowedHeaders(options, req));\n headers.push(configureMaxAge(options, req));\n headers.push(configureExposedHeaders(options, req));\n applyHeaders(headers, res);\n\n if (options.preflightContinue) {\n next();\n } else {\n // Safari (and potentially other browsers) need content-length 0,\n // for 204 or they just hang waiting for a body\n res.statusCode = options.optionsSuccessStatus;\n res.setHeader('Content-Length', '0');\n res.end();\n }\n } else {\n // actual response\n headers.push(configureOrigin(options, req));\n headers.push(configureCredentials(options, req));\n headers.push(configureExposedHeaders(options, req));\n applyHeaders(headers, res);\n next();\n }\n }\n\n function middlewareWrapper(o) {\n // if options are static (either via defaults or custom options passed in), wrap in a function\n var optionsCallback = null;\n if (typeof o === 'function') {\n optionsCallback = o;\n } else {\n optionsCallback = function (req, cb) {\n cb(null, o);\n };\n }\n\n return function corsMiddleware(req, res, next) {\n optionsCallback(req, function (err, options) {\n if (err) {\n next(err);\n } else {\n var corsOptions = assign({}, defaults, options);\n var originCallback = null;\n if (corsOptions.origin && typeof corsOptions.origin === 'function') {\n originCallback = corsOptions.origin;\n } else if (corsOptions.origin) {\n originCallback = function (origin, cb) {\n cb(null, corsOptions.origin);\n };\n }\n\n if (originCallback) {\n originCallback(req.headers.origin, function (err2, origin) {\n if (err2 || !origin) {\n next(err2);\n } else {\n corsOptions.origin = origin;\n cors(corsOptions, req, res, next);\n }\n });\n } else {\n next();\n }\n }\n });\n };\n }\n\n // can pass either an options hash, an options delegate, or nothing\n module.exports = middlewareWrapper;\n\n}());\n","'use strict';\n\nconst fs = require('fs');\nconst { Readable } = require('stream');\nconst sysPath = require('path');\nconst { promisify } = require('util');\nconst picomatch = require('picomatch');\n\nconst readdir = promisify(fs.readdir);\nconst stat = promisify(fs.stat);\nconst lstat = promisify(fs.lstat);\nconst realpath = promisify(fs.realpath);\n\n/**\n * @typedef {Object} EntryInfo\n * @property {String} path\n * @property {String} fullPath\n * @property {fs.Stats=} stats\n * @property {fs.Dirent=} dirent\n * @property {String} basename\n */\n\nconst BANG = '!';\nconst RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';\nconst NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);\nconst FILE_TYPE = 'files';\nconst DIR_TYPE = 'directories';\nconst FILE_DIR_TYPE = 'files_directories';\nconst EVERYTHING_TYPE = 'all';\nconst ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];\n\nconst isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);\nconst [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));\nconst wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));\n\nconst normalizeFilter = filter => {\n if (filter === undefined) return;\n if (typeof filter === 'function') return filter;\n\n if (typeof filter === 'string') {\n const glob = picomatch(filter.trim());\n return entry => glob(entry.basename);\n }\n\n if (Array.isArray(filter)) {\n const positive = [];\n const negative = [];\n for (const item of filter) {\n const trimmed = item.trim();\n if (trimmed.charAt(0) === BANG) {\n negative.push(picomatch(trimmed.slice(1)));\n } else {\n positive.push(picomatch(trimmed));\n }\n }\n\n if (negative.length > 0) {\n if (positive.length > 0) {\n return entry =>\n positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));\n }\n return entry => !negative.some(f => f(entry.basename));\n }\n return entry => positive.some(f => f(entry.basename));\n }\n};\n\nclass ReaddirpStream extends Readable {\n static get defaultOptions() {\n return {\n root: '.',\n /* eslint-disable no-unused-vars */\n fileFilter: (path) => true,\n directoryFilter: (path) => true,\n /* eslint-enable no-unused-vars */\n type: FILE_TYPE,\n lstat: false,\n depth: 2147483648,\n alwaysStat: false\n };\n }\n\n constructor(options = {}) {\n super({\n objectMode: true,\n autoDestroy: true,\n highWaterMark: options.highWaterMark || 4096\n });\n const opts = { ...ReaddirpStream.defaultOptions, ...options };\n const { root, type } = opts;\n\n this._fileFilter = normalizeFilter(opts.fileFilter);\n this._directoryFilter = normalizeFilter(opts.directoryFilter);\n\n const statMethod = opts.lstat ? lstat : stat;\n // Use bigint stats if it's windows and stat() supports options (node 10+).\n if (wantBigintFsStats) {\n this._stat = path => statMethod(path, { bigint: true });\n } else {\n this._stat = statMethod;\n }\n\n this._maxDepth = opts.depth;\n this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);\n this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);\n this._wantsEverything = type === EVERYTHING_TYPE;\n this._root = sysPath.resolve(root);\n this._isDirent = ('Dirent' in fs) && !opts.alwaysStat;\n this._statsProp = this._isDirent ? 'dirent' : 'stats';\n this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };\n\n // Launch stream with one parent, the root dir.\n this.parents = [this._exploreDir(root, 1)];\n this.reading = false;\n this.parent = undefined;\n }\n\n async _read(batch) {\n if (this.reading) return;\n this.reading = true;\n\n try {\n while (!this.destroyed && batch > 0) {\n const { path, depth, files = [] } = this.parent || {};\n\n if (files.length > 0) {\n const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));\n for (const entry of await Promise.all(slice)) {\n if (this.destroyed) return;\n\n const entryType = await this._getEntryType(entry);\n if (entryType === 'directory' && this._directoryFilter(entry)) {\n if (depth <= this._maxDepth) {\n this.parents.push(this._exploreDir(entry.fullPath, depth + 1));\n }\n\n if (this._wantsDir) {\n this.push(entry);\n batch--;\n }\n } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {\n if (this._wantsFile) {\n this.push(entry);\n batch--;\n }\n }\n }\n } else {\n const parent = this.parents.pop();\n if (!parent) {\n this.push(null);\n break;\n }\n this.parent = await parent;\n if (this.destroyed) return;\n }\n }\n } catch (error) {\n this.destroy(error);\n } finally {\n this.reading = false;\n }\n }\n\n async _exploreDir(path, depth) {\n let files;\n try {\n files = await readdir(path, this._rdOptions);\n } catch (error) {\n this._onError(error);\n }\n return { files, depth, path };\n }\n\n async _formatEntry(dirent, path) {\n let entry;\n try {\n const basename = this._isDirent ? dirent.name : dirent;\n const fullPath = sysPath.resolve(sysPath.join(path, basename));\n entry = { path: sysPath.relative(this._root, fullPath), fullPath, basename };\n entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);\n } catch (err) {\n this._onError(err);\n }\n return entry;\n }\n\n _onError(err) {\n if (isNormalFlowError(err) && !this.destroyed) {\n this.emit('warn', err);\n } else {\n this.destroy(err);\n }\n }\n\n async _getEntryType(entry) {\n // entry may be undefined, because a warning or an error were emitted\n // and the statsProp is undefined\n const stats = entry && entry[this._statsProp];\n if (!stats) {\n return;\n }\n if (stats.isFile()) {\n return 'file';\n }\n if (stats.isDirectory()) {\n return 'directory';\n }\n if (stats && stats.isSymbolicLink()) {\n const full = entry.fullPath;\n try {\n const entryRealPath = await realpath(full);\n const entryRealPathStats = await lstat(entryRealPath);\n if (entryRealPathStats.isFile()) {\n return 'file';\n }\n if (entryRealPathStats.isDirectory()) {\n const len = entryRealPath.length;\n if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath.sep) {\n const recursiveError = new Error(\n `Circular symlink detected: \"${full}\" points to \"${entryRealPath}\"`\n );\n recursiveError.code = RECURSIVE_ERROR_CODE;\n return this._onError(recursiveError);\n }\n return 'directory';\n }\n } catch (error) {\n this._onError(error);\n }\n }\n }\n\n _includeAsFile(entry) {\n const stats = entry && entry[this._statsProp];\n\n return stats && this._wantsEverything && !stats.isDirectory();\n }\n}\n\n/**\n * @typedef {Object} ReaddirpArguments\n * @property {Function=} fileFilter\n * @property {Function=} directoryFilter\n * @property {String=} type\n * @property {Number=} depth\n * @property {String=} root\n * @property {Boolean=} lstat\n * @property {Boolean=} bigint\n */\n\n/**\n * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.\n * @param {String} root Root directory\n * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth\n */\nconst readdirp = (root, options = {}) => {\n let type = options.entryType || options.type;\n if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility\n if (type) options.type = type;\n if (!root) {\n throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');\n } else if (typeof root !== 'string') {\n throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');\n } else if (type && !ALL_TYPES.includes(type)) {\n throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);\n }\n\n options.root = root;\n return new ReaddirpStream(options);\n};\n\nconst readdirpPromise = (root, options = {}) => {\n return new Promise((resolve, reject) => {\n const files = [];\n readdirp(root, options)\n .on('data', entry => files.push(entry))\n .on('end', () => resolve(files))\n .on('error', error => reject(error));\n });\n};\n\nreaddirp.promise = readdirpPromise;\nreaddirp.ReaddirpStream = ReaddirpStream;\nreaddirp.default = readdirp;\n\nmodule.exports = readdirp;\n","/*!\n * normalize-path \n *\n * Copyright (c) 2014-2018, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nmodule.exports = function(path, stripTrailing) {\n if (typeof path !== 'string') {\n throw new TypeError('expected path to be a string');\n }\n\n if (path === '\\\\' || path === '/') return '/';\n\n var len = path.length;\n if (len <= 1) return path;\n\n // ensure that win32 namespaces has two leading slashes, so that the path is\n // handled properly by the win32 version of path.parse() after being normalized\n // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces\n var prefix = '';\n if (len > 4 && path[3] === '\\\\') {\n var ch = path[2];\n if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\\\\\') {\n path = path.slice(2);\n prefix = '//';\n }\n }\n\n var segs = path.split(/[/\\\\]+/);\n if (stripTrailing !== false && segs[segs.length - 1] === '') {\n segs.pop();\n }\n return prefix + segs.join('/');\n};\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", { value: true });\n\nconst picomatch = require('picomatch');\nconst normalizePath = require('normalize-path');\n\n/**\n * @typedef {(testString: string) => boolean} AnymatchFn\n * @typedef {string|RegExp|AnymatchFn} AnymatchPattern\n * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher\n */\nconst BANG = '!';\nconst DEFAULT_OPTIONS = {returnIndex: false};\nconst arrify = (item) => Array.isArray(item) ? item : [item];\n\n/**\n * @param {AnymatchPattern} matcher\n * @param {object} options\n * @returns {AnymatchFn}\n */\nconst createPattern = (matcher, options) => {\n if (typeof matcher === 'function') {\n return matcher;\n }\n if (typeof matcher === 'string') {\n const glob = picomatch(matcher, options);\n return (string) => matcher === string || glob(string);\n }\n if (matcher instanceof RegExp) {\n return (string) => matcher.test(string);\n }\n return (string) => false;\n};\n\n/**\n * @param {Array} patterns\n * @param {Array} negPatterns\n * @param {String|Array} args\n * @param {Boolean} returnIndex\n * @returns {boolean|number}\n */\nconst matchPatterns = (patterns, negPatterns, args, returnIndex) => {\n const isList = Array.isArray(args);\n const _path = isList ? args[0] : args;\n if (!isList && typeof _path !== 'string') {\n throw new TypeError('anymatch: second argument must be a string: got ' +\n Object.prototype.toString.call(_path))\n }\n const path = normalizePath(_path);\n\n for (let index = 0; index < negPatterns.length; index++) {\n const nglob = negPatterns[index];\n if (nglob(path)) {\n return returnIndex ? -1 : false;\n }\n }\n\n const applied = isList && [path].concat(args.slice(1));\n for (let index = 0; index < patterns.length; index++) {\n const pattern = patterns[index];\n if (isList ? pattern(...applied) : pattern(path)) {\n return returnIndex ? index : true;\n }\n }\n\n return returnIndex ? -1 : false;\n};\n\n/**\n * @param {AnymatchMatcher} matchers\n * @param {Array|string} testString\n * @param {object} options\n * @returns {boolean|number|Function}\n */\nconst anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => {\n if (matchers == null) {\n throw new TypeError('anymatch: specify first argument');\n }\n const opts = typeof options === 'boolean' ? {returnIndex: options} : options;\n const returnIndex = opts.returnIndex || false;\n\n // Early cache for matchers.\n const mtchers = arrify(matchers);\n const negatedGlobs = mtchers\n .filter(item => typeof item === 'string' && item.charAt(0) === BANG)\n .map(item => item.slice(1))\n .map(item => picomatch(item, opts));\n const patterns = mtchers\n .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG))\n .map(matcher => createPattern(matcher, opts));\n\n if (testString == null) {\n return (testString, ri = false) => {\n const returnIndex = typeof ri === 'boolean' ? ri : false;\n return matchPatterns(patterns, negatedGlobs, testString, returnIndex);\n }\n }\n\n return matchPatterns(patterns, negatedGlobs, testString, returnIndex);\n};\n\nanymatch.default = anymatch;\nmodule.exports = anymatch;\n","module.exports = require('./binary-extensions.json');\n","'use strict';\nconst path = require('path');\nconst binaryExtensions = require('binary-extensions');\n\nconst extensions = new Set(binaryExtensions);\n\nmodule.exports = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase());\n","'use strict';\n\nconst {sep} = require('path');\nconst {platform} = process;\nconst os = require('os');\n\nexports.EV_ALL = 'all';\nexports.EV_READY = 'ready';\nexports.EV_ADD = 'add';\nexports.EV_CHANGE = 'change';\nexports.EV_ADD_DIR = 'addDir';\nexports.EV_UNLINK = 'unlink';\nexports.EV_UNLINK_DIR = 'unlinkDir';\nexports.EV_RAW = 'raw';\nexports.EV_ERROR = 'error';\n\nexports.STR_DATA = 'data';\nexports.STR_END = 'end';\nexports.STR_CLOSE = 'close';\n\nexports.FSEVENT_CREATED = 'created';\nexports.FSEVENT_MODIFIED = 'modified';\nexports.FSEVENT_DELETED = 'deleted';\nexports.FSEVENT_MOVED = 'moved';\nexports.FSEVENT_CLONED = 'cloned';\nexports.FSEVENT_UNKNOWN = 'unknown';\nexports.FSEVENT_TYPE_FILE = 'file';\nexports.FSEVENT_TYPE_DIRECTORY = 'directory';\nexports.FSEVENT_TYPE_SYMLINK = 'symlink';\n\nexports.KEY_LISTENERS = 'listeners';\nexports.KEY_ERR = 'errHandlers';\nexports.KEY_RAW = 'rawEmitters';\nexports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];\n\nexports.DOT_SLASH = `.${sep}`;\n\nexports.BACK_SLASH_RE = /\\\\/g;\nexports.DOUBLE_SLASH_RE = /\\/\\//;\nexports.SLASH_OR_BACK_SLASH_RE = /[/\\\\]/;\nexports.DOT_RE = /\\..*\\.(sw[px])$|~$|\\.subl.*\\.tmp/;\nexports.REPLACER_RE = /^\\.[/\\\\]/;\n\nexports.SLASH = '/';\nexports.SLASH_SLASH = '//';\nexports.BRACE_START = '{';\nexports.BANG = '!';\nexports.ONE_DOT = '.';\nexports.TWO_DOTS = '..';\nexports.STAR = '*';\nexports.GLOBSTAR = '**';\nexports.ROOT_GLOBSTAR = '/**/*';\nexports.SLASH_GLOBSTAR = '/**';\nexports.DIR_SUFFIX = 'Dir';\nexports.ANYMATCH_OPTS = {dot: true};\nexports.STRING_TYPE = 'string';\nexports.FUNCTION_TYPE = 'function';\nexports.EMPTY_STR = '';\nexports.EMPTY_FN = () => {};\nexports.IDENTITY_FN = val => val;\n\nexports.isWindows = platform === 'win32';\nexports.isMacos = platform === 'darwin';\nexports.isLinux = platform === 'linux';\nexports.isIBMi = os.type() === 'OS400';\n","'use strict';\n\nconst fs = require('fs');\nconst sysPath = require('path');\nconst { promisify } = require('util');\nconst isBinaryPath = require('is-binary-path');\nconst {\n isWindows,\n isLinux,\n EMPTY_FN,\n EMPTY_STR,\n KEY_LISTENERS,\n KEY_ERR,\n KEY_RAW,\n HANDLER_KEYS,\n EV_CHANGE,\n EV_ADD,\n EV_ADD_DIR,\n EV_ERROR,\n STR_DATA,\n STR_END,\n BRACE_START,\n STAR\n} = require('./constants');\n\nconst THROTTLE_MODE_WATCH = 'watch';\n\nconst open = promisify(fs.open);\nconst stat = promisify(fs.stat);\nconst lstat = promisify(fs.lstat);\nconst close = promisify(fs.close);\nconst fsrealpath = promisify(fs.realpath);\n\nconst statMethods = { lstat, stat };\n\n// TODO: emit errors properly. Example: EMFILE on Macos.\nconst foreach = (val, fn) => {\n if (val instanceof Set) {\n val.forEach(fn);\n } else {\n fn(val);\n }\n};\n\nconst addAndConvert = (main, prop, item) => {\n let container = main[prop];\n if (!(container instanceof Set)) {\n main[prop] = container = new Set([container]);\n }\n container.add(item);\n};\n\nconst clearItem = cont => key => {\n const set = cont[key];\n if (set instanceof Set) {\n set.clear();\n } else {\n delete cont[key];\n }\n};\n\nconst delFromSet = (main, prop, item) => {\n const container = main[prop];\n if (container instanceof Set) {\n container.delete(item);\n } else if (container === item) {\n delete main[prop];\n }\n};\n\nconst isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;\n\n/**\n * @typedef {String} Path\n */\n\n// fs_watch helpers\n\n// object to hold per-process fs_watch instances\n// (may be shared across chokidar FSWatcher instances)\n\n/**\n * @typedef {Object} FsWatchContainer\n * @property {Set} listeners\n * @property {Set} errHandlers\n * @property {Set} rawEmitters\n * @property {fs.FSWatcher=} watcher\n * @property {Boolean=} watcherUnusable\n */\n\n/**\n * @type {Map}\n */\nconst FsWatchInstances = new Map();\n\n/**\n * Instantiates the fs_watch interface\n * @param {String} path to be watched\n * @param {Object} options to be passed to fs_watch\n * @param {Function} listener main event handler\n * @param {Function} errHandler emits info about errors\n * @param {Function} emitRaw emits raw event data\n * @returns {fs.FSWatcher} new fsevents instance\n */\nfunction createFsWatchInstance(path, options, listener, errHandler, emitRaw) {\n const handleEvent = (rawEvent, evPath) => {\n listener(path);\n emitRaw(rawEvent, evPath, {watchedPath: path});\n\n // emit based on events occurring for files from a directory's watcher in\n // case the file's watcher misses it (and rely on throttling to de-dupe)\n if (evPath && path !== evPath) {\n fsWatchBroadcast(\n sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath)\n );\n }\n };\n try {\n return fs.watch(path, options, handleEvent);\n } catch (error) {\n errHandler(error);\n }\n}\n\n/**\n * Helper for passing fs_watch event data to a collection of listeners\n * @param {Path} fullPath absolute path bound to fs_watch instance\n * @param {String} type listener type\n * @param {*=} val1 arguments to be passed to listeners\n * @param {*=} val2\n * @param {*=} val3\n */\nconst fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {\n const cont = FsWatchInstances.get(fullPath);\n if (!cont) return;\n foreach(cont[type], (listener) => {\n listener(val1, val2, val3);\n });\n};\n\n/**\n * Instantiates the fs_watch interface or binds listeners\n * to an existing one covering the same file system entry\n * @param {String} path\n * @param {String} fullPath absolute path\n * @param {Object} options to be passed to fs_watch\n * @param {Object} handlers container for event listener functions\n */\nconst setFsWatchListener = (path, fullPath, options, handlers) => {\n const {listener, errHandler, rawEmitter} = handlers;\n let cont = FsWatchInstances.get(fullPath);\n\n /** @type {fs.FSWatcher=} */\n let watcher;\n if (!options.persistent) {\n watcher = createFsWatchInstance(\n path, options, listener, errHandler, rawEmitter\n );\n return watcher.close.bind(watcher);\n }\n if (cont) {\n addAndConvert(cont, KEY_LISTENERS, listener);\n addAndConvert(cont, KEY_ERR, errHandler);\n addAndConvert(cont, KEY_RAW, rawEmitter);\n } else {\n watcher = createFsWatchInstance(\n path,\n options,\n fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),\n errHandler, // no need to use broadcast here\n fsWatchBroadcast.bind(null, fullPath, KEY_RAW)\n );\n if (!watcher) return;\n watcher.on(EV_ERROR, async (error) => {\n const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);\n cont.watcherUnusable = true; // documented since Node 10.4.1\n // Workaround for https://github.com/joyent/node/issues/4337\n if (isWindows && error.code === 'EPERM') {\n try {\n const fd = await open(path, 'r');\n await close(fd);\n broadcastErr(error);\n } catch (err) {}\n } else {\n broadcastErr(error);\n }\n });\n cont = {\n listeners: listener,\n errHandlers: errHandler,\n rawEmitters: rawEmitter,\n watcher\n };\n FsWatchInstances.set(fullPath, cont);\n }\n // const index = cont.listeners.indexOf(listener);\n\n // removes this instance's listeners and closes the underlying fs_watch\n // instance if there are no more listeners left\n return () => {\n delFromSet(cont, KEY_LISTENERS, listener);\n delFromSet(cont, KEY_ERR, errHandler);\n delFromSet(cont, KEY_RAW, rawEmitter);\n if (isEmptySet(cont.listeners)) {\n // Check to protect against issue gh-730.\n // if (cont.watcherUnusable) {\n cont.watcher.close();\n // }\n FsWatchInstances.delete(fullPath);\n HANDLER_KEYS.forEach(clearItem(cont));\n cont.watcher = undefined;\n Object.freeze(cont);\n }\n };\n};\n\n// fs_watchFile helpers\n\n// object to hold per-process fs_watchFile instances\n// (may be shared across chokidar FSWatcher instances)\nconst FsWatchFileInstances = new Map();\n\n/**\n * Instantiates the fs_watchFile interface or binds listeners\n * to an existing one covering the same file system entry\n * @param {String} path to be watched\n * @param {String} fullPath absolute path\n * @param {Object} options options to be passed to fs_watchFile\n * @param {Object} handlers container for event listener functions\n * @returns {Function} closer\n */\nconst setFsWatchFileListener = (path, fullPath, options, handlers) => {\n const {listener, rawEmitter} = handlers;\n let cont = FsWatchFileInstances.get(fullPath);\n\n /* eslint-disable no-unused-vars, prefer-destructuring */\n let listeners = new Set();\n let rawEmitters = new Set();\n\n const copts = cont && cont.options;\n if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {\n // \"Upgrade\" the watcher to persistence or a quicker interval.\n // This creates some unlikely edge case issues if the user mixes\n // settings in a very weird way, but solving for those cases\n // doesn't seem worthwhile for the added complexity.\n listeners = cont.listeners;\n rawEmitters = cont.rawEmitters;\n fs.unwatchFile(fullPath);\n cont = undefined;\n }\n\n /* eslint-enable no-unused-vars, prefer-destructuring */\n\n if (cont) {\n addAndConvert(cont, KEY_LISTENERS, listener);\n addAndConvert(cont, KEY_RAW, rawEmitter);\n } else {\n // TODO\n // listeners.add(listener);\n // rawEmitters.add(rawEmitter);\n cont = {\n listeners: listener,\n rawEmitters: rawEmitter,\n options,\n watcher: fs.watchFile(fullPath, options, (curr, prev) => {\n foreach(cont.rawEmitters, (rawEmitter) => {\n rawEmitter(EV_CHANGE, fullPath, {curr, prev});\n });\n const currmtime = curr.mtimeMs;\n if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {\n foreach(cont.listeners, (listener) => listener(path, curr));\n }\n })\n };\n FsWatchFileInstances.set(fullPath, cont);\n }\n // const index = cont.listeners.indexOf(listener);\n\n // Removes this instance's listeners and closes the underlying fs_watchFile\n // instance if there are no more listeners left.\n return () => {\n delFromSet(cont, KEY_LISTENERS, listener);\n delFromSet(cont, KEY_RAW, rawEmitter);\n if (isEmptySet(cont.listeners)) {\n FsWatchFileInstances.delete(fullPath);\n fs.unwatchFile(fullPath);\n cont.options = cont.watcher = undefined;\n Object.freeze(cont);\n }\n };\n};\n\n/**\n * @mixin\n */\nclass NodeFsHandler {\n\n/**\n * @param {import(\"../index\").FSWatcher} fsW\n */\nconstructor(fsW) {\n this.fsw = fsW;\n this._boundHandleError = (error) => fsW._handleError(error);\n}\n\n/**\n * Watch file for changes with fs_watchFile or fs_watch.\n * @param {String} path to file or dir\n * @param {Function} listener on fs change\n * @returns {Function} closer for the watcher instance\n */\n_watchWithNodeFs(path, listener) {\n const opts = this.fsw.options;\n const directory = sysPath.dirname(path);\n const basename = sysPath.basename(path);\n const parent = this.fsw._getWatchedDir(directory);\n parent.add(basename);\n const absolutePath = sysPath.resolve(path);\n const options = {persistent: opts.persistent};\n if (!listener) listener = EMPTY_FN;\n\n let closer;\n if (opts.usePolling) {\n options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?\n opts.binaryInterval : opts.interval;\n closer = setFsWatchFileListener(path, absolutePath, options, {\n listener,\n rawEmitter: this.fsw._emitRaw\n });\n } else {\n closer = setFsWatchListener(path, absolutePath, options, {\n listener,\n errHandler: this._boundHandleError,\n rawEmitter: this.fsw._emitRaw\n });\n }\n return closer;\n}\n\n/**\n * Watch a file and emit add event if warranted.\n * @param {Path} file Path\n * @param {fs.Stats} stats result of fs_stat\n * @param {Boolean} initialAdd was the file added at watch instantiation?\n * @returns {Function} closer for the watcher instance\n */\n_handleFile(file, stats, initialAdd) {\n if (this.fsw.closed) {\n return;\n }\n const dirname = sysPath.dirname(file);\n const basename = sysPath.basename(file);\n const parent = this.fsw._getWatchedDir(dirname);\n // stats is always present\n let prevStats = stats;\n\n // if the file is already being watched, do nothing\n if (parent.has(basename)) return;\n\n const listener = async (path, newStats) => {\n if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;\n if (!newStats || newStats.mtimeMs === 0) {\n try {\n const newStats = await stat(file);\n if (this.fsw.closed) return;\n // Check that change event was not fired because of changed only accessTime.\n const at = newStats.atimeMs;\n const mt = newStats.mtimeMs;\n if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n this.fsw._emit(EV_CHANGE, file, newStats);\n }\n if (isLinux && prevStats.ino !== newStats.ino) {\n this.fsw._closeFile(path)\n prevStats = newStats;\n this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));\n } else {\n prevStats = newStats;\n }\n } catch (error) {\n // Fix issues where mtime is null but file is still present\n this.fsw._remove(dirname, basename);\n }\n // add is about to be emitted if file not already tracked in parent\n } else if (parent.has(basename)) {\n // Check that change event was not fired because of changed only accessTime.\n const at = newStats.atimeMs;\n const mt = newStats.mtimeMs;\n if (!at || at <= mt || mt !== prevStats.mtimeMs) {\n this.fsw._emit(EV_CHANGE, file, newStats);\n }\n prevStats = newStats;\n }\n }\n // kick off the watcher\n const closer = this._watchWithNodeFs(file, listener);\n\n // emit an add event if we're supposed to\n if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {\n if (!this.fsw._throttle(EV_ADD, file, 0)) return;\n this.fsw._emit(EV_ADD, file, stats);\n }\n\n return closer;\n}\n\n/**\n * Handle symlinks encountered while reading a dir.\n * @param {Object} entry returned by readdirp\n * @param {String} directory path of dir being read\n * @param {String} path of this item\n * @param {String} item basename of this item\n * @returns {Promise} true if no more processing is needed for this entry.\n */\nasync _handleSymlink(entry, directory, path, item) {\n if (this.fsw.closed) {\n return;\n }\n const full = entry.fullPath;\n const dir = this.fsw._getWatchedDir(directory);\n\n if (!this.fsw.options.followSymlinks) {\n // watch symlink directly (don't follow) and detect changes\n this.fsw._incrReadyCount();\n const linkPath = await fsrealpath(path);\n if (this.fsw.closed) return;\n if (dir.has(item)) {\n if (this.fsw._symlinkPaths.get(full) !== linkPath) {\n this.fsw._symlinkPaths.set(full, linkPath);\n this.fsw._emit(EV_CHANGE, path, entry.stats);\n }\n } else {\n dir.add(item);\n this.fsw._symlinkPaths.set(full, linkPath);\n this.fsw._emit(EV_ADD, path, entry.stats);\n }\n this.fsw._emitReady();\n return true;\n }\n\n // don't follow the same symlink more than once\n if (this.fsw._symlinkPaths.has(full)) {\n return true;\n }\n\n this.fsw._symlinkPaths.set(full, true);\n}\n\n_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {\n // Normalize the directory name on Windows\n directory = sysPath.join(directory, EMPTY_STR);\n\n if (!wh.hasGlob) {\n throttler = this.fsw._throttle('readdir', directory, 1000);\n if (!throttler) return;\n }\n\n const previous = this.fsw._getWatchedDir(wh.path);\n const current = new Set();\n\n let stream = this.fsw._readdirp(directory, {\n fileFilter: entry => wh.filterPath(entry),\n directoryFilter: entry => wh.filterDir(entry),\n depth: 0\n }).on(STR_DATA, async (entry) => {\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n const item = entry.path;\n let path = sysPath.join(directory, item);\n current.add(item);\n\n if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {\n return;\n }\n\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n // Files that present in current directory snapshot\n // but absent in previous are added to watch list and\n // emit `add` event.\n if (item === target || !target && !previous.has(item)) {\n this.fsw._incrReadyCount();\n\n // ensure relativeness of path is preserved in case of watcher reuse\n path = sysPath.join(dir, sysPath.relative(dir, path));\n\n this._addToNodeFs(path, initialAdd, wh, depth + 1);\n }\n }).on(EV_ERROR, this._boundHandleError);\n\n return new Promise(resolve =>\n stream.once(STR_END, () => {\n if (this.fsw.closed) {\n stream = undefined;\n return;\n }\n const wasThrottled = throttler ? throttler.clear() : false;\n\n resolve();\n\n // Files that absent in current directory snapshot\n // but present in previous emit `remove` event\n // and are removed from @watched[directory].\n previous.getChildren().filter((item) => {\n return item !== directory &&\n !current.has(item) &&\n // in case of intersecting globs;\n // a path may have been filtered out of this readdir, but\n // shouldn't be removed because it matches a different glob\n (!wh.hasGlob || wh.filterPath({\n fullPath: sysPath.resolve(directory, item)\n }));\n }).forEach((item) => {\n this.fsw._remove(directory, item);\n });\n\n stream = undefined;\n\n // one more time for any missed in case changes came in extremely quickly\n if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);\n })\n );\n}\n\n/**\n * Read directory to add / remove files from `@watched` list and re-read it on change.\n * @param {String} dir fs path\n * @param {fs.Stats} stats\n * @param {Boolean} initialAdd\n * @param {Number} depth relative to user-supplied path\n * @param {String} target child path targeted for watch\n * @param {Object} wh Common watch helpers for this path\n * @param {String} realpath\n * @returns {Promise} closer for the watcher instance.\n */\nasync _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {\n const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));\n const tracked = parentDir.has(sysPath.basename(dir));\n if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {\n if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats);\n }\n\n // ensure dir is tracked (harmless if redundant)\n parentDir.add(sysPath.basename(dir));\n this.fsw._getWatchedDir(dir);\n let throttler;\n let closer;\n\n const oDepth = this.fsw.options.depth;\n if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {\n if (!target) {\n await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);\n if (this.fsw.closed) return;\n }\n\n closer = this._watchWithNodeFs(dir, (dirPath, stats) => {\n // if current directory is removed, do nothing\n if (stats && stats.mtimeMs === 0) return;\n\n this._handleRead(dirPath, false, wh, target, dir, depth, throttler);\n });\n }\n return closer;\n}\n\n/**\n * Handle added file, directory, or glob pattern.\n * Delegates call to _handleFile / _handleDir after checks.\n * @param {String} path to file or ir\n * @param {Boolean} initialAdd was the file added at watch instantiation?\n * @param {Object} priorWh depth relative to user-supplied path\n * @param {Number} depth Child path actually targeted for watch\n * @param {String=} target Child path actually targeted for watch\n * @returns {Promise}\n */\nasync _addToNodeFs(path, initialAdd, priorWh, depth, target) {\n const ready = this.fsw._emitReady;\n if (this.fsw._isIgnored(path) || this.fsw.closed) {\n ready();\n return false;\n }\n\n const wh = this.fsw._getWatchHelpers(path, depth);\n if (!wh.hasGlob && priorWh) {\n wh.hasGlob = priorWh.hasGlob;\n wh.globFilter = priorWh.globFilter;\n wh.filterPath = entry => priorWh.filterPath(entry);\n wh.filterDir = entry => priorWh.filterDir(entry);\n }\n\n // evaluate what is at the path we're being asked to watch\n try {\n const stats = await statMethods[wh.statMethod](wh.watchPath);\n if (this.fsw.closed) return;\n if (this.fsw._isIgnored(wh.watchPath, stats)) {\n ready();\n return false;\n }\n\n const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START);\n let closer;\n if (stats.isDirectory()) {\n const absPath = sysPath.resolve(path);\n const targetPath = follow ? await fsrealpath(path) : path;\n if (this.fsw.closed) return;\n closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);\n if (this.fsw.closed) return;\n // preserve this symlink's target path\n if (absPath !== targetPath && targetPath !== undefined) {\n this.fsw._symlinkPaths.set(absPath, targetPath);\n }\n } else if (stats.isSymbolicLink()) {\n const targetPath = follow ? await fsrealpath(path) : path;\n if (this.fsw.closed) return;\n const parent = sysPath.dirname(wh.watchPath);\n this.fsw._getWatchedDir(parent).add(wh.watchPath);\n this.fsw._emit(EV_ADD, wh.watchPath, stats);\n closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);\n if (this.fsw.closed) return;\n\n // preserve this symlink's target path\n if (targetPath !== undefined) {\n this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);\n }\n } else {\n closer = this._handleFile(wh.watchPath, stats, initialAdd);\n }\n ready();\n\n this.fsw._addPathCloser(path, closer);\n return false;\n\n } catch (error) {\n if (this.fsw._handleError(error)) {\n ready();\n return path;\n }\n }\n}\n\n}\n\nmodule.exports = NodeFsHandler;\n","'use strict';\n\nconst fs = require('fs');\nconst sysPath = require('path');\nconst { promisify } = require('util');\n\nlet fsevents;\ntry {\n fsevents = require('fsevents');\n} catch (error) {\n if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);\n}\n\nif (fsevents) {\n // TODO: real check\n const mtch = process.version.match(/v(\\d+)\\.(\\d+)/);\n if (mtch && mtch[1] && mtch[2]) {\n const maj = Number.parseInt(mtch[1], 10);\n const min = Number.parseInt(mtch[2], 10);\n if (maj === 8 && min < 16) {\n fsevents = undefined;\n }\n }\n}\n\nconst {\n EV_ADD,\n EV_CHANGE,\n EV_ADD_DIR,\n EV_UNLINK,\n EV_ERROR,\n STR_DATA,\n STR_END,\n FSEVENT_CREATED,\n FSEVENT_MODIFIED,\n FSEVENT_DELETED,\n FSEVENT_MOVED,\n // FSEVENT_CLONED,\n FSEVENT_UNKNOWN,\n FSEVENT_TYPE_FILE,\n FSEVENT_TYPE_DIRECTORY,\n FSEVENT_TYPE_SYMLINK,\n\n ROOT_GLOBSTAR,\n DIR_SUFFIX,\n DOT_SLASH,\n FUNCTION_TYPE,\n EMPTY_FN,\n IDENTITY_FN\n} = require('./constants');\n\nconst Depth = (value) => isNaN(value) ? {} : {depth: value};\n\nconst stat = promisify(fs.stat);\nconst lstat = promisify(fs.lstat);\nconst realpath = promisify(fs.realpath);\n\nconst statMethods = { stat, lstat };\n\n/**\n * @typedef {String} Path\n */\n\n/**\n * @typedef {Object} FsEventsWatchContainer\n * @property {Set} listeners\n * @property {Function} rawEmitter\n * @property {{stop: Function}} watcher\n */\n\n// fsevents instance helper functions\n/**\n * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)\n * @type {Map}\n */\nconst FSEventsWatchers = new Map();\n\n// Threshold of duplicate path prefixes at which to start\n// consolidating going forward\nconst consolidateThreshhold = 10;\n\nconst wrongEventFlags = new Set([\n 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912\n]);\n\n/**\n * Instantiates the fsevents interface\n * @param {Path} path path to be watched\n * @param {Function} callback called when fsevents is bound and ready\n * @returns {{stop: Function}} new fsevents instance\n */\nconst createFSEventsInstance = (path, callback) => {\n const stop = fsevents.watch(path, callback);\n return {stop};\n};\n\n/**\n * Instantiates the fsevents interface or binds listeners to an existing one covering\n * the same file tree.\n * @param {Path} path - to be watched\n * @param {Path} realPath - real path for symlinks\n * @param {Function} listener - called when fsevents emits events\n * @param {Function} rawEmitter - passes data to listeners of the 'raw' event\n * @returns {Function} closer\n */\nfunction setFSEventsListener(path, realPath, listener, rawEmitter) {\n let watchPath = sysPath.extname(realPath) ? sysPath.dirname(realPath) : realPath;\n\n const parentPath = sysPath.dirname(watchPath);\n let cont = FSEventsWatchers.get(watchPath);\n\n // If we've accumulated a substantial number of paths that\n // could have been consolidated by watching one directory\n // above the current one, create a watcher on the parent\n // path instead, so that we do consolidate going forward.\n if (couldConsolidate(parentPath)) {\n watchPath = parentPath;\n }\n\n const resolvedPath = sysPath.resolve(path);\n const hasSymlink = resolvedPath !== realPath;\n\n const filteredListener = (fullPath, flags, info) => {\n if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);\n if (\n fullPath === resolvedPath ||\n !fullPath.indexOf(resolvedPath + sysPath.sep)\n ) listener(fullPath, flags, info);\n };\n\n // check if there is already a watcher on a parent path\n // modifies `watchPath` to the parent path when it finds a match\n let watchedParent = false;\n for (const watchedPath of FSEventsWatchers.keys()) {\n if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) {\n watchPath = watchedPath;\n cont = FSEventsWatchers.get(watchPath);\n watchedParent = true;\n break;\n }\n }\n\n if (cont || watchedParent) {\n cont.listeners.add(filteredListener);\n } else {\n cont = {\n listeners: new Set([filteredListener]),\n rawEmitter,\n watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {\n if (!cont.listeners.size) return;\n const info = fsevents.getInfo(fullPath, flags);\n cont.listeners.forEach(list => {\n list(fullPath, flags, info);\n });\n\n cont.rawEmitter(info.event, fullPath, info);\n })\n };\n FSEventsWatchers.set(watchPath, cont);\n }\n\n // removes this instance's listeners and closes the underlying fsevents\n // instance if there are no more listeners left\n return () => {\n const lst = cont.listeners;\n\n lst.delete(filteredListener);\n if (!lst.size) {\n FSEventsWatchers.delete(watchPath);\n if (cont.watcher) return cont.watcher.stop().then(() => {\n cont.rawEmitter = cont.watcher = undefined;\n Object.freeze(cont);\n });\n }\n };\n}\n\n// Decide whether or not we should start a new higher-level\n// parent watcher\nconst couldConsolidate = (path) => {\n let count = 0;\n for (const watchPath of FSEventsWatchers.keys()) {\n if (watchPath.indexOf(path) === 0) {\n count++;\n if (count >= consolidateThreshhold) {\n return true;\n }\n }\n }\n\n return false;\n};\n\n// returns boolean indicating whether fsevents can be used\nconst canUse = () => fsevents && FSEventsWatchers.size < 128;\n\n// determines subdirectory traversal levels from root to path\nconst calcDepth = (path, root) => {\n let i = 0;\n while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++;\n return i;\n};\n\n// returns boolean indicating whether the fsevents' event info has the same type\n// as the one returned by fs.stat\nconst sameTypes = (info, stats) => (\n info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||\n info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||\n info.type === FSEVENT_TYPE_FILE && stats.isFile()\n)\n\n/**\n * @mixin\n */\nclass FsEventsHandler {\n\n/**\n * @param {import('../index').FSWatcher} fsw\n */\nconstructor(fsw) {\n this.fsw = fsw;\n}\ncheckIgnored(path, stats) {\n const ipaths = this.fsw._ignoredPaths;\n if (this.fsw._isIgnored(path, stats)) {\n ipaths.add(path);\n if (stats && stats.isDirectory()) {\n ipaths.add(path + ROOT_GLOBSTAR);\n }\n return true;\n }\n\n ipaths.delete(path);\n ipaths.delete(path + ROOT_GLOBSTAR);\n}\n\naddOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {\n const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD;\n this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);\n}\n\nasync checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {\n try {\n const stats = await stat(path)\n if (this.fsw.closed) return;\n if (sameTypes(info, stats)) {\n this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);\n } else {\n this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);\n }\n } catch (error) {\n if (error.code === 'EACCES') {\n this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);\n } else {\n this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);\n }\n }\n}\n\nhandleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {\n if (this.fsw.closed || this.checkIgnored(path)) return;\n\n if (event === EV_UNLINK) {\n const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY\n // suppress unlink events on never before seen files\n if (isDirectory || watchedDir.has(item)) {\n this.fsw._remove(parent, item, isDirectory);\n }\n } else {\n if (event === EV_ADD) {\n // track new directories\n if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);\n\n if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {\n // push symlinks back to the top of the stack to get handled\n const curDepth = opts.depth === undefined ?\n undefined : calcDepth(fullPath, realPath) + 1;\n return this._addToFsEvents(path, false, true, curDepth);\n }\n\n // track new paths\n // (other than symlinks being followed, which will be tracked soon)\n this.fsw._getWatchedDir(parent).add(item);\n }\n /**\n * @type {'add'|'addDir'|'unlink'|'unlinkDir'}\n */\n const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;\n this.fsw._emit(eventName, path);\n if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true);\n }\n}\n\n/**\n * Handle symlinks encountered during directory scan\n * @param {String} watchPath - file/dir path to be watched with fsevents\n * @param {String} realPath - real path (in case of symlinks)\n * @param {Function} transform - path transformer\n * @param {Function} globFilter - path filter in case a glob pattern was provided\n * @returns {Function} closer for the watcher instance\n*/\n_watchWithFsEvents(watchPath, realPath, transform, globFilter) {\n if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;\n const opts = this.fsw.options;\n const watchCallback = async (fullPath, flags, info) => {\n if (this.fsw.closed) return;\n if (\n opts.depth !== undefined &&\n calcDepth(fullPath, realPath) > opts.depth\n ) return;\n const path = transform(sysPath.join(\n watchPath, sysPath.relative(watchPath, fullPath)\n ));\n if (globFilter && !globFilter(path)) return;\n // ensure directories are tracked\n const parent = sysPath.dirname(path);\n const item = sysPath.basename(path);\n const watchedDir = this.fsw._getWatchedDir(\n info.type === FSEVENT_TYPE_DIRECTORY ? path : parent\n );\n\n // correct for wrong events emitted\n if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {\n if (typeof opts.ignored === FUNCTION_TYPE) {\n let stats;\n try {\n stats = await stat(path);\n } catch (error) {}\n if (this.fsw.closed) return;\n if (this.checkIgnored(path, stats)) return;\n if (sameTypes(info, stats)) {\n this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);\n } else {\n this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);\n }\n } else {\n this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);\n }\n } else {\n switch (info.event) {\n case FSEVENT_CREATED:\n case FSEVENT_MODIFIED:\n return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);\n case FSEVENT_DELETED:\n case FSEVENT_MOVED:\n return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);\n }\n }\n };\n\n const closer = setFSEventsListener(\n watchPath,\n realPath,\n watchCallback,\n this.fsw._emitRaw\n );\n\n this.fsw._emitReady();\n return closer;\n}\n\n/**\n * Handle symlinks encountered during directory scan\n * @param {String} linkPath path to symlink\n * @param {String} fullPath absolute path to the symlink\n * @param {Function} transform pre-existing path transformer\n * @param {Number} curDepth level of subdirectories traversed to where symlink is\n * @returns {Promise}\n */\nasync _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {\n // don't follow the same symlink more than once\n if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;\n\n this.fsw._symlinkPaths.set(fullPath, true);\n this.fsw._incrReadyCount();\n\n try {\n const linkTarget = await realpath(linkPath);\n if (this.fsw.closed) return;\n if (this.fsw._isIgnored(linkTarget)) {\n return this.fsw._emitReady();\n }\n\n this.fsw._incrReadyCount();\n\n // add the linkTarget for watching with a wrapper for transform\n // that causes emitted paths to incorporate the link's path\n this._addToFsEvents(linkTarget || linkPath, (path) => {\n let aliasedPath = linkPath;\n if (linkTarget && linkTarget !== DOT_SLASH) {\n aliasedPath = path.replace(linkTarget, linkPath);\n } else if (path !== DOT_SLASH) {\n aliasedPath = sysPath.join(linkPath, path);\n }\n return transform(aliasedPath);\n }, false, curDepth);\n } catch(error) {\n if (this.fsw._handleError(error)) {\n return this.fsw._emitReady();\n }\n }\n}\n\n/**\n *\n * @param {Path} newPath\n * @param {fs.Stats} stats\n */\nemitAdd(newPath, stats, processPath, opts, forceAdd) {\n const pp = processPath(newPath);\n const isDir = stats.isDirectory();\n const dirObj = this.fsw._getWatchedDir(sysPath.dirname(pp));\n const base = sysPath.basename(pp);\n\n // ensure empty dirs get tracked\n if (isDir) this.fsw._getWatchedDir(pp);\n if (dirObj.has(base)) return;\n dirObj.add(base);\n\n if (!opts.ignoreInitial || forceAdd === true) {\n this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats);\n }\n}\n\ninitWatch(realPath, path, wh, processPath) {\n if (this.fsw.closed) return;\n const closer = this._watchWithFsEvents(\n wh.watchPath,\n sysPath.resolve(realPath || wh.watchPath),\n processPath,\n wh.globFilter\n );\n this.fsw._addPathCloser(path, closer);\n}\n\n/**\n * Handle added path with fsevents\n * @param {String} path file/dir path or glob pattern\n * @param {Function|Boolean=} transform converts working path to what the user expects\n * @param {Boolean=} forceAdd ensure add is emitted\n * @param {Number=} priorDepth Level of subdirectories already traversed.\n * @returns {Promise}\n */\nasync _addToFsEvents(path, transform, forceAdd, priorDepth) {\n if (this.fsw.closed) {\n return;\n }\n const opts = this.fsw.options;\n const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN;\n\n const wh = this.fsw._getWatchHelpers(path);\n\n // evaluate what is at the path we're being asked to watch\n try {\n const stats = await statMethods[wh.statMethod](wh.watchPath);\n if (this.fsw.closed) return;\n if (this.fsw._isIgnored(wh.watchPath, stats)) {\n throw null;\n }\n if (stats.isDirectory()) {\n // emit addDir unless this is a glob parent\n if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);\n\n // don't recurse further if it would exceed depth setting\n if (priorDepth && priorDepth > opts.depth) return;\n\n // scan the contents of the dir\n this.fsw._readdirp(wh.watchPath, {\n fileFilter: entry => wh.filterPath(entry),\n directoryFilter: entry => wh.filterDir(entry),\n ...Depth(opts.depth - (priorDepth || 0))\n }).on(STR_DATA, (entry) => {\n // need to check filterPath on dirs b/c filterDir is less restrictive\n if (this.fsw.closed) {\n return;\n }\n if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;\n\n const joinedPath = sysPath.join(wh.watchPath, entry.path);\n const {fullPath} = entry;\n\n if (wh.followSymlinks && entry.stats.isSymbolicLink()) {\n // preserve the current depth here since it can't be derived from\n // real paths past the symlink\n const curDepth = opts.depth === undefined ?\n undefined : calcDepth(joinedPath, sysPath.resolve(wh.watchPath)) + 1;\n\n this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);\n } else {\n this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);\n }\n }).on(EV_ERROR, EMPTY_FN).on(STR_END, () => {\n this.fsw._emitReady();\n });\n } else {\n this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);\n this.fsw._emitReady();\n }\n } catch (error) {\n if (!error || this.fsw._handleError(error)) {\n // TODO: Strange thing: \"should not choke on an ignored watch path\" will be failed without 2 ready calls -__-\n this.fsw._emitReady();\n this.fsw._emitReady();\n }\n }\n\n if (opts.persistent && forceAdd !== true) {\n if (typeof transform === FUNCTION_TYPE) {\n // realpath has already been resolved\n this.initWatch(undefined, path, wh, processPath);\n } else {\n let realPath;\n try {\n realPath = await realpath(wh.watchPath);\n } catch (e) {}\n this.initWatch(realPath, path, wh, processPath);\n }\n }\n}\n\n}\n\nmodule.exports = FsEventsHandler;\nmodule.exports.canUse = canUse;\n","'use strict';\n\nconst { EventEmitter } = require('events');\nconst fs = require('fs');\nconst sysPath = require('path');\nconst { promisify } = require('util');\nconst readdirp = require('readdirp');\nconst anymatch = require('anymatch').default;\nconst globParent = require('glob-parent');\nconst isGlob = require('is-glob');\nconst braces = require('braces');\nconst normalizePath = require('normalize-path');\n\nconst NodeFsHandler = require('./lib/nodefs-handler');\nconst FsEventsHandler = require('./lib/fsevents-handler');\nconst {\n EV_ALL,\n EV_READY,\n EV_ADD,\n EV_CHANGE,\n EV_UNLINK,\n EV_ADD_DIR,\n EV_UNLINK_DIR,\n EV_RAW,\n EV_ERROR,\n\n STR_CLOSE,\n STR_END,\n\n BACK_SLASH_RE,\n DOUBLE_SLASH_RE,\n SLASH_OR_BACK_SLASH_RE,\n DOT_RE,\n REPLACER_RE,\n\n SLASH,\n SLASH_SLASH,\n BRACE_START,\n BANG,\n ONE_DOT,\n TWO_DOTS,\n GLOBSTAR,\n SLASH_GLOBSTAR,\n ANYMATCH_OPTS,\n STRING_TYPE,\n FUNCTION_TYPE,\n EMPTY_STR,\n EMPTY_FN,\n\n isWindows,\n isMacos,\n isIBMi\n} = require('./lib/constants');\n\nconst stat = promisify(fs.stat);\nconst readdir = promisify(fs.readdir);\n\n/**\n * @typedef {String} Path\n * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName\n * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType\n */\n\n/**\n *\n * @typedef {Object} WatchHelpers\n * @property {Boolean} followSymlinks\n * @property {'stat'|'lstat'} statMethod\n * @property {Path} path\n * @property {Path} watchPath\n * @property {Function} entryPath\n * @property {Boolean} hasGlob\n * @property {Object} globFilter\n * @property {Function} filterPath\n * @property {Function} filterDir\n */\n\nconst arrify = (value = []) => Array.isArray(value) ? value : [value];\nconst flatten = (list, result = []) => {\n list.forEach(item => {\n if (Array.isArray(item)) {\n flatten(item, result);\n } else {\n result.push(item);\n }\n });\n return result;\n};\n\nconst unifyPaths = (paths_) => {\n /**\n * @type {Array}\n */\n const paths = flatten(arrify(paths_));\n if (!paths.every(p => typeof p === STRING_TYPE)) {\n throw new TypeError(`Non-string provided as watch path: ${paths}`);\n }\n return paths.map(normalizePathToUnix);\n};\n\n// If SLASH_SLASH occurs at the beginning of path, it is not replaced\n// because \"//StoragePC/DrivePool/Movies\" is a valid network path\nconst toUnix = (string) => {\n let str = string.replace(BACK_SLASH_RE, SLASH);\n let prepend = false;\n if (str.startsWith(SLASH_SLASH)) {\n prepend = true;\n }\n while (str.match(DOUBLE_SLASH_RE)) {\n str = str.replace(DOUBLE_SLASH_RE, SLASH);\n }\n if (prepend) {\n str = SLASH + str;\n }\n return str;\n};\n\n// Our version of upath.normalize\n// TODO: this is not equal to path-normalize module - investigate why\nconst normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));\n\nconst normalizeIgnored = (cwd = EMPTY_STR) => (path) => {\n if (typeof path !== STRING_TYPE) return path;\n return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));\n};\n\nconst getAbsolutePath = (path, cwd) => {\n if (sysPath.isAbsolute(path)) {\n return path;\n }\n if (path.startsWith(BANG)) {\n return BANG + sysPath.join(cwd, path.slice(1));\n }\n return sysPath.join(cwd, path);\n};\n\nconst undef = (opts, key) => opts[key] === undefined;\n\n/**\n * Directory entry.\n * @property {Path} path\n * @property {Set} items\n */\nclass DirEntry {\n /**\n * @param {Path} dir\n * @param {Function} removeWatcher\n */\n constructor(dir, removeWatcher) {\n this.path = dir;\n this._removeWatcher = removeWatcher;\n /** @type {Set} */\n this.items = new Set();\n }\n\n add(item) {\n const {items} = this;\n if (!items) return;\n if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);\n }\n\n async remove(item) {\n const {items} = this;\n if (!items) return;\n items.delete(item);\n if (items.size > 0) return;\n\n const dir = this.path;\n try {\n await readdir(dir);\n } catch (err) {\n if (this._removeWatcher) {\n this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));\n }\n }\n }\n\n has(item) {\n const {items} = this;\n if (!items) return;\n return items.has(item);\n }\n\n /**\n * @returns {Array}\n */\n getChildren() {\n const {items} = this;\n if (!items) return;\n return [...items.values()];\n }\n\n dispose() {\n this.items.clear();\n delete this.path;\n delete this._removeWatcher;\n delete this.items;\n Object.freeze(this);\n }\n}\n\nconst STAT_METHOD_F = 'stat';\nconst STAT_METHOD_L = 'lstat';\nclass WatchHelper {\n constructor(path, watchPath, follow, fsw) {\n this.fsw = fsw;\n this.path = path = path.replace(REPLACER_RE, EMPTY_STR);\n this.watchPath = watchPath;\n this.fullWatchPath = sysPath.resolve(watchPath);\n this.hasGlob = watchPath !== path;\n /** @type {object|boolean} */\n if (path === EMPTY_STR) this.hasGlob = false;\n this.globSymlink = this.hasGlob && follow ? undefined : false;\n this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;\n this.dirParts = this.getDirParts(path);\n this.dirParts.forEach((parts) => {\n if (parts.length > 1) parts.pop();\n });\n this.followSymlinks = follow;\n this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;\n }\n\n checkGlobSymlink(entry) {\n // only need to resolve once\n // first entry should always have entry.parentDir === EMPTY_STR\n if (this.globSymlink === undefined) {\n this.globSymlink = entry.fullParentDir === this.fullWatchPath ?\n false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};\n }\n\n if (this.globSymlink) {\n return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);\n }\n\n return entry.fullPath;\n }\n\n entryPath(entry) {\n return sysPath.join(this.watchPath,\n sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))\n );\n }\n\n filterPath(entry) {\n const {stats} = entry;\n if (stats && stats.isSymbolicLink()) return this.filterDir(entry);\n const resolvedPath = this.entryPath(entry);\n const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?\n this.globFilter(resolvedPath) : true;\n return matchesGlob &&\n this.fsw._isntIgnored(resolvedPath, stats) &&\n this.fsw._hasReadPermissions(stats);\n }\n\n getDirParts(path) {\n if (!this.hasGlob) return [];\n const parts = [];\n const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];\n expandedPath.forEach((path) => {\n parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));\n });\n return parts;\n }\n\n filterDir(entry) {\n if (this.hasGlob) {\n const entryParts = this.getDirParts(this.checkGlobSymlink(entry));\n let globstar = false;\n this.unmatchedGlob = !this.dirParts.some((parts) => {\n return parts.every((part, i) => {\n if (part === GLOBSTAR) globstar = true;\n return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);\n });\n });\n }\n return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);\n }\n}\n\n/**\n * Watches files & directories for changes. Emitted events:\n * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`\n *\n * new FSWatcher()\n * .add(directories)\n * .on('add', path => log('File', path, 'was added'))\n */\nclass FSWatcher extends EventEmitter {\n// Not indenting methods for history sake; for now.\nconstructor(_opts) {\n super();\n\n const opts = {};\n if (_opts) Object.assign(opts, _opts); // for frozen objects\n\n /** @type {Map} */\n this._watched = new Map();\n /** @type {Map} */\n this._closers = new Map();\n /** @type {Set} */\n this._ignoredPaths = new Set();\n\n /** @type {Map} */\n this._throttled = new Map();\n\n /** @type {Map} */\n this._symlinkPaths = new Map();\n\n this._streams = new Set();\n this.closed = false;\n\n // Set up default options.\n if (undef(opts, 'persistent')) opts.persistent = true;\n if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;\n if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;\n if (undef(opts, 'interval')) opts.interval = 100;\n if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;\n if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;\n opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;\n\n // Enable fsevents on OS X when polling isn't explicitly enabled.\n if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;\n\n // If we can't use fsevents, ensure the options reflect it's disabled.\n const canUseFsEvents = FsEventsHandler.canUse();\n if (!canUseFsEvents) opts.useFsEvents = false;\n\n // Use polling on Mac if not using fsevents.\n // Other platforms use non-polling fs_watch.\n if (undef(opts, 'usePolling') && !opts.useFsEvents) {\n opts.usePolling = isMacos;\n }\n\n // Always default to polling on IBM i because fs.watch() is not available on IBM i.\n if(isIBMi) {\n opts.usePolling = true;\n }\n\n // Global override (useful for end-developers that need to force polling for all\n // instances of chokidar, regardless of usage/dependency depth)\n const envPoll = process.env.CHOKIDAR_USEPOLLING;\n if (envPoll !== undefined) {\n const envLower = envPoll.toLowerCase();\n\n if (envLower === 'false' || envLower === '0') {\n opts.usePolling = false;\n } else if (envLower === 'true' || envLower === '1') {\n opts.usePolling = true;\n } else {\n opts.usePolling = !!envLower;\n }\n }\n const envInterval = process.env.CHOKIDAR_INTERVAL;\n if (envInterval) {\n opts.interval = Number.parseInt(envInterval, 10);\n }\n\n // Editor atomic write normalization enabled by default with fs.watch\n if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;\n if (opts.atomic) this._pendingUnlinks = new Map();\n\n if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;\n\n if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;\n if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};\n const awf = opts.awaitWriteFinish;\n if (awf) {\n if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;\n if (!awf.pollInterval) awf.pollInterval = 100;\n this._pendingWrites = new Map();\n }\n if (opts.ignored) opts.ignored = arrify(opts.ignored);\n\n let readyCalls = 0;\n this._emitReady = () => {\n readyCalls++;\n if (readyCalls >= this._readyCount) {\n this._emitReady = EMPTY_FN;\n this._readyEmitted = true;\n // use process.nextTick to allow time for listener to be bound\n process.nextTick(() => this.emit(EV_READY));\n }\n };\n this._emitRaw = (...args) => this.emit(EV_RAW, ...args);\n this._readyEmitted = false;\n this.options = opts;\n\n // Initialize with proper watcher.\n if (opts.useFsEvents) {\n this._fsEventsHandler = new FsEventsHandler(this);\n } else {\n this._nodeFsHandler = new NodeFsHandler(this);\n }\n\n // You’re frozen when your heart’s not open.\n Object.freeze(opts);\n}\n\n// Public methods\n\n/**\n * Adds paths to be watched on an existing FSWatcher instance\n * @param {Path|Array} paths_\n * @param {String=} _origAdd private; for handling non-existent paths to be watched\n * @param {Boolean=} _internal private; indicates a non-user add\n * @returns {FSWatcher} for chaining\n */\nadd(paths_, _origAdd, _internal) {\n const {cwd, disableGlobbing} = this.options;\n this.closed = false;\n let paths = unifyPaths(paths_);\n if (cwd) {\n paths = paths.map((path) => {\n const absPath = getAbsolutePath(path, cwd);\n\n // Check `path` instead of `absPath` because the cwd portion can't be a glob\n if (disableGlobbing || !isGlob(path)) {\n return absPath;\n }\n return normalizePath(absPath);\n });\n }\n\n // set aside negated glob strings\n paths = paths.filter((path) => {\n if (path.startsWith(BANG)) {\n this._ignoredPaths.add(path.slice(1));\n return false;\n }\n\n // if a path is being added that was previously ignored, stop ignoring it\n this._ignoredPaths.delete(path);\n this._ignoredPaths.delete(path + SLASH_GLOBSTAR);\n\n // reset the cached userIgnored anymatch fn\n // to make ignoredPaths changes effective\n this._userIgnored = undefined;\n\n return true;\n });\n\n if (this.options.useFsEvents && this._fsEventsHandler) {\n if (!this._readyCount) this._readyCount = paths.length;\n if (this.options.persistent) this._readyCount *= 2;\n paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));\n } else {\n if (!this._readyCount) this._readyCount = 0;\n this._readyCount += paths.length;\n Promise.all(\n paths.map(async path => {\n const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);\n if (res) this._emitReady();\n return res;\n })\n ).then(results => {\n if (this.closed) return;\n results.filter(item => item).forEach(item => {\n this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));\n });\n });\n }\n\n return this;\n}\n\n/**\n * Close watchers or start ignoring events from specified paths.\n * @param {Path|Array} paths_ - string or array of strings, file/directory paths and/or globs\n * @returns {FSWatcher} for chaining\n*/\nunwatch(paths_) {\n if (this.closed) return this;\n const paths = unifyPaths(paths_);\n const {cwd} = this.options;\n\n paths.forEach((path) => {\n // convert to absolute path unless relative path already matches\n if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {\n if (cwd) path = sysPath.join(cwd, path);\n path = sysPath.resolve(path);\n }\n\n this._closePath(path);\n\n this._ignoredPaths.add(path);\n if (this._watched.has(path)) {\n this._ignoredPaths.add(path + SLASH_GLOBSTAR);\n }\n\n // reset the cached userIgnored anymatch fn\n // to make ignoredPaths changes effective\n this._userIgnored = undefined;\n });\n\n return this;\n}\n\n/**\n * Close watchers and remove all listeners from watched paths.\n * @returns {Promise}.\n*/\nclose() {\n if (this.closed) return this._closePromise;\n this.closed = true;\n\n // Memory management.\n this.removeAllListeners();\n const closers = [];\n this._closers.forEach(closerList => closerList.forEach(closer => {\n const promise = closer();\n if (promise instanceof Promise) closers.push(promise);\n }));\n this._streams.forEach(stream => stream.destroy());\n this._userIgnored = undefined;\n this._readyCount = 0;\n this._readyEmitted = false;\n this._watched.forEach(dirent => dirent.dispose());\n ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {\n this[`_${key}`].clear();\n });\n\n this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();\n return this._closePromise;\n}\n\n/**\n * Expose list of watched paths\n * @returns {Object} for chaining\n*/\ngetWatched() {\n const watchList = {};\n this._watched.forEach((entry, dir) => {\n const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;\n watchList[key || ONE_DOT] = entry.getChildren().sort();\n });\n return watchList;\n}\n\nemitWithAll(event, args) {\n this.emit(...args);\n if (event !== EV_ERROR) this.emit(EV_ALL, ...args);\n}\n\n// Common helpers\n// --------------\n\n/**\n * Normalize and emit events.\n * Calling _emit DOES NOT MEAN emit() would be called!\n * @param {EventName} event Type of event\n * @param {Path} path File or directory path\n * @param {*=} val1 arguments to be passed with event\n * @param {*=} val2\n * @param {*=} val3\n * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n */\nasync _emit(event, path, val1, val2, val3) {\n if (this.closed) return;\n\n const opts = this.options;\n if (isWindows) path = sysPath.normalize(path);\n if (opts.cwd) path = sysPath.relative(opts.cwd, path);\n /** @type Array */\n const args = [event, path];\n if (val3 !== undefined) args.push(val1, val2, val3);\n else if (val2 !== undefined) args.push(val1, val2);\n else if (val1 !== undefined) args.push(val1);\n\n const awf = opts.awaitWriteFinish;\n let pw;\n if (awf && (pw = this._pendingWrites.get(path))) {\n pw.lastChange = new Date();\n return this;\n }\n\n if (opts.atomic) {\n if (event === EV_UNLINK) {\n this._pendingUnlinks.set(path, args);\n setTimeout(() => {\n this._pendingUnlinks.forEach((entry, path) => {\n this.emit(...entry);\n this.emit(EV_ALL, ...entry);\n this._pendingUnlinks.delete(path);\n });\n }, typeof opts.atomic === 'number' ? opts.atomic : 100);\n return this;\n }\n if (event === EV_ADD && this._pendingUnlinks.has(path)) {\n event = args[0] = EV_CHANGE;\n this._pendingUnlinks.delete(path);\n }\n }\n\n if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {\n const awfEmit = (err, stats) => {\n if (err) {\n event = args[0] = EV_ERROR;\n args[1] = err;\n this.emitWithAll(event, args);\n } else if (stats) {\n // if stats doesn't exist the file must have been deleted\n if (args.length > 2) {\n args[2] = stats;\n } else {\n args.push(stats);\n }\n this.emitWithAll(event, args);\n }\n };\n\n this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);\n return this;\n }\n\n if (event === EV_CHANGE) {\n const isThrottled = !this._throttle(EV_CHANGE, path, 50);\n if (isThrottled) return this;\n }\n\n if (opts.alwaysStat && val1 === undefined &&\n (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)\n ) {\n const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;\n let stats;\n try {\n stats = await stat(fullPath);\n } catch (err) {}\n // Suppress event when fs_stat fails, to avoid sending undefined 'stat'\n if (!stats || this.closed) return;\n args.push(stats);\n }\n this.emitWithAll(event, args);\n\n return this;\n}\n\n/**\n * Common handler for errors\n * @param {Error} error\n * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag\n */\n_handleError(error) {\n const code = error && error.code;\n if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&\n (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))\n ) {\n this.emit(EV_ERROR, error);\n }\n return error || this.closed;\n}\n\n/**\n * Helper utility for throttling\n * @param {ThrottleType} actionType type being throttled\n * @param {Path} path being acted upon\n * @param {Number} timeout duration of time to suppress duplicate actions\n * @returns {Object|false} tracking object or false if action should be suppressed\n */\n_throttle(actionType, path, timeout) {\n if (!this._throttled.has(actionType)) {\n this._throttled.set(actionType, new Map());\n }\n\n /** @type {Map} */\n const action = this._throttled.get(actionType);\n /** @type {Object} */\n const actionPath = action.get(path);\n\n if (actionPath) {\n actionPath.count++;\n return false;\n }\n\n let timeoutObject;\n const clear = () => {\n const item = action.get(path);\n const count = item ? item.count : 0;\n action.delete(path);\n clearTimeout(timeoutObject);\n if (item) clearTimeout(item.timeoutObject);\n return count;\n };\n timeoutObject = setTimeout(clear, timeout);\n const thr = {timeoutObject, clear, count: 0};\n action.set(path, thr);\n return thr;\n}\n\n_incrReadyCount() {\n return this._readyCount++;\n}\n\n/**\n * Awaits write operation to finish.\n * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.\n * @param {Path} path being acted upon\n * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished\n * @param {EventName} event\n * @param {Function} awfEmit Callback to be called when ready for event to be emitted.\n */\n_awaitWriteFinish(path, threshold, event, awfEmit) {\n let timeoutHandler;\n\n let fullPath = path;\n if (this.options.cwd && !sysPath.isAbsolute(path)) {\n fullPath = sysPath.join(this.options.cwd, path);\n }\n\n const now = new Date();\n\n const awaitWriteFinish = (prevStat) => {\n fs.stat(fullPath, (err, curStat) => {\n if (err || !this._pendingWrites.has(path)) {\n if (err && err.code !== 'ENOENT') awfEmit(err);\n return;\n }\n\n const now = Number(new Date());\n\n if (prevStat && curStat.size !== prevStat.size) {\n this._pendingWrites.get(path).lastChange = now;\n }\n const pw = this._pendingWrites.get(path);\n const df = now - pw.lastChange;\n\n if (df >= threshold) {\n this._pendingWrites.delete(path);\n awfEmit(undefined, curStat);\n } else {\n timeoutHandler = setTimeout(\n awaitWriteFinish,\n this.options.awaitWriteFinish.pollInterval,\n curStat\n );\n }\n });\n };\n\n if (!this._pendingWrites.has(path)) {\n this._pendingWrites.set(path, {\n lastChange: now,\n cancelWait: () => {\n this._pendingWrites.delete(path);\n clearTimeout(timeoutHandler);\n return event;\n }\n });\n timeoutHandler = setTimeout(\n awaitWriteFinish,\n this.options.awaitWriteFinish.pollInterval\n );\n }\n}\n\n_getGlobIgnored() {\n return [...this._ignoredPaths.values()];\n}\n\n/**\n * Determines whether user has asked to ignore this path.\n * @param {Path} path filepath or dir\n * @param {fs.Stats=} stats result of fs.stat\n * @returns {Boolean}\n */\n_isIgnored(path, stats) {\n if (this.options.atomic && DOT_RE.test(path)) return true;\n if (!this._userIgnored) {\n const {cwd} = this.options;\n const ign = this.options.ignored;\n\n const ignored = ign && ign.map(normalizeIgnored(cwd));\n const paths = arrify(ignored)\n .filter((path) => typeof path === STRING_TYPE && !isGlob(path))\n .map((path) => path + SLASH_GLOBSTAR);\n const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);\n this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);\n }\n\n return this._userIgnored([path, stats]);\n}\n\n_isntIgnored(path, stat) {\n return !this._isIgnored(path, stat);\n}\n\n/**\n * Provides a set of common helpers and properties relating to symlink and glob handling.\n * @param {Path} path file, directory, or glob pattern being watched\n * @param {Number=} depth at any depth > 0, this isn't a glob\n * @returns {WatchHelper} object containing helpers for this path\n */\n_getWatchHelpers(path, depth) {\n const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);\n const follow = this.options.followSymlinks;\n\n return new WatchHelper(path, watchPath, follow, this);\n}\n\n// Directory helpers\n// -----------------\n\n/**\n * Provides directory tracking objects\n * @param {String} directory path of the directory\n * @returns {DirEntry} the directory's tracking object\n */\n_getWatchedDir(directory) {\n if (!this._boundRemove) this._boundRemove = this._remove.bind(this);\n const dir = sysPath.resolve(directory);\n if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));\n return this._watched.get(dir);\n}\n\n// File helpers\n// ------------\n\n/**\n * Check for read permissions.\n * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405\n * @param {fs.Stats} stats - object, result of fs_stat\n * @returns {Boolean} indicates whether the file can be read\n*/\n_hasReadPermissions(stats) {\n if (this.options.ignorePermissionErrors) return true;\n\n // stats.mode may be bigint\n const md = stats && Number.parseInt(stats.mode, 10);\n const st = md & 0o777;\n const it = Number.parseInt(st.toString(8)[0], 10);\n return Boolean(4 & it);\n}\n\n/**\n * Handles emitting unlink events for\n * files and directories, and via recursion, for\n * files and directories within directories that are unlinked\n * @param {String} directory within which the following item is located\n * @param {String} item base path of item/directory\n * @returns {void}\n*/\n_remove(directory, item, isDirectory) {\n // if what is being deleted is a directory, get that directory's paths\n // for recursive deleting and cleaning of watched object\n // if it is not a directory, nestedDirectoryChildren will be empty array\n const path = sysPath.join(directory, item);\n const fullPath = sysPath.resolve(path);\n isDirectory = isDirectory != null\n ? isDirectory\n : this._watched.has(path) || this._watched.has(fullPath);\n\n // prevent duplicate handling in case of arriving here nearly simultaneously\n // via multiple paths (such as _handleFile and _handleDir)\n if (!this._throttle('remove', path, 100)) return;\n\n // if the only watched file is removed, watch for its return\n if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {\n this.add(directory, item, true);\n }\n\n // This will create a new entry in the watched object in either case\n // so we got to do the directory check beforehand\n const wp = this._getWatchedDir(path);\n const nestedDirectoryChildren = wp.getChildren();\n\n // Recursively remove children directories / files.\n nestedDirectoryChildren.forEach(nested => this._remove(path, nested));\n\n // Check if item was on the watched list and remove it\n const parent = this._getWatchedDir(directory);\n const wasTracked = parent.has(item);\n parent.remove(item);\n\n // Fixes issue #1042 -> Relative paths were detected and added as symlinks\n // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),\n // but never removed from the map in case the path was deleted.\n // This leads to an incorrect state if the path was recreated:\n // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553\n if (this._symlinkPaths.has(fullPath)) {\n this._symlinkPaths.delete(fullPath);\n }\n\n // If we wait for this file to be fully written, cancel the wait.\n let relPath = path;\n if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);\n if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {\n const event = this._pendingWrites.get(relPath).cancelWait();\n if (event === EV_ADD) return;\n }\n\n // The Entry will either be a directory that just got removed\n // or a bogus entry to a file, in either case we have to remove it\n this._watched.delete(path);\n this._watched.delete(fullPath);\n const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;\n if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);\n\n // Avoid conflicts if we later create another file with the same name\n if (!this.options.useFsEvents) {\n this._closePath(path);\n }\n}\n\n/**\n * Closes all watchers for a path\n * @param {Path} path\n */\n_closePath(path) {\n this._closeFile(path)\n const dir = sysPath.dirname(path);\n this._getWatchedDir(dir).remove(sysPath.basename(path));\n}\n\n/**\n * Closes only file-specific watchers\n * @param {Path} path\n */\n_closeFile(path) {\n const closers = this._closers.get(path);\n if (!closers) return;\n closers.forEach(closer => closer());\n this._closers.delete(path);\n}\n\n/**\n *\n * @param {Path} path\n * @param {Function} closer\n */\n_addPathCloser(path, closer) {\n if (!closer) return;\n let list = this._closers.get(path);\n if (!list) {\n list = [];\n this._closers.set(path, list);\n }\n list.push(closer);\n}\n\n_readdirp(root, opts) {\n if (this.closed) return;\n const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};\n let stream = readdirp(root, options);\n this._streams.add(stream);\n stream.once(STR_CLOSE, () => {\n stream = undefined;\n });\n stream.once(STR_END, () => {\n if (stream) {\n this._streams.delete(stream);\n stream = undefined;\n }\n });\n return stream;\n}\n\n}\n\n// Export FSWatcher class\nexports.FSWatcher = FSWatcher;\n\n/**\n * Instantiates watcher with paths to be tracked.\n * @param {String|Array} paths file/directory paths and/or globs\n * @param {Object=} options chokidar opts\n * @returns an instance of FSWatcher for chaining.\n */\nconst watch = (paths, options) => {\n const watcher = new FSWatcher(options);\n watcher.add(paths);\n return watcher;\n};\n\nexports.watch = watch;\n","import fs, { promises as fsp } from 'fs'\nimport path from 'path'\nimport { Server as HttpServer } from 'http'\nimport { ServerOptions as HttpsServerOptions } from 'https'\nimport { ResolvedConfig, ServerOptions } from '..'\nimport { isObject } from '../utils'\nimport { Connect } from 'types/connect'\nimport { Logger } from '../logger'\n\nexport async function resolveHttpServer(\n { proxy }: ServerOptions,\n app: Connect.Server,\n httpsOptions?: HttpsServerOptions\n): Promise {\n if (!httpsOptions) {\n return require('http').createServer(app)\n }\n\n if (proxy) {\n // #484 fallback to http1 when proxy is needed.\n return require('https').createServer(httpsOptions, app)\n } else {\n return require('http2').createSecureServer(\n {\n ...httpsOptions,\n allowHTTP1: true\n },\n app\n )\n }\n}\n\nexport async function resolveHttpsConfig(\n config: ResolvedConfig\n): Promise {\n if (!config.server.https) return undefined\n\n const httpsOption = isObject(config.server.https) ? config.server.https : {}\n\n const { ca, cert, key, pfx } = httpsOption\n Object.assign(httpsOption, {\n ca: readFileIfExists(ca),\n cert: readFileIfExists(cert),\n key: readFileIfExists(key),\n pfx: readFileIfExists(pfx)\n })\n if (!httpsOption.key || !httpsOption.cert) {\n httpsOption.cert = httpsOption.key = await getCertificate(config)\n }\n return httpsOption\n}\n\nfunction readFileIfExists(value?: string | Buffer | any[]) {\n if (typeof value === 'string') {\n try {\n return fs.readFileSync(path.resolve(value as string))\n } catch (e) {\n return value\n }\n }\n return value\n}\n\n/**\n * https://github.com/webpack/webpack-dev-server/blob/master/lib/utils/createCertificate.js\n *\n * Copyright JS Foundation and other contributors\n * This source code is licensed under the MIT license found in the\n * LICENSE file at\n * https://github.com/webpack/webpack-dev-server/blob/master/LICENSE\n */\nasync function createCertificate() {\n const { generate } = await import('selfsigned')\n const pems = generate(null, {\n algorithm: 'sha256',\n days: 30,\n keySize: 2048,\n extensions: [\n // {\n // name: 'basicConstraints',\n // cA: true,\n // },\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n timeStamping: true\n },\n {\n name: 'subjectAltName',\n altNames: [\n {\n // type 2 is DNS\n type: 2,\n value: 'localhost'\n },\n {\n type: 2,\n value: 'localhost.localdomain'\n },\n {\n type: 2,\n value: 'lvh.me'\n },\n {\n type: 2,\n value: '*.lvh.me'\n },\n {\n type: 2,\n value: '[::1]'\n },\n {\n // type 7 is IP\n type: 7,\n ip: '127.0.0.1'\n },\n {\n type: 7,\n ip: 'fe80::1'\n }\n ]\n }\n ]\n })\n return pems.private + pems.cert\n}\n\nasync function getCertificate(config: ResolvedConfig) {\n if (!config.cacheDir) return await createCertificate()\n\n const cachePath = path.join(config.cacheDir, '_cert.pem')\n\n try {\n const [stat, content] = await Promise.all([\n fsp.stat(cachePath),\n fsp.readFile(cachePath, 'utf8')\n ])\n\n if (Date.now() - stat.ctime.valueOf() > 30 * 24 * 60 * 60 * 1000) {\n throw new Error('cache is outdated.')\n }\n\n return content\n } catch {\n const content = await createCertificate()\n fsp\n .mkdir(config.cacheDir, { recursive: true })\n .then(() => fsp.writeFile(cachePath, content))\n .catch(() => {})\n return content\n }\n}\n\nexport async function httpServerStart(\n httpServer: HttpServer,\n serverOptions: {\n port: number\n strictPort: boolean | undefined\n host: string | undefined\n logger: Logger\n }\n): Promise {\n return new Promise((resolve, reject) => {\n let { port, strictPort, host, logger } = serverOptions\n\n const onError = (e: Error & { code?: string }) => {\n if (e.code === 'EADDRINUSE') {\n if (strictPort) {\n httpServer.removeListener('error', onError)\n reject(new Error(`Port ${port} is already in use`))\n } else {\n logger.info(`Port ${port} is in use, trying another one...`)\n httpServer.listen(++port, host)\n }\n } else {\n httpServer.removeListener('error', onError)\n reject(e)\n }\n }\n\n httpServer.on('error', onError)\n\n httpServer.listen(port, host, () => {\n httpServer.removeListener('error', onError)\n resolve(port)\n })\n })\n}\n","'use strict';\n\nmodule.exports = {\n BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n EMPTY_BUFFER: Buffer.alloc(0),\n NOOP: () => {}\n};\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) return target.slice(0, offset);\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n // Required until https://github.com/nodejs/node/issues/9006 is resolved.\n const length = buffer.length;\n for (let i = 0; i < length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.byteLength === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = Buffer.from(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\ntry {\n const bufferUtil = require('bufferutil');\n const bu = bufferUtil.BufferUtil || bufferUtil;\n\n module.exports = {\n concat,\n mask(source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bu.mask(source, mask, output, offset, length);\n },\n toArrayBuffer,\n toBuffer,\n unmask(buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bu.unmask(buffer, mask);\n }\n };\n} catch (e) /* istanbul ignore next */ {\n module.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n };\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode, NOOP } = require('./constants');\n\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {Boolean} [isServer=false] Create the instance in either server or\n * client mode\n * @param {Number} [maxPayload=0] The maximum allowed message length\n */\n constructor(options, isServer, maxPayload) {\n this._maxPayload = maxPayload | 0;\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._isServer = !!isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {Buffer} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {Buffer} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n //\n // An `'error'` event is emitted, only on Node.js < 10.0.0, if the\n // `zlib.DeflateRaw` instance is closed while data is being processed.\n // This can happen if `PerMessageDeflate#cleanup()` is called at the wrong\n // time due to an abnormal WebSocket closure.\n //\n this._deflate.on('error', NOOP);\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) data = data.slice(0, data.length - 4);\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\ntry {\n let isValidUTF8 = require('utf-8-validate');\n\n /* istanbul ignore if */\n if (typeof isValidUTF8 === 'object') {\n isValidUTF8 = isValidUTF8.Validation.isValidUTF8; // utf-8-validate@<3.0.0\n }\n\n module.exports = {\n isValidStatusCode,\n isValidUTF8(buf) {\n return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf);\n }\n };\n} catch (e) /* istanbul ignore next */ {\n module.exports = {\n isValidStatusCode,\n isValidUTF8: _isValidUTF8\n };\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {String} [binaryType=nodebuffer] The type for binary data\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Boolean} [isServer=false] Specifies whether to operate in client or\n * server mode\n * @param {Number} [maxPayload=0] The maximum allowed message length\n */\n constructor(binaryType, extensions, isServer, maxPayload) {\n super();\n\n this._binaryType = binaryType || BINARY_TYPES[0];\n this[kWebSocket] = undefined;\n this._extensions = extensions || {};\n this._isServer = !!isServer;\n this._maxPayload = maxPayload | 0;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._state = GET_INFO;\n this._loop = false;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = buf.slice(n);\n return buf.slice(0, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = buf.slice(n);\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n let err;\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n err = this.getInfo();\n break;\n case GET_PAYLOAD_LENGTH_16:\n err = this.getPayloadLength16();\n break;\n case GET_PAYLOAD_LENGTH_64:\n err = this.getPayloadLength64();\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n err = this.getData(cb);\n break;\n default:\n // `INFLATING`\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n cb(err);\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @return {(RangeError|undefined)} A possible error\n * @private\n */\n getInfo() {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n this._loop = false;\n return error(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n this._loop = false;\n return error(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n this._loop = false;\n return error(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n }\n\n if (!this._fragmented) {\n this._loop = false;\n return error(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n this._loop = false;\n return error(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n this._loop = false;\n return error(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n }\n\n if (compressed) {\n this._loop = false;\n return error(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n }\n\n if (this._payloadLength > 0x7d) {\n this._loop = false;\n return error(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n }\n } else {\n this._loop = false;\n return error(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n this._loop = false;\n return error(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n }\n } else if (this._masked) {\n this._loop = false;\n return error(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else return this.haveLength();\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @return {(RangeError|undefined)} A possible error\n * @private\n */\n getPayloadLength16() {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n return this.haveLength();\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @return {(RangeError|undefined)} A possible error\n * @private\n */\n getPayloadLength64() {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n this._loop = false;\n return error(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n return this.haveLength();\n }\n\n /**\n * Payload length has been read.\n *\n * @return {(RangeError|undefined)} A possible error\n * @private\n */\n haveLength() {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n this._loop = false;\n return error(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n if (this._masked) unmask(data, this._mask);\n }\n\n if (this._opcode > 0x07) return this.controlMessage(data);\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its lenght is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n return this.dataMessage();\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n return cb(\n error(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n )\n );\n }\n\n this._fragments.push(buf);\n }\n\n const er = this.dataMessage();\n if (er) return cb(er);\n\n this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @return {(Error|undefined)} A possible error\n * @private\n */\n dataMessage() {\n if (this._fin) {\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else {\n data = fragments;\n }\n\n this.emit('message', data);\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!isValidUTF8(buf)) {\n this._loop = false;\n return error(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n }\n\n this.emit('message', buf.toString());\n }\n }\n\n this._state = GET_INFO;\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data) {\n if (this._opcode === 0x08) {\n this._loop = false;\n\n if (data.length === 0) {\n this.emit('conclude', 1005, '');\n this.end();\n } else if (data.length === 1) {\n return error(\n RangeError,\n 'invalid payload length 1',\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n return error(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n }\n\n const buf = data.slice(2);\n\n if (!isValidUTF8(buf)) {\n return error(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n }\n\n this.emit('conclude', code, buf.toString());\n this.end();\n }\n } else if (this._opcode === 0x09) {\n this.emit('ping', data);\n } else {\n this.emit('pong', data);\n }\n\n this._state = GET_INFO;\n }\n}\n\nmodule.exports = Receiver;\n\n/**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\nfunction error(ErrorCtor, message, prefix, statusCode, errorCode) {\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, error);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n}\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^net|tls$\" }] */\n\n'use strict';\n\nconst net = require('net');\nconst tls = require('tls');\nconst { randomFillSync } = require('crypto');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER } = require('./constants');\nconst { isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst mask = Buffer.alloc(4);\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {(net.Socket|tls.Socket)} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n */\n constructor(socket, extensions) {\n this._extensions = extensions || {};\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._deflating = false;\n this._queue = [];\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {Buffer} data The data to frame\n * @param {Object} options Options object\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {Buffer[]} The framed data as a list of `Buffer` instances\n * @public\n */\n static frame(data, options) {\n const merge = options.mask && options.readOnly;\n let offset = options.mask ? 6 : 2;\n let payloadLength = data.length;\n\n if (data.length >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (data.length > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(data.length, 2);\n } else if (payloadLength === 127) {\n target.writeUInt32BE(0, 2);\n target.writeUInt32BE(data.length, 6);\n }\n\n if (!options.mask) return [target, data];\n\n randomFillSync(mask, 0, 4);\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (merge) {\n applyMask(data, mask, target, offset, data.length);\n return [target];\n }\n\n applyMask(data, mask, data, 0, data.length);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {String} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || data === '') {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n buf.write(data, 2);\n }\n\n if (this._deflating) {\n this.enqueue([this.doClose, buf, mask, cb]);\n } else {\n this.doClose(buf, mask, cb);\n }\n }\n\n /**\n * Frames and sends a close message.\n *\n * @param {Buffer} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @private\n */\n doClose(data, mask, cb) {\n this.sendFrame(\n Sender.frame(data, {\n fin: true,\n rsv1: false,\n opcode: 0x08,\n mask,\n readOnly: false\n }),\n cb\n );\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n const buf = toBuffer(data);\n\n if (buf.length > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n if (this._deflating) {\n this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]);\n } else {\n this.doPing(buf, mask, toBuffer.readOnly, cb);\n }\n }\n\n /**\n * Frames and sends a ping message.\n *\n * @param {Buffer} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified\n * @param {Function} [cb] Callback\n * @private\n */\n doPing(data, mask, readOnly, cb) {\n this.sendFrame(\n Sender.frame(data, {\n fin: true,\n rsv1: false,\n opcode: 0x09,\n mask,\n readOnly\n }),\n cb\n );\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n const buf = toBuffer(data);\n\n if (buf.length > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n if (this._deflating) {\n this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]);\n } else {\n this.doPong(buf, mask, toBuffer.readOnly, cb);\n }\n }\n\n /**\n * Frames and sends a pong message.\n *\n * @param {Buffer} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified\n * @param {Function} [cb] Callback\n * @private\n */\n doPong(data, mask, readOnly, cb) {\n this.sendFrame(\n Sender.frame(data, {\n fin: true,\n rsv1: false,\n opcode: 0x0a,\n mask,\n readOnly\n }),\n cb\n );\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const buf = toBuffer(data);\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (rsv1 && perMessageDeflate) {\n rsv1 = buf.length >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n if (perMessageDeflate) {\n const opts = {\n fin: options.fin,\n rsv1,\n opcode,\n mask: options.mask,\n readOnly: toBuffer.readOnly\n };\n\n if (this._deflating) {\n this.enqueue([this.dispatch, buf, this._compress, opts, cb]);\n } else {\n this.dispatch(buf, this._compress, opts, cb);\n }\n } else {\n this.sendFrame(\n Sender.frame(buf, {\n fin: options.fin,\n rsv1: false,\n opcode,\n mask: options.mask,\n readOnly: toBuffer.readOnly\n }),\n cb\n );\n }\n }\n\n /**\n * Dispatches a data message.\n *\n * @param {Buffer} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += data.length;\n this._deflating = true;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < this._queue.length; i++) {\n const callback = this._queue[i][4];\n\n if (typeof callback === 'function') callback(err);\n }\n\n return;\n }\n\n this._bufferedBytes -= data.length;\n this._deflating = false;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (!this._deflating && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[1].length;\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[1].length;\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {Buffer[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n","'use strict';\n\n/**\n * Class representing an event.\n *\n * @private\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @param {Object} target A reference to the target to which the event was\n * dispatched\n */\n constructor(type, target) {\n this.target = target;\n this.type = type;\n }\n}\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n * @private\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data\n * @param {WebSocket} target A reference to the target to which the event was\n * dispatched\n */\n constructor(data, target) {\n super('message', target);\n\n this.data = data;\n }\n}\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n * @private\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {Number} code The status code explaining why the connection is being\n * closed\n * @param {String} reason A human-readable string explaining why the\n * connection is closing\n * @param {WebSocket} target A reference to the target to which the event was\n * dispatched\n */\n constructor(code, reason, target) {\n super('close', target);\n\n this.wasClean = target._closeFrameReceived && target._closeFrameSent;\n this.reason = reason;\n this.code = code;\n }\n}\n\n/**\n * Class representing an open event.\n *\n * @extends Event\n * @private\n */\nclass OpenEvent extends Event {\n /**\n * Create a new `OpenEvent`.\n *\n * @param {WebSocket} target A reference to the target to which the event was\n * dispatched\n */\n constructor(target) {\n super('open', target);\n }\n}\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n * @private\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {Object} error The error that generated this event\n * @param {WebSocket} target A reference to the target to which the event was\n * dispatched\n */\n constructor(error, target) {\n super('error', target);\n\n this.message = error.message;\n this.error = error;\n }\n}\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {Function} listener The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean`` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, listener, options) {\n if (typeof listener !== 'function') return;\n\n function onMessage(data) {\n listener.call(this, new MessageEvent(data, this));\n }\n\n function onClose(code, message) {\n listener.call(this, new CloseEvent(code, message, this));\n }\n\n function onError(error) {\n listener.call(this, new ErrorEvent(error, this));\n }\n\n function onOpen() {\n listener.call(this, new OpenEvent(this));\n }\n\n const method = options && options.once ? 'once' : 'on';\n\n if (type === 'message') {\n onMessage._listener = listener;\n this[method](type, onMessage);\n } else if (type === 'close') {\n onClose._listener = listener;\n this[method](type, onClose);\n } else if (type === 'error') {\n onError._listener = listener;\n this[method](type, onError);\n } else if (type === 'open') {\n onOpen._listener = listener;\n this[method](type, onOpen);\n } else {\n this[method](type, listener);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {Function} listener The listener to remove\n * @public\n */\n removeEventListener(type, listener) {\n const listeners = this.listeners(type);\n\n for (let i = 0; i < listeners.length; i++) {\n if (listeners[i] === listener || listeners[i]._listener === listener) {\n this.removeListener(type, listeners[i]);\n }\n }\n }\n};\n\nmodule.exports = EventTarget;\n","'use strict';\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n\n if (header === undefined || header === '') return offers;\n\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 /* ' ' */ || code === 0x09 /* '\\t' */) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n GUID,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst { addEventListener, removeEventListener } = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst protocolVersions = [8, 13];\nconst closeTimeout = 30 * 1000;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = '';\n this._closeTimer = null;\n this._extensions = {};\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (Array.isArray(protocols)) {\n protocols = protocols.join(', ');\n } else if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = undefined;\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._isServer = true;\n }\n }\n\n /**\n * This deviates from the WHATWG interface since ws doesn't support the\n * required default \"blob\" type (instead we define a custom \"nodebuffer\"\n * type).\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return undefined;\n }\n\n /* istanbul ignore next */\n set onclose(listener) {}\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return undefined;\n }\n\n /* istanbul ignore next */\n set onerror(listener) {}\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return undefined;\n }\n\n /* istanbul ignore next */\n set onopen(listener) {}\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return undefined;\n }\n\n /* istanbul ignore next */\n set onmessage(listener) {}\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {(net.Socket|tls.Socket)} socket The network socket between the\n * server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Number} [maxPayload=0] The maximum allowed message size\n * @private\n */\n setSocket(socket, head, maxPayload) {\n const receiver = new Receiver(\n this.binaryType,\n this._extensions,\n this._isServer,\n maxPayload\n );\n\n this._sender = new Sender(socket, this._extensions);\n this._receiver = receiver;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n socket.setTimeout(0);\n socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {String} [data] A string explaining why the connection is closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n return abortHandshake(this, this._req, msg);\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n //\n // Specify a timeout for the closing handshake to complete.\n //\n this._closeTimer = setTimeout(\n this._socket.destroy.bind(this._socket),\n closeTimeout\n );\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n return abortHandshake(this, this._req, msg);\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n const listeners = this.listeners(method);\n for (let i = 0; i < listeners.length; i++) {\n if (listeners[i]._listener) return listeners[i]._listener;\n }\n\n return undefined;\n },\n set(listener) {\n const listeners = this.listeners(method);\n for (let i = 0; i < listeners.length; i++) {\n //\n // Remove only the listeners added via `addEventListener`.\n //\n if (listeners[i]._listener) this.removeListener(method, listeners[i]);\n }\n this.addEventListener(method, listener);\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {String} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n protocolVersion: protocolVersions[1],\n maxPayload: 100 * 1024 * 1024,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n createConnection: undefined,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: undefined,\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n websocket._url = address.href;\n } else {\n parsedUrl = new URL(address);\n websocket._url = address;\n }\n\n const isUnixSocket = parsedUrl.protocol === 'ws+unix:';\n\n if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {\n throw new Error(`Invalid URL: ${websocket.url}`);\n }\n\n const isSecure =\n parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const get = isSecure ? https.get : http.get;\n let perMessageDeflate;\n\n opts.createConnection = isSecure ? tlsConnect : netConnect;\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket',\n ...opts.headers\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate(\n opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},\n false,\n opts.maxPayload\n );\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols) {\n opts.headers['Sec-WebSocket-Protocol'] = protocols;\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isUnixSocket) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req = (websocket._req = get(opts));\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req.aborted) return;\n\n req = websocket._req = null;\n websocket._readyState = WebSocket.CLOSING;\n websocket.emit('error', err);\n websocket.emitClose();\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n const addr = new URL(location, address);\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the `upgrade`\n // event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n const protList = (protocols || '').split(/, */);\n let protError;\n\n if (!protocols && serverProt) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (protocols && !serverProt) {\n protError = 'Server sent no subprotocol';\n } else if (serverProt && !protList.includes(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (extensionNames.length) {\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message =\n 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n }\n\n websocket.setSocket(socket, head, opts.maxPayload);\n });\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n stream.once('abort', websocket.emitClose.bind(websocket));\n websocket.emit('error', err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n cb(err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {String} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._socket.removeListener('data', socketOnData);\n websocket._socket.resume();\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n this[kWebSocket]._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n websocket._socket.removeListener('data', socketOnData);\n websocket._socket.resume();\n\n websocket.close(err[kStatusCode]);\n websocket.emit('error', err);\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message\n * @private\n */\nfunction receiverOnMessage(data) {\n this[kWebSocket].emit('message', data);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n websocket.pong(data, !websocket._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * The listener of the `net.Socket` `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written and `readable.read()`\n // will return `null`. If instead, the socket is paused, any possible buffered\n // data will be read as a single chunk and emitted synchronously in a single\n // `'data'` event.\n //\n websocket._socket.read();\n websocket._receiver.end();\n\n this.removeListener('data', socketOnData);\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the `net.Socket` `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the `net.Socket` `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the `net.Socket` `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","'use strict';\n\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let resumeOnReceiverDrain = true;\n let terminateOnDestroy = true;\n\n function receiverOnDrain() {\n if (resumeOnReceiverDrain) ws._socket.resume();\n }\n\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n ws._receiver.removeAllListeners('drain');\n ws._receiver.on('drain', receiverOnDrain);\n });\n } else {\n ws._receiver.removeAllListeners('drain');\n ws._receiver.on('drain', receiverOnDrain);\n }\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg) {\n if (!duplex.push(msg)) {\n resumeOnReceiverDrain = false;\n ws._socket.pause();\n }\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.readyState === ws.OPEN && !resumeOnReceiverDrain) {\n resumeOnReceiverDrain = true;\n if (!ws._receiver._writableState.needDrain) ws._socket.resume();\n }\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^net|tls|https$\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst https = require('https');\nconst net = require('net');\nconst tls = require('tls');\nconst { createHash } = require('crypto');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst WebSocket = require('./websocket');\nconst { format, parse } = require('./extension');\nconst { GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n maxPayload: 100 * 1024 * 1024,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) this.clients = new Set();\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Close the server.\n *\n * @param {Function} [cb] Callback\n * @public\n */\n close(cb) {\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSED) {\n process.nextTick(emitClose, this);\n return;\n }\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n //\n // Terminate all associated clients.\n //\n if (this.clients) {\n for (const client of this.clients) client.terminate();\n }\n\n const server = this._server;\n\n if (server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // Close the http server if it was internally created.\n //\n if (this.options.port != null) {\n server.close(emitClose.bind(undefined, this));\n return;\n }\n }\n\n process.nextTick(emitClose, this);\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {(net.Socket|tls.Socket)} socket The network socket between the\n * server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key =\n req.headers['sec-websocket-key'] !== undefined\n ? req.headers['sec-websocket-key'].trim()\n : false;\n const version = +req.headers['sec-websocket-version'];\n const extensions = {};\n\n if (\n req.method !== 'GET' ||\n req.headers.upgrade.toLowerCase() !== 'websocket' ||\n !key ||\n !keyRegex.test(key) ||\n (version !== 8 && version !== 13) ||\n !this.shouldHandle(req)\n ) {\n return abortHandshake(socket, 400);\n }\n\n if (this.options.perMessageDeflate) {\n const perMessageDeflate = new PerMessageDeflate(\n this.options.perMessageDeflate,\n true,\n this.options.maxPayload\n );\n\n try {\n const offers = parse(req.headers['sec-websocket-extensions']);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n return abortHandshake(socket, 400);\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(key, extensions, req, socket, head, cb);\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(key, extensions, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Object} extensions The accepted extensions\n * @param {http.IncomingMessage} req The request object\n * @param {(net.Socket|tls.Socket)} socket The network socket between the\n * server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(key, extensions, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new WebSocket(null);\n let protocol = req.headers['sec-websocket-protocol'];\n\n if (protocol) {\n protocol = protocol.split(',').map(trim);\n\n //\n // Optionally call external protocol selection handler.\n //\n if (this.options.handleProtocols) {\n protocol = this.options.handleProtocols(protocol, req);\n } else {\n protocol = protocol[0];\n }\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, this.options.maxPayload);\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => this.clients.delete(ws));\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of \n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle premature socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n if (socket.writable) {\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.write(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n }\n\n socket.removeListener('error', socketOnError);\n socket.destroy();\n}\n\n/**\n * Remove whitespace characters from both ends of a string.\n *\n * @param {String} str The string\n * @return {String} A new string representing `str` stripped of whitespace\n * characters from both its beginning and end\n * @private\n */\nfunction trim(str) {\n return str.trim();\n}\n","'use strict';\n\nconst WebSocket = require('./lib/websocket');\n\nWebSocket.createWebSocketStream = require('./lib/stream');\nWebSocket.Server = require('./lib/websocket-server');\nWebSocket.Receiver = require('./lib/receiver');\nWebSocket.Sender = require('./lib/sender');\n\nmodule.exports = WebSocket;\n","import chalk from 'chalk'\nimport { Server, STATUS_CODES } from 'http'\nimport {\n createServer as createHttpsServer,\n ServerOptions as HttpsServerOptions\n} from 'https'\nimport WebSocket from 'ws'\nimport { ErrorPayload, HMRPayload } from 'types/hmrPayload'\nimport { ResolvedConfig } from '..'\nimport { isObject } from '../utils'\nimport { Socket } from 'net'\nexport const HMR_HEADER = 'vite-hmr'\n\nexport interface WebSocketServer {\n send(payload: HMRPayload): void\n close(): Promise\n}\n\nexport function createWebSocketServer(\n server: Server | null,\n config: ResolvedConfig,\n httpsOptions?: HttpsServerOptions\n): WebSocketServer {\n let wss: WebSocket.Server\n let httpsServer: Server | undefined = undefined\n\n const hmr = isObject(config.server.hmr) && config.server.hmr\n const wsServer = (hmr && hmr.server) || server\n\n if (wsServer) {\n wss = new WebSocket.Server({ noServer: true })\n wsServer.on('upgrade', (req, socket, head) => {\n if (req.headers['sec-websocket-protocol'] === HMR_HEADER) {\n wss.handleUpgrade(req, socket as Socket, head, (ws) => {\n wss.emit('connection', ws, req)\n })\n }\n })\n } else {\n const websocketServerOptions: WebSocket.ServerOptions = {}\n const port = (hmr && hmr.port) || 24678\n if (httpsOptions) {\n // if we're serving the middlewares over https, the ws library doesn't support automatically creating an https server, so we need to do it ourselves\n // create an inline https server and mount the websocket server to it\n httpsServer = createHttpsServer(httpsOptions, (req, res) => {\n const statusCode = 426\n const body = STATUS_CODES[statusCode]\n if (!body)\n throw new Error(\n `No body text found for the ${statusCode} status code`\n )\n\n res.writeHead(statusCode, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n })\n res.end(body)\n })\n\n httpsServer.listen(port)\n websocketServerOptions.server = httpsServer\n } else {\n // we don't need to serve over https, just let ws handle its own server\n websocketServerOptions.port = port\n }\n\n // vite dev server in middleware mode\n wss = new WebSocket.Server(websocketServerOptions)\n }\n\n wss.on('connection', (socket) => {\n socket.send(JSON.stringify({ type: 'connected' }))\n if (bufferedError) {\n socket.send(JSON.stringify(bufferedError))\n bufferedError = null\n }\n })\n\n wss.on('error', (e: Error & { code: string }) => {\n if (e.code !== 'EADDRINUSE') {\n config.logger.error(\n chalk.red(`WebSocket server error:\\n${e.stack || e.message}`),\n { error: e }\n )\n }\n })\n\n // On page reloads, if a file fails to compile and returns 500, the server\n // sends the error payload before the client connection is established.\n // If we have no open clients, buffer the error and send it to the next\n // connected client.\n let bufferedError: ErrorPayload | null = null\n\n return {\n send(payload: HMRPayload) {\n if (payload.type === 'error' && !wss.clients.size) {\n bufferedError = payload\n return\n }\n\n const stringified = JSON.stringify(payload)\n wss.clients.forEach((client) => {\n if (client.readyState === WebSocket.OPEN) {\n client.send(stringified)\n }\n })\n },\n\n close() {\n return new Promise((resolve, reject) => {\n wss.close((err) => {\n if (err) {\n reject(err)\n } else {\n if (httpsServer) {\n httpsServer.close((err) => {\n if (err) {\n reject(err)\n } else {\n resolve()\n }\n })\n } else {\n resolve()\n }\n }\n })\n })\n }\n }\n}\n","import { parse as parseUrl } from 'url'\nimport { ViteDevServer } from '..'\nimport { Connect } from 'types/connect'\n\n// this middleware is only active when (config.base !== '/')\n\nexport function baseMiddleware({\n config\n}: ViteDevServer): Connect.NextHandleFunction {\n const base = config.base\n\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return function viteBaseMiddleware(req, res, next) {\n const url = req.url!\n const parsed = parseUrl(url)\n const path = parsed.pathname || '/'\n\n if (path.startsWith(base)) {\n // rewrite url to remove base.. this ensures that other middleware does\n // not need to consider base being prepended or not\n req.url = url.replace(base, '/')\n return next()\n }\n\n // skip redirect and error fallback on middleware mode, #4057\n if (config.server.middlewareMode) {\n return next()\n }\n\n if (path === '/' || path === '/index.html') {\n // redirect root visit to based url\n res.writeHead(302, {\n Location: base\n })\n res.end()\n return\n } else if (req.headers.accept?.includes('text/html')) {\n // non-based page visit\n const redirectPath = base + url.slice(1)\n res.writeHead(404, {\n 'Content-Type': 'text/html'\n })\n res.end(\n `The server is configured with a public base URL of ${base} - ` +\n `did you mean to visit ${redirectPath} instead?`\n )\n return\n }\n\n next()\n }\n}\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","'use strict';\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nmodule.exports = function required(port, protocol) {\n protocol = protocol.split(':')[0];\n port = +port;\n\n if (!port) return false;\n\n switch (protocol) {\n case 'http':\n case 'ws':\n return port !== 80;\n\n case 'https':\n case 'wss':\n return port !== 443;\n\n case 'ftp':\n return port !== 21;\n\n case 'gopher':\n return port !== 70;\n\n case 'file':\n return false;\n }\n\n return port !== 0;\n};\n","var common = exports,\n url = require('url'),\n extend = require('util')._extend,\n required = require('requires-port');\n\nvar upgradeHeader = /(^|,)\\s*upgrade\\s*($|,)/i,\n isSSL = /^https|wss/;\n\n/**\n * Simple Regex for testing if protocol is https\n */\ncommon.isSSL = isSSL;\n/**\n * Copies the right headers from `options` and `req` to\n * `outgoing` which is then used to fire the proxied\n * request.\n *\n * Examples:\n *\n * common.setupOutgoing(outgoing, options, req)\n * // => { host: ..., hostname: ...}\n *\n * @param {Object} Outgoing Base object to be filled with required properties\n * @param {Object} Options Config object passed to the proxy\n * @param {ClientRequest} Req Request Object\n * @param {String} Forward String to select forward or target\n * \n * @return {Object} Outgoing Object with all required properties set\n *\n * @api private\n */\n\ncommon.setupOutgoing = function(outgoing, options, req, forward) {\n outgoing.port = options[forward || 'target'].port ||\n (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80);\n\n ['host', 'hostname', 'socketPath', 'pfx', 'key',\n 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach(\n function(e) { outgoing[e] = options[forward || 'target'][e]; }\n );\n\n outgoing.method = options.method || req.method;\n outgoing.headers = extend({}, req.headers);\n\n if (options.headers){\n extend(outgoing.headers, options.headers);\n }\n\n if (options.auth) {\n outgoing.auth = options.auth;\n }\n \n if (options.ca) {\n outgoing.ca = options.ca;\n }\n\n if (isSSL.test(options[forward || 'target'].protocol)) {\n outgoing.rejectUnauthorized = (typeof options.secure === \"undefined\") ? true : options.secure;\n }\n\n\n outgoing.agent = options.agent || false;\n outgoing.localAddress = options.localAddress;\n\n //\n // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do\n // as node core doesn't handle this COMPLETELY properly yet.\n //\n if (!outgoing.agent) {\n outgoing.headers = outgoing.headers || {};\n if (typeof outgoing.headers.connection !== 'string'\n || !upgradeHeader.test(outgoing.headers.connection)\n ) { outgoing.headers.connection = 'close'; }\n }\n\n\n // the final path is target path + relative path requested by user:\n var target = options[forward || 'target'];\n var targetPath = target && options.prependPath !== false\n ? (target.path || '')\n : '';\n\n //\n // Remark: Can we somehow not use url.parse as a perf optimization?\n //\n var outgoingPath = !options.toProxy\n ? (url.parse(req.url).path || '')\n : req.url;\n\n //\n // Remark: ignorePath will just straight up ignore whatever the request's\n // path is. This can be labeled as FOOT-GUN material if you do not know what\n // you are doing and are using conflicting options.\n //\n outgoingPath = !options.ignorePath ? outgoingPath : '';\n\n outgoing.path = common.urlJoin(targetPath, outgoingPath);\n\n if (options.changeOrigin) {\n outgoing.headers.host =\n required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host)\n ? outgoing.host + ':' + outgoing.port\n : outgoing.host;\n }\n return outgoing;\n};\n\n/**\n * Set the proper configuration for sockets,\n * set no delay and set keep alive, also set\n * the timeout to 0.\n *\n * Examples:\n *\n * common.setupSocket(socket)\n * // => Socket\n *\n * @param {Socket} Socket instance to setup\n * \n * @return {Socket} Return the configured socket.\n *\n * @api private\n */\n\ncommon.setupSocket = function(socket) {\n socket.setTimeout(0);\n socket.setNoDelay(true);\n\n socket.setKeepAlive(true, 0);\n\n return socket;\n};\n\n/**\n * Get the port number from the host. Or guess it based on the connection type.\n *\n * @param {Request} req Incoming HTTP request.\n *\n * @return {String} The port number.\n *\n * @api private\n */\ncommon.getPort = function(req) {\n var res = req.headers.host ? req.headers.host.match(/:(\\d+)/) : '';\n\n return res ?\n res[1] :\n common.hasEncryptedConnection(req) ? '443' : '80';\n};\n\n/**\n * Check if the request has an encrypted connection.\n *\n * @param {Request} req Incoming HTTP request.\n *\n * @return {Boolean} Whether the connection is encrypted or not.\n *\n * @api private\n */\ncommon.hasEncryptedConnection = function(req) {\n return Boolean(req.connection.encrypted || req.connection.pair);\n};\n\n/**\n * OS-agnostic join (doesn't break on URLs like path.join does on Windows)>\n *\n * @return {String} The generated path.\n *\n * @api private\n */\n\ncommon.urlJoin = function() {\n //\n // We do not want to mess with the query string. All we want to touch is the path.\n //\n var args = Array.prototype.slice.call(arguments),\n lastIndex = args.length - 1,\n last = args[lastIndex],\n lastSegs = last.split('?'),\n retSegs;\n\n args[lastIndex] = lastSegs.shift();\n\n //\n // Join all strings, but remove empty strings so we don't get extra slashes from\n // joining e.g. ['', 'am']\n //\n retSegs = [\n args.filter(Boolean).join('/')\n .replace(/\\/+/g, '/')\n .replace('http:/', 'http://')\n .replace('https:/', 'https://')\n ];\n\n // Only join the query string if it exists so we don't have trailing a '?'\n // on every request\n\n // Handle case where there could be multiple ? in the URL.\n retSegs.push.apply(retSegs, lastSegs);\n\n return retSegs.join('?')\n};\n\n/**\n * Rewrites or removes the domain of a cookie header\n *\n * @param {String|Array} Header\n * @param {Object} Config, mapping of domain to rewritten domain.\n * '*' key to match any domain, null value to remove the domain.\n *\n * @api private\n */\ncommon.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) {\n if (Array.isArray(header)) {\n return header.map(function (headerElement) {\n return rewriteCookieProperty(headerElement, config, property);\n });\n }\n return header.replace(new RegExp(\"(;\\\\s*\" + property + \"=)([^;]+)\", 'i'), function(match, prefix, previousValue) {\n var newValue;\n if (previousValue in config) {\n newValue = config[previousValue];\n } else if ('*' in config) {\n newValue = config['*'];\n } else {\n //no match, return previous value\n return match;\n }\n if (newValue) {\n //replace value\n return prefix + newValue;\n } else {\n //remove value\n return '';\n }\n });\n};\n\n/**\n * Check the host and see if it potentially has a port in it (keep it simple)\n *\n * @returns {Boolean} Whether we have one or not\n *\n * @api private\n */\nfunction hasPort(host) {\n return !!~host.indexOf(':');\n};\n","var url = require('url'),\n common = require('../common');\n\n\nvar redirectRegex = /^201|30(1|2|7|8)$/;\n\n/*!\n * Array of passes.\n *\n * A `pass` is just a function that is executed on `req, res, options`\n * so that you can easily add new checks while still keeping the base\n * flexible.\n */\n\nmodule.exports = { // <--\n\n /**\n * If is a HTTP 1.0 request, remove chunk headers\n *\n * @param {ClientRequest} Req Request object\n * @param {IncomingMessage} Res Response object\n * @param {proxyResponse} Res Response object from the proxy request\n *\n * @api private\n */\n removeChunked: function removeChunked(req, res, proxyRes) {\n if (req.httpVersion === '1.0') {\n delete proxyRes.headers['transfer-encoding'];\n }\n },\n\n /**\n * If is a HTTP 1.0 request, set the correct connection header\n * or if connection header not present, then use `keep-alive`\n *\n * @param {ClientRequest} Req Request object\n * @param {IncomingMessage} Res Response object\n * @param {proxyResponse} Res Response object from the proxy request\n *\n * @api private\n */\n setConnection: function setConnection(req, res, proxyRes) {\n if (req.httpVersion === '1.0') {\n proxyRes.headers.connection = req.headers.connection || 'close';\n } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) {\n proxyRes.headers.connection = req.headers.connection || 'keep-alive';\n }\n },\n\n setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) {\n if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)\n && proxyRes.headers['location']\n && redirectRegex.test(proxyRes.statusCode)) {\n var target = url.parse(options.target);\n var u = url.parse(proxyRes.headers['location']);\n\n // make sure the redirected host matches the target host before rewriting\n if (target.host != u.host) {\n return;\n }\n\n if (options.hostRewrite) {\n u.host = options.hostRewrite;\n } else if (options.autoRewrite) {\n u.host = req.headers['host'];\n }\n if (options.protocolRewrite) {\n u.protocol = options.protocolRewrite;\n }\n\n proxyRes.headers['location'] = u.format();\n }\n },\n /**\n * Copy headers from proxyResponse to response\n * set each header in response object.\n *\n * @param {ClientRequest} Req Request object\n * @param {IncomingMessage} Res Response object\n * @param {proxyResponse} Res Response object from the proxy request\n * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain\n *\n * @api private\n */\n writeHeaders: function writeHeaders(req, res, proxyRes, options) {\n var rewriteCookieDomainConfig = options.cookieDomainRewrite,\n rewriteCookiePathConfig = options.cookiePathRewrite,\n preserveHeaderKeyCase = options.preserveHeaderKeyCase,\n rawHeaderKeyMap,\n setHeader = function(key, header) {\n if (header == undefined) return;\n if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') {\n header = common.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain');\n }\n if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') {\n header = common.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path');\n }\n res.setHeader(String(key).trim(), header);\n };\n\n if (typeof rewriteCookieDomainConfig === 'string') { //also test for ''\n rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig };\n }\n\n if (typeof rewriteCookiePathConfig === 'string') { //also test for ''\n rewriteCookiePathConfig = { '*': rewriteCookiePathConfig };\n }\n\n // message.rawHeaders is added in: v0.11.6\n // https://nodejs.org/api/http.html#http_message_rawheaders\n if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) {\n rawHeaderKeyMap = {};\n for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {\n var key = proxyRes.rawHeaders[i];\n rawHeaderKeyMap[key.toLowerCase()] = key;\n }\n }\n\n Object.keys(proxyRes.headers).forEach(function(key) {\n var header = proxyRes.headers[key];\n if (preserveHeaderKeyCase && rawHeaderKeyMap) {\n key = rawHeaderKeyMap[key] || key;\n }\n setHeader(key, header);\n });\n },\n\n /**\n * Set the statusCode from the proxyResponse\n *\n * @param {ClientRequest} Req Request object\n * @param {IncomingMessage} Res Response object\n * @param {proxyResponse} Res Response object from the proxy request\n *\n * @api private\n */\n writeStatusCode: function writeStatusCode(req, res, proxyRes) {\n // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers])\n if(proxyRes.statusMessage) {\n res.statusCode = proxyRes.statusCode;\n res.statusMessage = proxyRes.statusMessage;\n } else {\n res.statusCode = proxyRes.statusCode;\n }\n }\n\n};\n","var debug;\n\nmodule.exports = function () {\n if (!debug) {\n try {\n /* eslint global-require: off */\n debug = require(\"debug\")(\"follow-redirects\");\n }\n catch (error) { /* */ }\n if (typeof debug !== \"function\") {\n debug = function () { /* */ };\n }\n }\n debug.apply(null, arguments);\n};\n","var url = require(\"url\");\nvar URL = url.URL;\nvar http = require(\"http\");\nvar https = require(\"https\");\nvar Writable = require(\"stream\").Writable;\nvar assert = require(\"assert\");\nvar debug = require(\"./debug\");\n\n// Create handlers that pass events from native requests\nvar events = [\"abort\", \"aborted\", \"connect\", \"error\", \"socket\", \"timeout\"];\nvar eventHandlers = Object.create(null);\nevents.forEach(function (event) {\n eventHandlers[event] = function (arg1, arg2, arg3) {\n this._redirectable.emit(event, arg1, arg2, arg3);\n };\n});\n\n// Error types with codes\nvar RedirectionError = createErrorType(\n \"ERR_FR_REDIRECTION_FAILURE\",\n \"\"\n);\nvar TooManyRedirectsError = createErrorType(\n \"ERR_FR_TOO_MANY_REDIRECTS\",\n \"Maximum number of redirects exceeded\"\n);\nvar MaxBodyLengthExceededError = createErrorType(\n \"ERR_FR_MAX_BODY_LENGTH_EXCEEDED\",\n \"Request body larger than maxBodyLength limit\"\n);\nvar WriteAfterEndError = createErrorType(\n \"ERR_STREAM_WRITE_AFTER_END\",\n \"write after end\"\n);\n\n// An HTTP(S) request that can be redirected\nfunction RedirectableRequest(options, responseCallback) {\n // Initialize the request\n Writable.call(this);\n this._sanitizeOptions(options);\n this._options = options;\n this._ended = false;\n this._ending = false;\n this._redirectCount = 0;\n this._redirects = [];\n this._requestBodyLength = 0;\n this._requestBodyBuffers = [];\n\n // Attach a callback if passed\n if (responseCallback) {\n this.on(\"response\", responseCallback);\n }\n\n // React to responses of native requests\n var self = this;\n this._onNativeResponse = function (response) {\n self._processResponse(response);\n };\n\n // Perform the first request\n this._performRequest();\n}\nRedirectableRequest.prototype = Object.create(Writable.prototype);\n\nRedirectableRequest.prototype.abort = function () {\n abortRequest(this._currentRequest);\n this.emit(\"abort\");\n};\n\n// Writes buffered data to the current native request\nRedirectableRequest.prototype.write = function (data, encoding, callback) {\n // Writing is not allowed if end has been called\n if (this._ending) {\n throw new WriteAfterEndError();\n }\n\n // Validate input and shift parameters if necessary\n if (!(typeof data === \"string\" || typeof data === \"object\" && (\"length\" in data))) {\n throw new TypeError(\"data should be a string, Buffer or Uint8Array\");\n }\n if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n\n // Ignore empty buffers, since writing them doesn't invoke the callback\n // https://github.com/nodejs/node/issues/22066\n if (data.length === 0) {\n if (callback) {\n callback();\n }\n return;\n }\n // Only write when we don't exceed the maximum body length\n if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {\n this._requestBodyLength += data.length;\n this._requestBodyBuffers.push({ data: data, encoding: encoding });\n this._currentRequest.write(data, encoding, callback);\n }\n // Error when we exceed the maximum body length\n else {\n this.emit(\"error\", new MaxBodyLengthExceededError());\n this.abort();\n }\n};\n\n// Ends the current native request\nRedirectableRequest.prototype.end = function (data, encoding, callback) {\n // Shift parameters if necessary\n if (typeof data === \"function\") {\n callback = data;\n data = encoding = null;\n }\n else if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n\n // Write data if needed and end\n if (!data) {\n this._ended = this._ending = true;\n this._currentRequest.end(null, null, callback);\n }\n else {\n var self = this;\n var currentRequest = this._currentRequest;\n this.write(data, encoding, function () {\n self._ended = true;\n currentRequest.end(null, null, callback);\n });\n this._ending = true;\n }\n};\n\n// Sets a header value on the current native request\nRedirectableRequest.prototype.setHeader = function (name, value) {\n this._options.headers[name] = value;\n this._currentRequest.setHeader(name, value);\n};\n\n// Clears a header value on the current native request\nRedirectableRequest.prototype.removeHeader = function (name) {\n delete this._options.headers[name];\n this._currentRequest.removeHeader(name);\n};\n\n// Global timeout for all underlying requests\nRedirectableRequest.prototype.setTimeout = function (msecs, callback) {\n var self = this;\n if (callback) {\n this.on(\"timeout\", callback);\n }\n\n function destroyOnTimeout(socket) {\n socket.setTimeout(msecs);\n socket.removeListener(\"timeout\", socket.destroy);\n socket.addListener(\"timeout\", socket.destroy);\n }\n\n // Sets up a timer to trigger a timeout event\n function startTimer(socket) {\n if (self._timeout) {\n clearTimeout(self._timeout);\n }\n self._timeout = setTimeout(function () {\n self.emit(\"timeout\");\n clearTimer();\n }, msecs);\n destroyOnTimeout(socket);\n }\n\n // Prevent a timeout from triggering\n function clearTimer() {\n clearTimeout(this._timeout);\n if (callback) {\n self.removeListener(\"timeout\", callback);\n }\n if (!this.socket) {\n self._currentRequest.removeListener(\"socket\", startTimer);\n }\n }\n\n // Start the timer when the socket is opened\n if (this.socket) {\n startTimer(this.socket);\n }\n else {\n this._currentRequest.once(\"socket\", startTimer);\n }\n\n this.on(\"socket\", destroyOnTimeout);\n this.once(\"response\", clearTimer);\n this.once(\"error\", clearTimer);\n\n return this;\n};\n\n// Proxy all other public ClientRequest methods\n[\n \"flushHeaders\", \"getHeader\",\n \"setNoDelay\", \"setSocketKeepAlive\",\n].forEach(function (method) {\n RedirectableRequest.prototype[method] = function (a, b) {\n return this._currentRequest[method](a, b);\n };\n});\n\n// Proxy all public ClientRequest properties\n[\"aborted\", \"connection\", \"socket\"].forEach(function (property) {\n Object.defineProperty(RedirectableRequest.prototype, property, {\n get: function () { return this._currentRequest[property]; },\n });\n});\n\nRedirectableRequest.prototype._sanitizeOptions = function (options) {\n // Ensure headers are always present\n if (!options.headers) {\n options.headers = {};\n }\n\n // Since http.request treats host as an alias of hostname,\n // but the url module interprets host as hostname plus port,\n // eliminate the host property to avoid confusion.\n if (options.host) {\n // Use hostname if set, because it has precedence\n if (!options.hostname) {\n options.hostname = options.host;\n }\n delete options.host;\n }\n\n // Complete the URL object when necessary\n if (!options.pathname && options.path) {\n var searchPos = options.path.indexOf(\"?\");\n if (searchPos < 0) {\n options.pathname = options.path;\n }\n else {\n options.pathname = options.path.substring(0, searchPos);\n options.search = options.path.substring(searchPos);\n }\n }\n};\n\n\n// Executes the next native request (initial or redirect)\nRedirectableRequest.prototype._performRequest = function () {\n // Load the native protocol\n var protocol = this._options.protocol;\n var nativeProtocol = this._options.nativeProtocols[protocol];\n if (!nativeProtocol) {\n this.emit(\"error\", new TypeError(\"Unsupported protocol \" + protocol));\n return;\n }\n\n // If specified, use the agent corresponding to the protocol\n // (HTTP and HTTPS use different types of agents)\n if (this._options.agents) {\n var scheme = protocol.substr(0, protocol.length - 1);\n this._options.agent = this._options.agents[scheme];\n }\n\n // Create the native request\n var request = this._currentRequest =\n nativeProtocol.request(this._options, this._onNativeResponse);\n this._currentUrl = url.format(this._options);\n\n // Set up event handlers\n request._redirectable = this;\n for (var e = 0; e < events.length; e++) {\n request.on(events[e], eventHandlers[events[e]]);\n }\n\n // End a redirected request\n // (The first request must be ended explicitly with RedirectableRequest#end)\n if (this._isRedirect) {\n // Write the request entity and end.\n var i = 0;\n var self = this;\n var buffers = this._requestBodyBuffers;\n (function writeNext(error) {\n // Only write if this request has not been redirected yet\n /* istanbul ignore else */\n if (request === self._currentRequest) {\n // Report any write errors\n /* istanbul ignore if */\n if (error) {\n self.emit(\"error\", error);\n }\n // Write the next buffer if there are still left\n else if (i < buffers.length) {\n var buffer = buffers[i++];\n /* istanbul ignore else */\n if (!request.finished) {\n request.write(buffer.data, buffer.encoding, writeNext);\n }\n }\n // End the request if `end` has been called on us\n else if (self._ended) {\n request.end();\n }\n }\n }());\n }\n};\n\n// Processes a response from the current native request\nRedirectableRequest.prototype._processResponse = function (response) {\n // Store the redirected response\n var statusCode = response.statusCode;\n if (this._options.trackRedirects) {\n this._redirects.push({\n url: this._currentUrl,\n headers: response.headers,\n statusCode: statusCode,\n });\n }\n\n // RFC7231§6.4: The 3xx (Redirection) class of status code indicates\n // that further action needs to be taken by the user agent in order to\n // fulfill the request. If a Location header field is provided,\n // the user agent MAY automatically redirect its request to the URI\n // referenced by the Location field value,\n // even if the specific status code is not understood.\n var location = response.headers.location;\n if (location && this._options.followRedirects !== false &&\n statusCode >= 300 && statusCode < 400) {\n // Abort the current request\n abortRequest(this._currentRequest);\n // Discard the remainder of the response to avoid waiting for data\n response.destroy();\n\n // RFC7231§6.4: A client SHOULD detect and intervene\n // in cyclical redirections (i.e., \"infinite\" redirection loops).\n if (++this._redirectCount > this._options.maxRedirects) {\n this.emit(\"error\", new TooManyRedirectsError());\n return;\n }\n\n // RFC7231§6.4: Automatic redirection needs to done with\n // care for methods not known to be safe, […]\n // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change\n // the request method from POST to GET for the subsequent request.\n if ((statusCode === 301 || statusCode === 302) && this._options.method === \"POST\" ||\n // RFC7231§6.4.4: The 303 (See Other) status code indicates that\n // the server is redirecting the user agent to a different resource […]\n // A user agent can perform a retrieval request targeting that URI\n // (a GET or HEAD request if using HTTP) […]\n (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {\n this._options.method = \"GET\";\n // Drop a possible entity and headers related to it\n this._requestBodyBuffers = [];\n removeMatchingHeaders(/^content-/i, this._options.headers);\n }\n\n // Drop the Host header, as the redirect might lead to a different host\n var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) ||\n url.parse(this._currentUrl).hostname;\n\n // Create the redirected request\n var redirectUrl = url.resolve(this._currentUrl, location);\n debug(\"redirecting to\", redirectUrl);\n this._isRedirect = true;\n var redirectUrlParts = url.parse(redirectUrl);\n Object.assign(this._options, redirectUrlParts);\n\n // Drop the Authorization header if redirecting to another host\n if (redirectUrlParts.hostname !== previousHostName) {\n removeMatchingHeaders(/^authorization$/i, this._options.headers);\n }\n\n // Evaluate the beforeRedirect callback\n if (typeof this._options.beforeRedirect === \"function\") {\n var responseDetails = { headers: response.headers };\n try {\n this._options.beforeRedirect.call(null, this._options, responseDetails);\n }\n catch (err) {\n this.emit(\"error\", err);\n return;\n }\n this._sanitizeOptions(this._options);\n }\n\n // Perform the redirected request\n try {\n this._performRequest();\n }\n catch (cause) {\n var error = new RedirectionError(\"Redirected request failed: \" + cause.message);\n error.cause = cause;\n this.emit(\"error\", error);\n }\n }\n else {\n // The response is not a redirect; return it as-is\n response.responseUrl = this._currentUrl;\n response.redirects = this._redirects;\n this.emit(\"response\", response);\n\n // Clean up\n this._requestBodyBuffers = [];\n }\n};\n\n// Wraps the key/value object of protocols with redirect functionality\nfunction wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024,\n };\n\n // Wrap each protocol\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);\n\n // Executes a request, following redirects\n function request(input, options, callback) {\n // Parse parameters\n if (typeof input === \"string\") {\n var urlStr = input;\n try {\n input = urlToOptions(new URL(urlStr));\n }\n catch (err) {\n /* istanbul ignore next */\n input = url.parse(urlStr);\n }\n }\n else if (URL && (input instanceof URL)) {\n input = urlToOptions(input);\n }\n else {\n callback = options;\n options = input;\n input = { protocol: protocol };\n }\n if (typeof options === \"function\") {\n callback = options;\n options = null;\n }\n\n // Set defaults\n options = Object.assign({\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength,\n }, input, options);\n options.nativeProtocols = nativeProtocols;\n\n assert.equal(options.protocol, protocol, \"protocol mismatch\");\n debug(\"options\", options);\n return new RedirectableRequest(options, callback);\n }\n\n // Executes a GET request, following redirects\n function get(input, options, callback) {\n var wrappedRequest = wrappedProtocol.request(input, options, callback);\n wrappedRequest.end();\n return wrappedRequest;\n }\n\n // Expose the properties on the wrapped protocol\n Object.defineProperties(wrappedProtocol, {\n request: { value: request, configurable: true, enumerable: true, writable: true },\n get: { value: get, configurable: true, enumerable: true, writable: true },\n });\n });\n return exports;\n}\n\n/* istanbul ignore next */\nfunction noop() { /* empty */ }\n\n// from https://github.com/nodejs/node/blob/master/lib/internal/url.js\nfunction urlToOptions(urlObject) {\n var options = {\n protocol: urlObject.protocol,\n hostname: urlObject.hostname.startsWith(\"[\") ?\n /* istanbul ignore next */\n urlObject.hostname.slice(1, -1) :\n urlObject.hostname,\n hash: urlObject.hash,\n search: urlObject.search,\n pathname: urlObject.pathname,\n path: urlObject.pathname + urlObject.search,\n href: urlObject.href,\n };\n if (urlObject.port !== \"\") {\n options.port = Number(urlObject.port);\n }\n return options;\n}\n\nfunction removeMatchingHeaders(regex, headers) {\n var lastValue;\n for (var header in headers) {\n if (regex.test(header)) {\n lastValue = headers[header];\n delete headers[header];\n }\n }\n return lastValue;\n}\n\nfunction createErrorType(code, defaultMessage) {\n function CustomError(message) {\n Error.captureStackTrace(this, this.constructor);\n this.message = message || defaultMessage;\n }\n CustomError.prototype = new Error();\n CustomError.prototype.constructor = CustomError;\n CustomError.prototype.name = \"Error [\" + code + \"]\";\n CustomError.prototype.code = code;\n return CustomError;\n}\n\nfunction abortRequest(request) {\n for (var e = 0; e < events.length; e++) {\n request.removeListener(events[e], eventHandlers[events[e]]);\n }\n request.on(\"error\", noop);\n request.abort();\n}\n\n// Exports\nmodule.exports = wrap({ http: http, https: https });\nmodule.exports.wrap = wrap;\n","var httpNative = require('http'),\n httpsNative = require('https'),\n web_o = require('./web-outgoing'),\n common = require('../common'),\n followRedirects = require('follow-redirects');\n\nweb_o = Object.keys(web_o).map(function(pass) {\n return web_o[pass];\n});\n\nvar nativeAgents = { http: httpNative, https: httpsNative };\n\n/*!\n * Array of passes.\n *\n * A `pass` is just a function that is executed on `req, res, options`\n * so that you can easily add new checks while still keeping the base\n * flexible.\n */\n\n\nmodule.exports = {\n\n /**\n * Sets `content-length` to '0' if request is of DELETE type.\n *\n * @param {ClientRequest} Req Request object\n * @param {IncomingMessage} Res Response object\n * @param {Object} Options Config object passed to the proxy\n *\n * @api private\n */\n\n deleteLength: function deleteLength(req, res, options) {\n if((req.method === 'DELETE' || req.method === 'OPTIONS')\n && !req.headers['content-length']) {\n req.headers['content-length'] = '0';\n delete req.headers['transfer-encoding'];\n }\n },\n\n /**\n * Sets timeout in request socket if it was specified in options.\n *\n * @param {ClientRequest} Req Request object\n * @param {IncomingMessage} Res Response object\n * @param {Object} Options Config object passed to the proxy\n *\n * @api private\n */\n\n timeout: function timeout(req, res, options) {\n if(options.timeout) {\n req.socket.setTimeout(options.timeout);\n }\n },\n\n /**\n * Sets `x-forwarded-*` headers if specified in config.\n *\n * @param {ClientRequest} Req Request object\n * @param {IncomingMessage} Res Response object\n * @param {Object} Options Config object passed to the proxy\n *\n * @api private\n */\n\n XHeaders: function XHeaders(req, res, options) {\n if(!options.xfwd) return;\n\n var encrypted = req.isSpdy || common.hasEncryptedConnection(req);\n var values = {\n for : req.connection.remoteAddress || req.socket.remoteAddress,\n port : common.getPort(req),\n proto: encrypted ? 'https' : 'http'\n };\n\n ['for', 'port', 'proto'].forEach(function(header) {\n req.headers['x-forwarded-' + header] =\n (req.headers['x-forwarded-' + header] || '') +\n (req.headers['x-forwarded-' + header] ? ',' : '') +\n values[header];\n });\n\n req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || '';\n },\n\n /**\n * Does the actual proxying. If `forward` is enabled fires up\n * a ForwardStream, same happens for ProxyStream. The request\n * just dies otherwise.\n *\n * @param {ClientRequest} Req Request object\n * @param {IncomingMessage} Res Response object\n * @param {Object} Options Config object passed to the proxy\n *\n * @api private\n */\n\n stream: function stream(req, res, options, _, server, clb) {\n\n // And we begin!\n server.emit('start', req, res, options.target || options.forward);\n\n var agents = options.followRedirects ? followRedirects : nativeAgents;\n var http = agents.http;\n var https = agents.https;\n\n if(options.forward) {\n // If forward enable, so just pipe the request\n var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(\n common.setupOutgoing(options.ssl || {}, options, req, 'forward')\n );\n\n // error handler (e.g. ECONNRESET, ECONNREFUSED)\n // Handle errors on incoming request as well as it makes sense to\n var forwardError = createErrorHandler(forwardReq, options.forward);\n req.on('error', forwardError);\n forwardReq.on('error', forwardError);\n\n (options.buffer || req).pipe(forwardReq);\n if(!options.target) { return res.end(); }\n }\n\n // Request initalization\n var proxyReq = (options.target.protocol === 'https:' ? https : http).request(\n common.setupOutgoing(options.ssl || {}, options, req)\n );\n\n // Enable developers to modify the proxyReq before headers are sent\n proxyReq.on('socket', function(socket) {\n if(server && !proxyReq.getHeader('expect')) {\n server.emit('proxyReq', proxyReq, req, res, options);\n }\n });\n\n // allow outgoing socket to timeout so that we could\n // show an error page at the initial request\n if(options.proxyTimeout) {\n proxyReq.setTimeout(options.proxyTimeout, function() {\n proxyReq.abort();\n });\n }\n\n // Ensure we abort proxy if request is aborted\n req.on('aborted', function () {\n proxyReq.abort();\n });\n\n // handle errors in proxy and incoming request, just like for forward proxy\n var proxyError = createErrorHandler(proxyReq, options.target);\n req.on('error', proxyError);\n proxyReq.on('error', proxyError);\n\n function createErrorHandler(proxyReq, url) {\n return function proxyError(err) {\n if (req.socket.destroyed && err.code === 'ECONNRESET') {\n server.emit('econnreset', err, req, res, url);\n return proxyReq.abort();\n }\n\n if (clb) {\n clb(err, req, res, url);\n } else {\n server.emit('error', err, req, res, url);\n }\n }\n }\n\n (options.buffer || req).pipe(proxyReq);\n\n proxyReq.on('response', function(proxyRes) {\n if(server) { server.emit('proxyRes', proxyRes, req, res); }\n\n if(!res.headersSent && !options.selfHandleResponse) {\n for(var i=0; i < web_o.length; i++) {\n if(web_o[i](req, res, proxyRes, options)) { break; }\n }\n }\n\n if (!res.finished) {\n // Allow us to listen when the proxy has completed\n proxyRes.on('end', function () {\n if (server) server.emit('end', req, res, proxyRes);\n });\n // We pipe to the response unless its expected to be handled by the user\n if (!options.selfHandleResponse) proxyRes.pipe(res);\n } else {\n if (server) server.emit('end', req, res, proxyRes);\n }\n });\n }\n\n};\n","var http = require('http'),\n https = require('https'),\n common = require('../common');\n\n/*!\n * Array of passes.\n *\n * A `pass` is just a function that is executed on `req, socket, options`\n * so that you can easily add new checks while still keeping the base\n * flexible.\n */\n\n/*\n * Websockets Passes\n *\n */\n\n\nmodule.exports = {\n /**\n * WebSocket requests must have the `GET` method and\n * the `upgrade:websocket` header\n *\n * @param {ClientRequest} Req Request object\n * @param {Socket} Websocket\n *\n * @api private\n */\n\n checkMethodAndHeader : function checkMethodAndHeader(req, socket) {\n if (req.method !== 'GET' || !req.headers.upgrade) {\n socket.destroy();\n return true;\n }\n\n if (req.headers.upgrade.toLowerCase() !== 'websocket') {\n socket.destroy();\n return true;\n }\n },\n\n /**\n * Sets `x-forwarded-*` headers if specified in config.\n *\n * @param {ClientRequest} Req Request object\n * @param {Socket} Websocket\n * @param {Object} Options Config object passed to the proxy\n *\n * @api private\n */\n\n XHeaders : function XHeaders(req, socket, options) {\n if(!options.xfwd) return;\n\n var values = {\n for : req.connection.remoteAddress || req.socket.remoteAddress,\n port : common.getPort(req),\n proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws'\n };\n\n ['for', 'port', 'proto'].forEach(function(header) {\n req.headers['x-forwarded-' + header] =\n (req.headers['x-forwarded-' + header] || '') +\n (req.headers['x-forwarded-' + header] ? ',' : '') +\n values[header];\n });\n },\n\n /**\n * Does the actual proxying. Make the request and upgrade it\n * send the Switching Protocols request and pipe the sockets.\n *\n * @param {ClientRequest} Req Request object\n * @param {Socket} Websocket\n * @param {Object} Options Config object passed to the proxy\n *\n * @api private\n */\n stream : function stream(req, socket, options, head, server, clb) {\n\n var createHttpHeader = function(line, headers) {\n return Object.keys(headers).reduce(function (head, key) {\n var value = headers[key];\n\n if (!Array.isArray(value)) {\n head.push(key + ': ' + value);\n return head;\n }\n\n for (var i = 0; i < value.length; i++) {\n head.push(key + ': ' + value[i]);\n }\n return head;\n }, [line])\n .join('\\r\\n') + '\\r\\n\\r\\n';\n }\n\n common.setupSocket(socket);\n\n if (head && head.length) socket.unshift(head);\n\n\n var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request(\n common.setupOutgoing(options.ssl || {}, options, req)\n );\n\n // Enable developers to modify the proxyReq before headers are sent\n if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); }\n\n // Error Handler\n proxyReq.on('error', onOutgoingError);\n proxyReq.on('response', function (res) {\n // if upgrade event isn't going to happen, close the socket\n if (!res.upgrade) {\n socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers));\n res.pipe(socket);\n }\n });\n\n proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {\n proxySocket.on('error', onOutgoingError);\n\n // Allow us to listen when the websocket has completed\n proxySocket.on('end', function () {\n server.emit('close', proxyRes, proxySocket, proxyHead);\n });\n\n // The pipe below will end proxySocket if socket closes cleanly, but not\n // if it errors (eg, vanishes from the net and starts returning\n // EHOSTUNREACH). We need to do that explicitly.\n socket.on('error', function () {\n proxySocket.end();\n });\n\n common.setupSocket(proxySocket);\n\n if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);\n\n //\n // Remark: Handle writing the headers to the socket when switching protocols\n // Also handles when a header is an array\n //\n socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers));\n\n proxySocket.pipe(socket).pipe(proxySocket);\n\n server.emit('open', proxySocket);\n server.emit('proxySocket', proxySocket); //DEPRECATED.\n });\n\n return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT\n\n function onOutgoingError(err) {\n if (clb) {\n clb(err, req, socket);\n } else {\n server.emit('error', err, req, socket);\n }\n socket.end();\n }\n }\n};\n","var httpProxy = module.exports,\n extend = require('util')._extend,\n parse_url = require('url').parse,\n EE3 = require('eventemitter3'),\n http = require('http'),\n https = require('https'),\n web = require('./passes/web-incoming'),\n ws = require('./passes/ws-incoming');\n\nhttpProxy.Server = ProxyServer;\n\n/**\n * Returns a function that creates the loader for\n * either `ws` or `web`'s passes.\n *\n * Examples:\n *\n * httpProxy.createRightProxy('ws')\n * // => [Function]\n *\n * @param {String} Type Either 'ws' or 'web'\n * \n * @return {Function} Loader Function that when called returns an iterator for the right passes\n *\n * @api private\n */\n\nfunction createRightProxy(type) {\n\n return function(options) {\n return function(req, res /*, [head], [opts] */) {\n var passes = (type === 'ws') ? this.wsPasses : this.webPasses,\n args = [].slice.call(arguments),\n cntr = args.length - 1,\n head, cbl;\n\n /* optional args parse begin */\n if(typeof args[cntr] === 'function') {\n cbl = args[cntr];\n\n cntr--;\n }\n\n var requestOptions = options;\n if(\n !(args[cntr] instanceof Buffer) &&\n args[cntr] !== res\n ) {\n //Copy global options\n requestOptions = extend({}, options);\n //Overwrite with request options\n extend(requestOptions, args[cntr]);\n\n cntr--;\n }\n\n if(args[cntr] instanceof Buffer) {\n head = args[cntr];\n }\n\n /* optional args parse end */\n\n ['target', 'forward'].forEach(function(e) {\n if (typeof requestOptions[e] === 'string')\n requestOptions[e] = parse_url(requestOptions[e]);\n });\n\n if (!requestOptions.target && !requestOptions.forward) {\n return this.emit('error', new Error('Must provide a proper URL as target'));\n }\n\n for(var i=0; i < passes.length; i++) {\n /**\n * Call of passes functions\n * pass(req, res, options, head)\n *\n * In WebSockets case the `res` variable\n * refer to the connection socket\n * pass(req, socket, options, head)\n */\n if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop\n break;\n }\n }\n };\n };\n}\nhttpProxy.createRightProxy = createRightProxy;\n\nfunction ProxyServer(options) {\n EE3.call(this);\n\n options = options || {};\n options.prependPath = options.prependPath === false ? false : true;\n\n this.web = this.proxyRequest = createRightProxy('web')(options);\n this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options);\n this.options = options;\n\n this.webPasses = Object.keys(web).map(function(pass) {\n return web[pass];\n });\n\n this.wsPasses = Object.keys(ws).map(function(pass) {\n return ws[pass];\n });\n\n this.on('error', this.onError, this);\n\n}\n\nrequire('util').inherits(ProxyServer, EE3);\n\nProxyServer.prototype.onError = function (err) {\n //\n // Remark: Replicate node core behavior using EE3\n // so we force people to handle their own errors\n //\n if(this.listeners('error').length === 1) {\n throw err;\n }\n};\n\nProxyServer.prototype.listen = function(port, hostname) {\n var self = this,\n closure = function(req, res) { self.web(req, res); };\n\n this._server = this.options.ssl ?\n https.createServer(this.options.ssl, closure) :\n http.createServer(closure);\n\n if(this.options.ws) {\n this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); });\n }\n\n this._server.listen(port, hostname);\n\n return this;\n};\n\nProxyServer.prototype.close = function(callback) {\n var self = this;\n if (this._server) {\n this._server.close(done);\n }\n\n // Wrap callback to nullify server after all open connections are closed.\n function done() {\n self._server = null;\n if (callback) {\n callback.apply(null, arguments);\n }\n };\n};\n\nProxyServer.prototype.before = function(type, passName, callback) {\n if (type !== 'ws' && type !== 'web') {\n throw new Error('type must be `web` or `ws`');\n }\n var passes = (type === 'ws') ? this.wsPasses : this.webPasses,\n i = false;\n\n passes.forEach(function(v, idx) {\n if(v.name === passName) i = idx;\n })\n\n if(i === false) throw new Error('No such pass');\n\n passes.splice(i, 0, callback);\n};\nProxyServer.prototype.after = function(type, passName, callback) {\n if (type !== 'ws' && type !== 'web') {\n throw new Error('type must be `web` or `ws`');\n }\n var passes = (type === 'ws') ? this.wsPasses : this.webPasses,\n i = false;\n\n passes.forEach(function(v, idx) {\n if(v.name === passName) i = idx;\n })\n\n if(i === false) throw new Error('No such pass');\n\n passes.splice(i++, 0, callback);\n};\n"," // Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!)\nvar ProxyServer = require('./http-proxy/index.js').Server;\n\n\n/**\n * Creates the proxy server.\n *\n * Examples:\n *\n * httpProxy.createProxyServer({ .. }, 8000)\n * // => '{ web: [Function], ws: [Function] ... }'\n *\n * @param {Object} Options Config object passed to the proxy\n *\n * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests\n *\n * @api public\n */\n\n\nfunction createProxyServer(options) {\n /*\n * `options` is needed and it must have the following layout:\n *\n * {\n * target : \n * forward: \n * agent : \n * ssl : \n * ws : \n * xfwd : \n * secure : \n * toProxy: \n * prependPath: \n * ignorePath: \n * localAddress : \n * changeOrigin: \n * preserveHeaderKeyCase: \n * auth : Basic authentication i.e. 'user:password' to compute an Authorization header.\n * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null.\n * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.\n * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.\n * }\n *\n * NOTE: `options.ws` and `options.ssl` are optional.\n * `options.target and `options.forward` cannot be\n * both missing\n * }\n */\n\n return new ProxyServer(options);\n}\n\n\nProxyServer.createProxyServer = createProxyServer;\nProxyServer.createServer = createProxyServer;\nProxyServer.createProxy = createProxyServer;\n\n\n\n\n/**\n * Export the proxy \"Server\" as the main export.\n */\nmodule.exports = ProxyServer;\n\n","/*!\n * Caron dimonio, con occhi di bragia\n * loro accennando, tutte le raccoglie;\n * batte col remo qualunque s’adagia \n *\n * Charon the demon, with the eyes of glede,\n * Beckoning to them, collects them all together,\n * Beats with his oar whoever lags behind\n * \n * Dante - The Divine Comedy (Canto III)\n */\n\nmodule.exports = require('./lib/http-proxy');","import * as http from 'http'\nimport { createDebugger, isObject } from '../../utils'\nimport httpProxy from 'http-proxy'\nimport { HMR_HEADER } from '../ws'\nimport { Connect } from 'types/connect'\nimport { HttpProxy } from 'types/http-proxy'\nimport chalk from 'chalk'\nimport { ResolvedConfig } from '../..'\n\nconst debug = createDebugger('vite:proxy')\n\nexport interface ProxyOptions extends HttpProxy.ServerOptions {\n /**\n * rewrite path\n */\n rewrite?: (path: string) => string\n /**\n * configure the proxy server (e.g. listen to events)\n */\n configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void\n /**\n * webpack-dev-server style bypass function\n */\n bypass?: (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n options: ProxyOptions\n ) => void | null | undefined | false | string\n}\n\nexport function proxyMiddleware(\n httpServer: http.Server | null,\n config: ResolvedConfig\n): Connect.NextHandleFunction {\n const options = config.server.proxy!\n\n // lazy require only when proxy is used\n const proxies: Record = {}\n\n Object.keys(options).forEach((context) => {\n let opts = options[context]\n if (typeof opts === 'string') {\n opts = { target: opts, changeOrigin: true } as ProxyOptions\n }\n const proxy = httpProxy.createProxyServer(opts) as HttpProxy.Server\n\n proxy.on('error', (err) => {\n config.logger.error(`${chalk.red(`http proxy error:`)}\\n${err.stack}`, {\n timestamp: true,\n error: err\n })\n })\n\n if (opts.configure) {\n opts.configure(proxy, opts)\n }\n // clone before saving because http-proxy mutates the options\n proxies[context] = [proxy, { ...opts }]\n })\n\n if (httpServer) {\n httpServer.on('upgrade', (req, socket, head) => {\n const url = req.url!\n for (const context in proxies) {\n if (url.startsWith(context)) {\n const [proxy, opts] = proxies[context]\n if (\n (opts.ws || opts.target?.toString().startsWith('ws:')) &&\n req.headers['sec-websocket-protocol'] !== HMR_HEADER\n ) {\n if (opts.rewrite) {\n req.url = opts.rewrite(url)\n }\n proxy.ws(req, socket, head)\n }\n }\n }\n })\n }\n\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return function viteProxyMiddleware(req, res, next) {\n const url = req.url!\n for (const context in proxies) {\n if (\n (context.startsWith('^') && new RegExp(context).test(url)) ||\n url.startsWith(context)\n ) {\n const [proxy, opts] = proxies[context]\n const options: HttpProxy.ServerOptions = {}\n\n if (opts.bypass) {\n const bypassResult = opts.bypass(req, res, opts)\n if (typeof bypassResult === 'string') {\n req.url = bypassResult\n debug(`bypass: ${req.url} -> ${bypassResult}`)\n return next()\n } else if (isObject(bypassResult)) {\n Object.assign(options, bypassResult)\n debug(`bypass: ${req.url} use modified options: %O`, options)\n return next()\n } else if (bypassResult === false) {\n debug(`bypass: ${req.url} -> 404`)\n return res.end(404)\n }\n }\n\n debug(`${req.url} -> ${opts.target || opts.forward}`)\n if (opts.rewrite) {\n req.url = opts.rewrite(req.url!)\n }\n proxy.web(req, res, options)\n return\n }\n }\n next()\n }\n}\n","/*!\n * etag\n * Copyright(c) 2014-2016 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = etag\n\n/**\n * Module dependencies.\n * @private\n */\n\nvar crypto = require('crypto')\nvar Stats = require('fs').Stats\n\n/**\n * Module variables.\n * @private\n */\n\nvar toString = Object.prototype.toString\n\n/**\n * Generate an entity tag.\n *\n * @param {Buffer|string} entity\n * @return {string}\n * @private\n */\n\nfunction entitytag (entity) {\n if (entity.length === 0) {\n // fast-path empty\n return '\"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk\"'\n }\n\n // compute hash of entity\n var hash = crypto\n .createHash('sha1')\n .update(entity, 'utf8')\n .digest('base64')\n .substring(0, 27)\n\n // compute length of entity\n var len = typeof entity === 'string'\n ? Buffer.byteLength(entity, 'utf8')\n : entity.length\n\n return '\"' + len.toString(16) + '-' + hash + '\"'\n}\n\n/**\n * Create a simple ETag.\n *\n * @param {string|Buffer|Stats} entity\n * @param {object} [options]\n * @param {boolean} [options.weak]\n * @return {String}\n * @public\n */\n\nfunction etag (entity, options) {\n if (entity == null) {\n throw new TypeError('argument entity is required')\n }\n\n // support fs.Stats object\n var isStats = isstats(entity)\n var weak = options && typeof options.weak === 'boolean'\n ? options.weak\n : isStats\n\n // validate argument\n if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {\n throw new TypeError('argument entity must be string, Buffer, or fs.Stats')\n }\n\n // generate entity tag\n var tag = isStats\n ? stattag(entity)\n : entitytag(entity)\n\n return weak\n ? 'W/' + tag\n : tag\n}\n\n/**\n * Determine if object is a Stats object.\n *\n * @param {object} obj\n * @return {boolean}\n * @api private\n */\n\nfunction isstats (obj) {\n // genuine fs.Stats\n if (typeof Stats === 'function' && obj instanceof Stats) {\n return true\n }\n\n // quack quack\n return obj && typeof obj === 'object' &&\n 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' &&\n 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' &&\n 'ino' in obj && typeof obj.ino === 'number' &&\n 'size' in obj && typeof obj.size === 'number'\n}\n\n/**\n * Generate a tag for a stat.\n *\n * @param {object} stat\n * @return {string}\n * @private\n */\n\nfunction stattag (stat) {\n var mtime = stat.mtime.getTime().toString(16)\n var size = stat.size.toString(16)\n\n return '\"' + size + '-' + mtime + '\"'\n}\n","import { IncomingMessage, ServerResponse } from 'http'\nimport getEtag from 'etag'\nimport { SourceMap } from 'rollup'\n\nconst isDebug = process.env.DEBUG\n\nconst alias: Record = {\n js: 'application/javascript',\n css: 'text/css',\n html: 'text/html',\n json: 'application/json'\n}\n\nexport function send(\n req: IncomingMessage,\n res: ServerResponse,\n content: string | Buffer,\n type: string,\n etag = getEtag(content, { weak: true }),\n cacheControl = 'no-cache',\n map?: SourceMap | null\n): void {\n if (req.headers['if-none-match'] === etag) {\n res.statusCode = 304\n return res.end()\n }\n\n res.setHeader('Content-Type', alias[type] || type)\n res.setHeader('Cache-Control', cacheControl)\n res.setHeader('Etag', etag)\n\n // inject source map reference\n if (map && map.mappings) {\n if (isDebug) {\n content += `\\n/*${JSON.stringify(map, null, 2).replace(\n /\\*\\//g,\n '*\\\\/'\n )}*/\\n`\n }\n content += genSourceMapString(map)\n }\n\n res.statusCode = 200\n return res.end(content)\n}\n\nfunction genSourceMapString(map: SourceMap | string | undefined) {\n if (typeof map !== 'string') {\n map = JSON.stringify(map)\n }\n return `\\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(\n map\n ).toString('base64')}`\n}\n","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","'use strict';\nvar fs = require('fs');\nvar path = require('path');\nvar SafeBuffer = require('safe-buffer');\n\nObject.defineProperty(exports, 'commentRegex', {\n get: function getCommentRegex () {\n return /^\\s*\\/(?:\\/|\\*)[@#]\\s+sourceMappingURL=data:(?:application|text)\\/json;(?:charset[:=]\\S+?;)?base64,(?:.*)$/mg;\n }\n});\n\nObject.defineProperty(exports, 'mapFileCommentRegex', {\n get: function getMapFileCommentRegex () {\n // Matches sourceMappingURL in either // or /* comment styles.\n return /(?:\\/\\/[@#][ \\t]+sourceMappingURL=([^\\s'\"`]+?)[ \\t]*$)|(?:\\/\\*[@#][ \\t]+sourceMappingURL=([^\\*]+?)[ \\t]*(?:\\*\\/){1}[ \\t]*$)/mg;\n }\n});\n\n\nfunction decodeBase64(base64) {\n return (SafeBuffer.Buffer.from(base64, 'base64') || \"\").toString();\n}\n\nfunction stripComment(sm) {\n return sm.split(',').pop();\n}\n\nfunction readFromFileMap(sm, dir) {\n // NOTE: this will only work on the server since it attempts to read the map file\n\n var r = exports.mapFileCommentRegex.exec(sm);\n\n // for some odd reason //# .. captures in 1 and /* .. */ in 2\n var filename = r[1] || r[2];\n var filepath = path.resolve(dir, filename);\n\n try {\n return fs.readFileSync(filepath, 'utf8');\n } catch (e) {\n throw new Error('An error occurred while trying to read the map file at ' + filepath + '\\n' + e);\n }\n}\n\nfunction Converter (sm, opts) {\n opts = opts || {};\n\n if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir);\n if (opts.hasComment) sm = stripComment(sm);\n if (opts.isEncoded) sm = decodeBase64(sm);\n if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm);\n\n this.sourcemap = sm;\n}\n\nConverter.prototype.toJSON = function (space) {\n return JSON.stringify(this.sourcemap, null, space);\n};\n\nConverter.prototype.toBase64 = function () {\n var json = this.toJSON();\n return (SafeBuffer.Buffer.from(json, 'utf8') || \"\").toString('base64');\n};\n\nConverter.prototype.toComment = function (options) {\n var base64 = this.toBase64();\n var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;\n return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;\n};\n\n// returns copy instead of original\nConverter.prototype.toObject = function () {\n return JSON.parse(this.toJSON());\n};\n\nConverter.prototype.addProperty = function (key, value) {\n if (this.sourcemap.hasOwnProperty(key)) throw new Error('property \"' + key + '\" already exists on the sourcemap, use set property instead');\n return this.setProperty(key, value);\n};\n\nConverter.prototype.setProperty = function (key, value) {\n this.sourcemap[key] = value;\n return this;\n};\n\nConverter.prototype.getProperty = function (key) {\n return this.sourcemap[key];\n};\n\nexports.fromObject = function (obj) {\n return new Converter(obj);\n};\n\nexports.fromJSON = function (json) {\n return new Converter(json, { isJSON: true });\n};\n\nexports.fromBase64 = function (base64) {\n return new Converter(base64, { isEncoded: true });\n};\n\nexports.fromComment = function (comment) {\n comment = comment\n .replace(/^\\/\\*/g, '//')\n .replace(/\\*\\/$/g, '');\n\n return new Converter(comment, { isEncoded: true, hasComment: true });\n};\n\nexports.fromMapFileComment = function (comment, dir) {\n return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true });\n};\n\n// Finds last sourcemap comment in file or returns null if none was found\nexports.fromSource = function (content) {\n var m = content.match(exports.commentRegex);\n return m ? exports.fromComment(m.pop()) : null;\n};\n\n// Finds last sourcemap comment in file or returns null if none was found\nexports.fromMapFileSource = function (content, dir) {\n var m = content.match(exports.mapFileCommentRegex);\n return m ? exports.fromMapFileComment(m.pop(), dir) : null;\n};\n\nexports.removeComments = function (src) {\n return src.replace(exports.commentRegex, '');\n};\n\nexports.removeMapFileComments = function (src) {\n return src.replace(exports.mapFileCommentRegex, '');\n};\n\nexports.generateMapFileComment = function (file, options) {\n var data = 'sourceMappingURL=' + file;\n return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;\n};\n","import { walk } from 'estree-walker';\nimport is_reference from 'is-reference';\n\n// @ts-check\n\n/** @typedef { import('estree').Node} Node */\n/** @typedef { import('estree').VariableDeclaration} VariableDeclaration */\n/** @typedef { import('estree').ClassDeclaration} ClassDeclaration */\n/** @typedef { import('estree').VariableDeclarator} VariableDeclarator */\n/** @typedef { import('estree').Property} Property */\n/** @typedef { import('estree').RestElement} RestElement */\n/** @typedef { import('estree').Identifier} Identifier */\n\n/**\n *\n * @param {Node} expression\n */\nfunction analyze(expression) {\n\t/** @type {WeakMap} */\n\tconst map = new WeakMap();\n\n\t/** @type {Map} */\n\tconst globals = new Map();\n\n\tconst scope = new Scope(null, false);\n\n\t/** @type {[Scope, Identifier][]} */\n\tconst references = [];\n\tlet current_scope = scope;\n\n\twalk(expression, {\n\t\t/**\n\t\t *\n\t\t * @param {Node} node\n\t\t * @param {Node} parent\n\t\t */\n\t\tenter(node, parent) {\n\t\t\tswitch (node.type) {\n\t\t\t\tcase 'Identifier':\n\t\t\t\t\tif (is_reference(node, parent)) {\n\t\t\t\t\t\treferences.push([current_scope, node]);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'ImportDeclaration':\n\t\t\t\t\tnode.specifiers.forEach((specifier) => {\n\t\t\t\t\t\tcurrent_scope.declarations.set(specifier.local.name, specifier);\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'FunctionExpression':\n\t\t\t\tcase 'FunctionDeclaration':\n\t\t\t\tcase 'ArrowFunctionExpression':\n\t\t\t\t\tif (node.type === 'FunctionDeclaration') {\n\t\t\t\t\t\tif (node.id) {\n\t\t\t\t\t\t\tcurrent_scope.declarations.set(node.id.name, node);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tmap.set(node, current_scope = new Scope(current_scope, false));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmap.set(node, current_scope = new Scope(current_scope, false));\n\n\t\t\t\t\t\tif (node.type === 'FunctionExpression' && node.id) {\n\t\t\t\t\t\t\tcurrent_scope.declarations.set(node.id.name, node);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tnode.params.forEach(param => {\n\t\t\t\t\t\textract_names(param).forEach(name => {\n\t\t\t\t\t\t\tcurrent_scope.declarations.set(name, node);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'ForStatement':\n\t\t\t\tcase 'ForInStatement':\n\t\t\t\tcase 'ForOfStatement':\n\t\t\t\t\tmap.set(node, current_scope = new Scope(current_scope, true));\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'BlockStatement':\n\t\t\t\t\tmap.set(node, current_scope = new Scope(current_scope, true));\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'ClassDeclaration':\n\t\t\t\tcase 'VariableDeclaration':\n\t\t\t\t\tcurrent_scope.add_declaration(node);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'CatchClause':\n\t\t\t\t\tmap.set(node, current_scope = new Scope(current_scope, true));\n\n\t\t\t\t\tif (node.param) {\n\t\t\t\t\t\textract_names(node.param).forEach(name => {\n\t\t\t\t\t\t\tcurrent_scope.declarations.set(name, node.param);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t *\n\t\t * @param {Node} node\n\t\t */\n\t\tleave(node) {\n\t\t\tif (map.has(node)) {\n\t\t\t\tcurrent_scope = current_scope.parent;\n\t\t\t}\n\t\t}\n\t});\n\n\tfor (let i = references.length - 1; i >= 0; --i) {\n\t\tconst [scope, reference] = references[i];\n\n\t\tif (!scope.references.has(reference.name)) {\n\t\t\tadd_reference(scope, reference.name);\n\n\t\t\tif (!scope.find_owner(reference.name)) {\n\t\t\t\tglobals.set(reference.name, reference);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { map, scope, globals };\n}\n\n/**\n *\n * @param {Scope} scope\n * @param {string} name\n */\nfunction add_reference(scope, name) {\n\tscope.references.add(name);\n\tif (scope.parent) add_reference(scope.parent, name);\n}\n\nclass Scope {\n\tconstructor(parent, block) {\n\t\t/** @type {Scope | null} */\n\t\tthis.parent = parent;\n\n\t\t/** @type {boolean} */\n\t\tthis.block = block;\n\n\t\t/** @type {Map} */\n\t\tthis.declarations = new Map();\n\n\t\t/** @type {Set} */\n\t\tthis.initialised_declarations = new Set();\n\n\t\t/** @type {Set} */\n\t\tthis.references = new Set();\n\t}\n\n\t/**\n\t *\n\t * @param {VariableDeclaration | ClassDeclaration} node\n\t */\n\tadd_declaration(node) {\n\t\tif (node.type === 'VariableDeclaration') {\n\t\t\tif (node.kind === 'var' && this.block && this.parent) {\n\t\t\t\tthis.parent.add_declaration(node);\n\t\t\t} else {\n\t\t\t\t/**\n\t\t\t\t *\n\t\t\t\t * @param {VariableDeclarator} declarator\n\t\t\t\t */\n\t\t\t\tconst handle_declarator = (declarator) => {\n\t\t\t\t\textract_names(declarator.id).forEach(name => {\n\t\t\t\t\t\tthis.declarations.set(name, node);\n\t\t\t\t\t\tif (declarator.init) this.initialised_declarations.add(name);\n\t\t\t\t\t});\t\t\t\t};\n\n\t\t\t\tnode.declarations.forEach(handle_declarator);\n\t\t\t}\n\t\t} else if (node.id) {\n\t\t\tthis.declarations.set(node.id.name, node);\n\t\t}\n\t}\n\n\t/**\n\t *\n\t * @param {string} name\n\t * @returns {Scope | null}\n\t */\n\tfind_owner(name) {\n\t\tif (this.declarations.has(name)) return this;\n\t\treturn this.parent && this.parent.find_owner(name);\n\t}\n\n\t/**\n\t *\n\t * @param {string} name\n\t * @returns {boolean}\n\t */\n\thas(name) {\n\t\treturn (\n\t\t\tthis.declarations.has(name) || (!!this.parent && this.parent.has(name))\n\t\t);\n\t}\n}\n\n/**\n *\n * @param {Node} param\n * @returns {string[]}\n */\nfunction extract_names(param) {\n\treturn extract_identifiers(param).map(node => node.name);\n}\n\n/**\n *\n * @param {Node} param\n * @param {Identifier[]} nodes\n * @returns {Identifier[]}\n */\nfunction extract_identifiers(param, nodes = []) {\n\tswitch (param.type) {\n\t\tcase 'Identifier':\n\t\t\tnodes.push(param);\n\t\t\tbreak;\n\n\t\tcase 'MemberExpression':\n\t\t\tlet object = param;\n\t\t\twhile (object.type === 'MemberExpression') {\n\t\t\t\tobject = /** @type {any} */ (object.object);\n\t\t\t}\n\t\t\tnodes.push(/** @type {any} */ (object));\n\t\t\tbreak;\n\n\t\tcase 'ObjectPattern':\n\t\t\t/**\n\t\t\t *\n\t\t\t * @param {Property | RestElement} prop\n\t\t\t */\n\t\t\tconst handle_prop = (prop) => {\n\t\t\t\tif (prop.type === 'RestElement') {\n\t\t\t\t\textract_identifiers(prop.argument, nodes);\n\t\t\t\t} else {\n\t\t\t\t\textract_identifiers(prop.value, nodes);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tparam.properties.forEach(handle_prop);\n\t\t\tbreak;\n\n\t\tcase 'ArrayPattern':\n\t\t\t/**\n\t\t\t *\n\t\t\t * @param {Node} element\n\t\t\t */\n\t\t\tconst handle_element = (element) => {\n\t\t\t\tif (element) extract_identifiers(element, nodes);\n\t\t\t};\n\n\t\t\tparam.elements.forEach(handle_element);\n\t\t\tbreak;\n\n\t\tcase 'RestElement':\n\t\t\textract_identifiers(param.argument, nodes);\n\t\t\tbreak;\n\n\t\tcase 'AssignmentPattern':\n\t\t\textract_identifiers(param.left, nodes);\n\t\t\tbreak;\n\t}\n\n\treturn nodes;\n}\n\nexport { analyze, Scope, extract_names, extract_identifiers };\n","import MagicString from 'magic-string'\nimport { SourceMap } from 'rollup'\nimport { TransformResult } from '../server/transformRequest'\nimport { parser } from '../server/pluginContainer'\nimport {\n Identifier,\n Node as _Node,\n Property,\n Function as FunctionNode\n} from 'estree'\nimport { extract_names as extractNames } from 'periscopic'\nimport { walk as eswalk } from 'estree-walker'\nimport { combineSourcemaps } from '../utils'\nimport { RawSourceMap } from '@ampproject/remapping/dist/types/types'\n\ntype Node = _Node & {\n start: number\n end: number\n}\n\nexport const ssrModuleExportsKey = `__vite_ssr_exports__`\nexport const ssrImportKey = `__vite_ssr_import__`\nexport const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`\nexport const ssrExportAllKey = `__vite_ssr_exportAll__`\nexport const ssrImportMetaKey = `__vite_ssr_import_meta__`\n\nexport async function ssrTransform(\n code: string,\n inMap: SourceMap | null,\n url: string\n): Promise {\n const s = new MagicString(code)\n\n const ast = parser.parse(code, {\n sourceType: 'module',\n ecmaVersion: 2021,\n locations: true\n }) as any\n\n let uid = 0\n const deps = new Set()\n const idToImportMap = new Map()\n const declaredConst = new Set()\n\n function defineImport(node: Node, source: string) {\n deps.add(source)\n const importId = `__vite_ssr_import_${uid++}__`\n s.appendLeft(\n node.start,\n `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\\n`\n )\n return importId\n }\n\n function defineExport(position: number, name: string, local = name) {\n s.appendRight(\n position,\n `\\nObject.defineProperty(${ssrModuleExportsKey}, \"${name}\", ` +\n `{ enumerable: true, configurable: true, get(){ return ${local} }});`\n )\n }\n\n // 1. check all import statements and record id -> importName map\n for (const node of ast.body as Node[]) {\n // import foo from 'foo' --> foo -> __import_foo__.default\n // import { baz } from 'foo' --> baz -> __import_foo__.baz\n // import * as ok from 'foo' --> ok -> __import_foo__\n if (node.type === 'ImportDeclaration') {\n const importId = defineImport(node, node.source.value as string)\n for (const spec of node.specifiers) {\n if (spec.type === 'ImportSpecifier') {\n idToImportMap.set(\n spec.local.name,\n `${importId}.${spec.imported.name}`\n )\n } else if (spec.type === 'ImportDefaultSpecifier') {\n idToImportMap.set(spec.local.name, `${importId}.default`)\n } else {\n // namespace specifier\n idToImportMap.set(spec.local.name, importId)\n }\n }\n s.remove(node.start, node.end)\n }\n }\n\n // 2. check all export statements and define exports\n for (const node of ast.body as Node[]) {\n // named exports\n if (node.type === 'ExportNamedDeclaration') {\n if (node.declaration) {\n if (\n node.declaration.type === 'FunctionDeclaration' ||\n node.declaration.type === 'ClassDeclaration'\n ) {\n // export function foo() {}\n defineExport(node.end, node.declaration.id!.name)\n } else {\n // export const foo = 1, bar = 2\n for (const declaration of node.declaration.declarations) {\n const names = extractNames(declaration.id as any)\n for (const name of names) {\n defineExport(node.end, name)\n }\n }\n }\n s.remove(node.start, (node.declaration as Node).start)\n } else {\n s.remove(node.start, node.end)\n if (node.source) {\n // export { foo, bar } from './foo'\n const importId = defineImport(node, node.source.value as string)\n for (const spec of node.specifiers) {\n defineExport(\n node.end,\n spec.exported.name,\n `${importId}.${spec.local.name}`\n )\n }\n } else {\n // export { foo, bar }\n for (const spec of node.specifiers) {\n const local = spec.local.name\n const binding = idToImportMap.get(local)\n defineExport(node.end, spec.exported.name, binding || local)\n }\n }\n }\n }\n\n // default export\n if (node.type === 'ExportDefaultDeclaration') {\n if ('id' in node.declaration && node.declaration.id) {\n // named hoistable/class exports\n // export default function foo() {}\n // export default class A {}\n const { name } = node.declaration.id\n s.remove(node.start, node.start + 15 /* 'export default '.length */)\n s.append(\n `\\nObject.defineProperty(${ssrModuleExportsKey}, \"default\", ` +\n `{ enumerable: true, value: ${name} });`\n )\n } else {\n // anonymous default exports\n s.overwrite(\n node.start,\n node.start + 14 /* 'export default'.length */,\n `${ssrModuleExportsKey}.default =`\n )\n }\n }\n\n // export * from './foo'\n if (node.type === 'ExportAllDeclaration') {\n if (node.exported) {\n const importId = defineImport(node, node.source.value as string)\n s.remove(node.start, node.end)\n defineExport(node.end, node.exported.name, `${importId}`)\n } else {\n const importId = defineImport(node, node.source.value as string)\n s.remove(node.start, node.end)\n s.appendLeft(node.end, `${ssrExportAllKey}(${importId});`)\n }\n }\n }\n\n // 3. convert references to import bindings & import.meta references\n walk(ast, {\n onIdentifier(id, parent, parentStack) {\n const binding = idToImportMap.get(id.name)\n if (!binding) {\n return\n }\n if (isStaticProperty(parent) && parent.shorthand) {\n // let binding used in a property shorthand\n // { foo } -> { foo: __import_x__.foo }\n // skip for destructuring patterns\n if (\n !(parent as any).inPattern ||\n isInDestructuringAssignment(parent, parentStack)\n ) {\n s.appendLeft(id.end, `: ${binding}`)\n }\n } else if (\n parent.type === 'ClassDeclaration' &&\n id === parent.superClass\n ) {\n if (!declaredConst.has(id.name)) {\n declaredConst.add(id.name)\n // locate the top-most node containing the class declaration\n const topNode = parentStack[1]\n s.prependRight(topNode.start, `const ${id.name} = ${binding};\\n`)\n }\n } else {\n s.overwrite(id.start, id.end, binding)\n }\n },\n onImportMeta(node) {\n s.overwrite(node.start, node.end, ssrImportMetaKey)\n },\n onDynamicImport(node) {\n s.overwrite(node.start, node.start + 6, ssrDynamicImportKey)\n }\n })\n\n let map = s.generateMap({ hires: true })\n if (inMap && inMap.mappings && inMap.sources.length > 0) {\n map = combineSourcemaps(url, [\n {\n ...map,\n sources: inMap.sources,\n sourcesContent: inMap.sourcesContent\n } as RawSourceMap,\n inMap as RawSourceMap\n ]) as SourceMap\n } else {\n map.sources = [url]\n map.sourcesContent = [code]\n }\n\n return {\n code: s.toString(),\n map,\n deps: [...deps]\n }\n}\n\ninterface Visitors {\n onIdentifier: (\n node: Identifier & {\n start: number\n end: number\n },\n parent: Node,\n parentStack: Node[]\n ) => void\n onImportMeta: (node: Node) => void\n onDynamicImport: (node: Node) => void\n}\n\n/**\n * Same logic from \\@vue/compiler-core & \\@vue/compiler-sfc\n * Except this is using acorn AST\n */\nfunction walk(\n root: Node,\n { onIdentifier, onImportMeta, onDynamicImport }: Visitors\n) {\n const parentStack: Node[] = []\n const scope: Record = Object.create(null)\n const scopeMap = new WeakMap<_Node, Set>()\n\n const setScope = (node: FunctionNode, name: string) => {\n let scopeIds = scopeMap.get(node)\n if (scopeIds && scopeIds.has(name)) {\n return\n }\n if (name in scope) {\n scope[name]++\n } else {\n scope[name] = 1\n }\n if (!scopeIds) {\n scopeIds = new Set()\n scopeMap.set(node, scopeIds)\n }\n scopeIds.add(name)\n }\n\n ;(eswalk as any)(root, {\n enter(node: Node, parent: Node | null) {\n if (node.type === 'ImportDeclaration') {\n return this.skip()\n }\n\n parent && parentStack.push(parent)\n\n if (node.type === 'MetaProperty' && node.meta.name === 'import') {\n onImportMeta(node)\n } else if (node.type === 'ImportExpression') {\n onDynamicImport(node)\n }\n\n if (node.type === 'Identifier') {\n if (!scope[node.name] && isRefIdentifier(node, parent!, parentStack)) {\n onIdentifier(node, parent!, parentStack)\n }\n } else if (isFunction(node)) {\n // walk function expressions and add its arguments to known identifiers\n // so that we don't prefix them\n node.params.forEach((p) =>\n (eswalk as any)(p, {\n enter(child: Node, parent: Node) {\n if (\n child.type === 'Identifier' &&\n // do not record as scope variable if is a destructuring key\n !isStaticPropertyKey(child, parent) &&\n // do not record if this is a default value\n // assignment of a destructuring variable\n !(\n parent &&\n parent.type === 'AssignmentPattern' &&\n parent.right === child\n )\n ) {\n setScope(node, child.name)\n }\n }\n })\n )\n } else if (node.type === 'Property' && parent!.type === 'ObjectPattern') {\n // mark property in destructuring pattern\n ;(node as any).inPattern = true\n } else if (node.type === 'VariableDeclarator') {\n const parentFunction = findParentFunction(parentStack)\n if (parentFunction) {\n if (node.id.type === 'ObjectPattern') {\n node.id.properties.forEach((property) => {\n if (property.type === 'RestElement') {\n setScope(parentFunction, (property.argument as Identifier).name)\n } else {\n setScope(parentFunction, (property.value as Identifier).name)\n }\n })\n } else {\n setScope(parentFunction, (node.id as Identifier).name)\n }\n }\n }\n },\n\n leave(node: Node, parent: Node | null) {\n parent && parentStack.pop()\n const scopeIds = scopeMap.get(node)\n if (scopeIds) {\n scopeIds.forEach((id: string) => {\n scope[id]--\n if (scope[id] === 0) {\n delete scope[id]\n }\n })\n }\n }\n })\n}\n\nfunction isRefIdentifier(id: Identifier, parent: _Node, parentStack: _Node[]) {\n // declaration id\n if (\n parent.type === 'CatchClause' ||\n ((parent.type === 'VariableDeclarator' ||\n parent.type === 'ClassDeclaration') &&\n parent.id === id)\n ) {\n return false\n }\n\n if (isFunction(parent)) {\n // function declaration/expression id\n if ((parent as any).id === id) {\n return false\n }\n // params list\n if (parent.params.includes(id)) {\n return false\n }\n }\n\n // class method name\n if (parent.type === 'MethodDefinition') {\n return false\n }\n\n // property key\n // this also covers object destructuring pattern\n if (isStaticPropertyKey(id, parent) || (parent as any).inPattern) {\n return false\n }\n\n // non-assignment array destructuring pattern\n if (\n parent.type === 'ArrayPattern' &&\n !isInDestructuringAssignment(parent, parentStack)\n ) {\n return false\n }\n\n // member expression property\n if (\n parent.type === 'MemberExpression' &&\n parent.property === id &&\n !parent.computed\n ) {\n return false\n }\n\n if (parent.type === 'ExportSpecifier') {\n return false\n }\n\n // is a special keyword but parsed as identifier\n if (id.name === 'arguments') {\n return false\n }\n\n return true\n}\n\nconst isStaticProperty = (node: _Node): node is Property =>\n node && node.type === 'Property' && !node.computed\n\nconst isStaticPropertyKey = (node: _Node, parent: _Node) =>\n isStaticProperty(parent) && parent.key === node\n\nfunction isFunction(node: _Node): node is FunctionNode {\n return /Function(?:Expression|Declaration)$|Method$/.test(node.type)\n}\n\nfunction findParentFunction(parentStack: _Node[]): FunctionNode | undefined {\n for (let i = parentStack.length - 1; i >= 0; i--) {\n const node = parentStack[i]\n if (isFunction(node)) {\n return node\n }\n }\n}\n\nfunction isInDestructuringAssignment(\n parent: _Node,\n parentStack: _Node[]\n): boolean {\n if (\n parent &&\n (parent.type === 'Property' || parent.type === 'ArrayPattern')\n ) {\n let i = parentStack.length\n while (i--) {\n const p = parentStack[i]\n if (p.type === 'AssignmentExpression') {\n return true\n } else if (p.type !== 'Property' && !p.type.endsWith('Pattern')) {\n break\n }\n }\n }\n return false\n}\n","import path from 'path'\nimport { promises as fs } from 'fs'\nimport { Logger } from '../logger'\nimport { createDebugger } from '../utils'\n\nconst isDebug = !!process.env.DEBUG\nconst debug = createDebugger('vite:sourcemap', {\n onlyWhenFocused: true\n})\n\ninterface SourceMapLike {\n sources: string[]\n sourcesContent?: (string | null)[]\n sourceRoot?: string\n}\n\nexport async function injectSourcesContent(\n map: SourceMapLike,\n file: string,\n logger: Logger\n): Promise {\n let sourceRoot: string | undefined\n try {\n // The source root is undefined for virtual modules and permission errors.\n sourceRoot = await fs.realpath(\n path.resolve(path.dirname(file), map.sourceRoot || '')\n )\n } catch {}\n\n const missingSources: string[] = []\n map.sourcesContent = await Promise.all(\n map.sources.map((sourcePath) => {\n if (sourcePath) {\n sourcePath = decodeURI(sourcePath)\n if (sourceRoot) {\n sourcePath = path.resolve(sourceRoot, sourcePath)\n }\n return fs.readFile(sourcePath, 'utf-8').catch(() => {\n missingSources.push(sourcePath)\n return null\n })\n }\n return null\n })\n )\n\n // Use this command…\n // DEBUG=\"vite:sourcemap\" vite build\n // …to log the missing sources.\n if (missingSources.length) {\n logger.warnOnce(`Sourcemap for \"${file}\" points to missing source files`)\n isDebug && debug(`Missing sources:\\n ` + missingSources.join(`\\n `))\n }\n}\n","import * as qs from 'querystring';\n\n/**\n * @typedef ParsedURL\n * @type {import('.').ParsedURL}\n */\n\n/**\n * @typedef Request\n * @property {string} url\n * @property {ParsedURL} _parsedUrl\n */\n\n/**\n * @param {Request} req\n * @returns {ParsedURL|void}\n */\nexport function parse(req) {\n\tlet raw = req.url;\n\tif (raw == null) return;\n\n\tlet prev = req._parsedUrl;\n\tif (prev && prev.raw === raw) return prev;\n\n\tlet pathname=raw, search='', query;\n\n\tif (raw.length > 1) {\n\t\tlet idx = raw.indexOf('?', 1);\n\n\t\tif (idx !== -1) {\n\t\t\tsearch = raw.substring(idx);\n\t\t\tpathname = raw.substring(0, idx);\n\t\t\tif (search.length > 1) {\n\t\t\t\tquery = qs.parse(search.substring(1));\n\t\t\t}\n\t\t}\n\t}\n\n\treturn req._parsedUrl = { pathname, search, query, raw };\n}\n","import { join, resolve } from 'path';\nimport { readdirSync, statSync } from 'fs';\n\nexport default function list(dir, callback, pre='') {\n\tdir = resolve('.', dir);\n\tlet arr = readdirSync(dir);\n\tlet i=0, abs, stats;\n\tfor (; i < arr.length; i++) {\n\t\tabs = join(dir, arr[i]);\n\t\tstats = statSync(abs);\n\t\tstats.isDirectory()\n\t\t\t? list(abs, callback, join(pre, arr[i]))\n\t\t\t: callback(join(pre, arr[i]), abs, stats);\n\t}\n}\n","import * as fs from 'fs';\nimport { join, normalize, resolve } from 'path';\nimport { parse } from '@polka/url';\nimport list from 'totalist/sync';\nimport mime from 'mime/lite';\n\nconst noop = () => {};\n\nfunction isMatch(uri, arr) {\n\tfor (let i=0; i < arr.length; i++) {\n\t\tif (arr[i].test(uri)) return true;\n\t}\n}\n\nfunction toAssume(uri, extns) {\n\tlet i=0, x, len=uri.length - 1;\n\tif (uri.charCodeAt(len) === 47) {\n\t\turi = uri.substring(0, len);\n\t}\n\n\tlet arr=[], tmp=`${uri}/index`;\n\tfor (; i < extns.length; i++) {\n\t\tx = extns[i] ? `.${extns[i]}` : '';\n\t\tif (uri) arr.push(uri + x);\n\t\tarr.push(tmp + x);\n\t}\n\n\treturn arr;\n}\n\nfunction viaCache(cache, uri, extns) {\n\tlet i=0, data, arr=toAssume(uri, extns);\n\tfor (; i < arr.length; i++) {\n\t\tif (data = cache[arr[i]]) return data;\n\t}\n}\n\nfunction viaLocal(dir, isEtag, uri, extns) {\n\tlet i=0, arr=toAssume(uri, extns);\n\tlet abs, stats, name, headers;\n\tfor (; i < arr.length; i++) {\n\t\tabs = normalize(join(dir, name=arr[i]));\n\t\tif (abs.startsWith(dir) && fs.existsSync(abs)) {\n\t\t\tstats = fs.statSync(abs);\n\t\t\tif (stats.isDirectory()) continue;\n\t\t\theaders = toHeaders(name, stats, isEtag);\n\t\t\theaders['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';\n\t\t\treturn { abs, stats, headers };\n\t\t}\n\t}\n}\n\nfunction is404(req, res) {\n\treturn (res.statusCode=404,res.end());\n}\n\nfunction send(req, res, file, stats, headers) {\n\tlet code=200, tmp, opts={};\n\theaders = { ...headers };\n\n\tfor (let key in headers) {\n\t\ttmp = res.getHeader(key);\n\t\tif (tmp) headers[key] = tmp;\n\t}\n\n\tif (tmp = res.getHeader('content-type')) {\n\t\theaders['Content-Type'] = tmp;\n\t}\n\n\tif (req.headers.range) {\n\t\tcode = 206;\n\t\tlet [x, y] = req.headers.range.replace('bytes=', '').split('-');\n\t\tlet end = opts.end = parseInt(y, 10) || stats.size - 1;\n\t\tlet start = opts.start = parseInt(x, 10) || 0;\n\n\t\tif (start >= stats.size || end >= stats.size) {\n\t\t\tres.setHeader('Content-Range', `bytes */${stats.size}`);\n\t\t\tres.statusCode = 416;\n\t\t\treturn res.end();\n\t\t}\n\n\t\theaders['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;\n\t\theaders['Content-Length'] = (end - start + 1);\n\t\theaders['Accept-Ranges'] = 'bytes';\n\t}\n\n\tres.writeHead(code, headers);\n\tfs.createReadStream(file, opts).pipe(res);\n}\n\nfunction isEncoding(name, type, headers) {\n\theaders['Content-Encoding'] = type;\n\theaders['Content-Type'] = mime.getType(name.replace(/\\.([^.]*)$/, '')) || '';\n}\n\nfunction toHeaders(name, stats, isEtag) {\n\tlet headers = {\n\t\t'Content-Length': stats.size,\n\t\t'Content-Type': mime.getType(name) || '',\n\t\t'Last-Modified': stats.mtime.toUTCString(),\n\t};\n\tif (isEtag) headers['ETag'] = `W/\"${stats.size}-${stats.mtime.getTime()}\"`;\n\tif (/\\.br$/.test(name)) isEncoding(name, 'br', headers);\n\tif (/\\.gz$/.test(name)) isEncoding(name, 'gzip', headers);\n\treturn headers;\n}\n\nexport default function (dir, opts={}) {\n\tdir = resolve(dir || '.');\n\n\tlet isNotFound = opts.onNoMatch || is404;\n\tlet setHeaders = opts.setHeaders || noop;\n\n\tlet extensions = opts.extensions || ['html', 'htm'];\n\tlet gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');\n\tlet brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');\n\n\tconst FILES = {};\n\n\tlet fallback = '/';\n\tlet isEtag = !!opts.etag;\n\tlet isSPA = !!opts.single;\n\tif (typeof opts.single === 'string') {\n\t\tlet idx = opts.single.lastIndexOf('.');\n\t\tfallback += !!~idx ? opts.single.substring(0, idx) : opts.single;\n\t}\n\n\tlet ignores = [];\n\tif (opts.ignores !== false) {\n\t\tignores.push(/[/]([A-Za-z\\s\\d~$._-]+\\.\\w+){1,}$/); // any extn\n\t\tif (opts.dotfiles) ignores.push(/\\/\\.\\w/);\n\t\telse ignores.push(/\\/\\.well-known/);\n\t\t[].concat(opts.ignores || []).forEach(x => {\n\t\t\tignores.push(new RegExp(x, 'i'));\n\t\t});\n\t}\n\n\tlet cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;\n\tif (cc && opts.immutable) cc += ',immutable';\n\telse if (cc && opts.maxAge === 0) cc += ',must-revalidate';\n\n\tif (!opts.dev) {\n\t\tlist(dir, (name, abs, stats) => {\n\t\t\tif (/\\.well-known[\\\\+\\/]/.test(name)) {} // keep\n\t\t\telse if (!opts.dotfiles && /(^\\.|[\\\\+|\\/+]\\.)/.test(name)) return;\n\n\t\t\tlet headers = toHeaders(name, stats, isEtag);\n\t\t\tif (cc) headers['Cache-Control'] = cc;\n\n\t\t\tFILES['/' + name.normalize().replace(/\\\\+/g, '/')] = { abs, stats, headers };\n\t\t});\n\t}\n\n\tlet lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);\n\n\treturn function (req, res, next) {\n\t\tlet extns = [''];\n\t\tlet pathname = parse(req).pathname;\n\t\tlet val = req.headers['accept-encoding'] || '';\n\t\tif (gzips && val.includes('gzip')) extns.unshift(...gzips);\n\t\tif (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);\n\t\textns.push(...extensions); // [...br, ...gz, orig, ...exts]\n\n\t\tif (pathname.indexOf('%') !== -1) {\n\t\t\ttry { pathname = decodeURIComponent(pathname) }\n\t\t\tcatch (err) { /* malform uri */ }\n\t\t}\n\n\t\tlet data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);\n\t\tif (!data) return next ? next() : isNotFound(req, res);\n\n\t\tif (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {\n\t\t\tres.writeHead(304);\n\t\t\treturn res.end();\n\t\t}\n\n\t\tif (gzips || brots) {\n\t\t\tres.setHeader('Vary', 'Accept-Encoding');\n\t\t}\n\n\t\tsetHeaders(res, pathname, data.stats);\n\t\tsend(req, res, data.abs, data.stats, data.headers);\n\t};\n}\n","import path from 'path'\nimport sirv, { Options } from 'sirv'\nimport { Connect } from 'types/connect'\nimport { normalizePath, ResolvedConfig, ViteDevServer } from '../..'\nimport { FS_PREFIX } from '../../constants'\nimport {\n cleanUrl,\n ensureLeadingSlash,\n fsPathFromId,\n isImportRequest,\n isInternalRequest,\n isWindows,\n slash\n} from '../../utils'\nimport { AccessRestrictedError } from './error'\n\nconst sirvOptions: Options = {\n dev: true,\n etag: true,\n extensions: [],\n setHeaders(res, pathname) {\n // Matches js, jsx, ts, tsx.\n // The reason this is done, is that the .ts file extension is reserved\n // for the MIME type video/mp2t. In almost all cases, we can expect\n // these files to be TypeScript files, and for Vite to serve them with\n // this Content-Type.\n if (/\\.[tj]sx?$/.test(pathname)) {\n res.setHeader('Content-Type', 'application/javascript')\n }\n }\n}\n\nexport function servePublicMiddleware(dir: string): Connect.NextHandleFunction {\n const serve = sirv(dir, sirvOptions)\n\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return function viteServePublicMiddleware(req, res, next) {\n // skip import request and internal requests `/@fs/ /@vite-client` etc...\n if (isImportRequest(req.url!) || isInternalRequest(req.url!)) {\n return next()\n }\n serve(req, res, next)\n }\n}\n\nexport function serveStaticMiddleware(\n dir: string,\n config: ResolvedConfig\n): Connect.NextHandleFunction {\n const serve = sirv(dir, sirvOptions)\n\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return function viteServeStaticMiddleware(req, res, next) {\n // only serve the file if it's not an html request\n // so that html requests can fallthrough to our html middleware for\n // special processing\n // also skip internal requests `/@fs/ /@vite-client` etc...\n if (\n path.extname(cleanUrl(req.url!)) === '.html' ||\n isInternalRequest(req.url!)\n ) {\n return next()\n }\n\n const url = decodeURI(req.url!)\n\n // apply aliases to static requests as well\n let redirected: string | undefined\n for (const { find, replacement } of config.resolve.alias) {\n const matches =\n typeof find === 'string' ? url.startsWith(find) : find.test(url)\n if (matches) {\n redirected = url.replace(find, replacement)\n break\n }\n }\n if (redirected) {\n // dir is pre-normalized to posix style\n if (redirected.startsWith(dir)) {\n redirected = redirected.slice(dir.length)\n }\n req.url = redirected\n }\n\n serve(req, res, next)\n }\n}\n\nexport function serveRawFsMiddleware(\n server: ViteDevServer\n): Connect.NextHandleFunction {\n const serveFromRoot = sirv('/', sirvOptions)\n\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return function viteServeRawFsMiddleware(req, res, next) {\n let url = req.url!\n // In some cases (e.g. linked monorepos) files outside of root will\n // reference assets that are also out of served root. In such cases\n // the paths are rewritten to `/@fs/` prefixed paths and must be served by\n // searching based from fs root.\n if (url.startsWith(FS_PREFIX)) {\n // restrict files outside of `fs.allow`\n ensureServingAccess(slash(path.resolve(fsPathFromId(url))), server)\n url = url.slice(FS_PREFIX.length)\n if (isWindows) url = url.replace(/^[A-Z]:/i, '')\n\n req.url = url\n serveFromRoot(req, res, next)\n } else {\n next()\n }\n }\n}\n\nexport function isFileServingAllowed(\n url: string,\n server: ViteDevServer\n): boolean {\n // explicitly disabled\n if (server.config.server.fs.strict === false) return true\n\n const file = ensureLeadingSlash(normalizePath(cleanUrl(url)))\n\n if (server.moduleGraph.safeModulesPath.has(file)) return true\n\n if (server.config.server.fs.allow.some((i) => file.startsWith(i + '/')))\n return true\n\n if (!server.config.server.fs.strict) {\n server.config.logger.warnOnce(`Unrestricted file system access to \"${url}\"`)\n server.config.logger.warnOnce(\n `For security concerns, accessing files outside of serving allow list will ` +\n `be restricted by default in the future version of Vite. ` +\n `Refer to https://vitejs.dev/config/#server-fs-allow for more details.`\n )\n return true\n }\n\n return false\n}\n\nexport function ensureServingAccess(url: string, server: ViteDevServer): void {\n if (!isFileServingAllowed(url, server)) {\n const allow = server.config.server.fs.allow\n throw new AccessRestrictedError(\n `The request url \"${url}\" is outside of Vite serving allow list:\n\n${allow.map((i) => `- ${i}`).join('\\n')}\n\nRefer to docs https://vitejs.dev/config/#server-fs-allow for configurations and more details.`\n )\n }\n}\n","import { promises as fs } from 'fs'\nimport path from 'path'\nimport getEtag from 'etag'\nimport * as convertSourceMap from 'convert-source-map'\nimport { SourceDescription, SourceMap } from 'rollup'\nimport { ViteDevServer } from '..'\nimport chalk from 'chalk'\nimport {\n createDebugger,\n cleanUrl,\n prettifyUrl,\n removeTimestampQuery,\n timeFrom,\n ensureWatchedFile,\n isObject\n} from '../utils'\nimport { checkPublicFile } from '../plugins/asset'\nimport { ssrTransform } from '../ssr/ssrTransform'\nimport { injectSourcesContent } from './sourcemap'\nimport { isFileServingAllowed } from './middlewares/static'\n\nconst debugLoad = createDebugger('vite:load')\nconst debugTransform = createDebugger('vite:transform')\nconst debugCache = createDebugger('vite:cache')\nconst isDebug = !!process.env.DEBUG\n\nexport interface TransformResult {\n code: string\n map: SourceMap | null\n etag?: string\n deps?: string[]\n}\n\nexport interface TransformOptions {\n ssr?: boolean\n html?: boolean\n}\n\nexport async function transformRequest(\n url: string,\n server: ViteDevServer,\n options: TransformOptions = {}\n): Promise {\n const { config, pluginContainer, moduleGraph, watcher } = server\n\n url = removeTimestampQuery(url)\n const { root, logger } = config\n const prettyUrl = isDebug ? prettifyUrl(url, root) : ''\n const ssr = !!options.ssr\n\n // check if we have a fresh cache\n const module = await moduleGraph.getModuleByUrl(url)\n const cached =\n module && (ssr ? module.ssrTransformResult : module.transformResult)\n if (cached) {\n isDebug && debugCache(`[memory] ${prettyUrl}`)\n return cached\n }\n\n // resolve\n const id = (await pluginContainer.resolveId(url))?.id || url\n const file = cleanUrl(id)\n\n let code: string | null = null\n let map: SourceDescription['map'] = null\n\n // load\n const loadStart = isDebug ? Date.now() : 0\n const loadResult = await pluginContainer.load(id, ssr)\n if (loadResult == null) {\n // if this is an html request and there is no load result, skip ahead to\n // SPA fallback.\n if (options.html && !id.endsWith('.html')) {\n return null\n }\n // try fallback loading it from fs as string\n // if the file is a binary, there should be a plugin that already loaded it\n // as string\n // only try the fallback if access is allowed, skip for out of root url\n // like /service-worker.js or /api/users\n if (options.ssr || isFileServingAllowed(file, server)) {\n try {\n code = await fs.readFile(file, 'utf-8')\n isDebug && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`)\n } catch (e) {\n if (e.code !== 'ENOENT') {\n throw e\n }\n }\n }\n if (code) {\n try {\n map = (\n convertSourceMap.fromSource(code) ||\n convertSourceMap.fromMapFileSource(code, path.dirname(file))\n )?.toObject()\n } catch (e) {\n logger.warn(`Failed to load source map for ${url}.`, {\n timestamp: true\n })\n }\n }\n } else {\n isDebug && debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`)\n if (isObject(loadResult)) {\n code = loadResult.code\n map = loadResult.map\n } else {\n code = loadResult\n }\n }\n if (code == null) {\n if (checkPublicFile(url, config)) {\n throw new Error(\n `Failed to load url ${url} (resolved id: ${id}). ` +\n `This file is in /public and will be copied as-is during build without ` +\n `going through the plugin transforms, and therefore should not be ` +\n `imported from source code. It can only be referenced via HTML tags.`\n )\n } else {\n return null\n }\n }\n\n // ensure module in graph after successful load\n const mod = await moduleGraph.ensureEntryFromUrl(url)\n ensureWatchedFile(watcher, mod.file, root)\n\n // transform\n const transformStart = isDebug ? Date.now() : 0\n const transformResult = await pluginContainer.transform(code, id, map, ssr)\n if (\n transformResult == null ||\n (isObject(transformResult) && transformResult.code == null)\n ) {\n // no transform applied, keep code as-is\n isDebug &&\n debugTransform(\n timeFrom(transformStart) + chalk.dim(` [skipped] ${prettyUrl}`)\n )\n } else {\n isDebug && debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`)\n code = transformResult.code!\n map = transformResult.map\n }\n\n if (map && mod.file) {\n map = (typeof map === 'string' ? JSON.parse(map) : map) as SourceMap\n if (map.mappings && !map.sourcesContent) {\n await injectSourcesContent(map, mod.file, logger)\n }\n }\n\n if (ssr) {\n return (mod.ssrTransformResult = await ssrTransform(\n code,\n map as SourceMap,\n url\n ))\n } else {\n return (mod.transformResult = {\n code,\n map,\n etag: getEtag(code, { weak: true })\n } as TransformResult)\n }\n}\n","import path from 'path'\nimport { ViteDevServer } from '..'\nimport { Connect } from 'types/connect'\nimport {\n cleanUrl,\n createDebugger,\n injectQuery,\n isImportRequest,\n isJSRequest,\n normalizePath,\n prettifyUrl,\n removeImportQuery,\n removeTimestampQuery,\n unwrapId\n} from '../../utils'\nimport { send } from '../send'\nimport { transformRequest } from '../transformRequest'\nimport { isHTMLProxy } from '../../plugins/html'\nimport chalk from 'chalk'\nimport {\n CLIENT_PUBLIC_PATH,\n DEP_VERSION_RE,\n NULL_BYTE_PLACEHOLDER\n} from '../../constants'\nimport {\n isCSSRequest,\n isDirectCSSRequest,\n isDirectRequest\n} from '../../plugins/css'\n\n/**\n * Time (ms) Vite has to full-reload the page before returning\n * an empty response.\n */\nconst NEW_DEPENDENCY_BUILD_TIMEOUT = 1000\n\nconst debugCache = createDebugger('vite:cache')\nconst isDebug = !!process.env.DEBUG\n\nconst knownIgnoreList = new Set(['/', '/favicon.ico'])\n\nexport function transformMiddleware(\n server: ViteDevServer\n): Connect.NextHandleFunction {\n const {\n config: { root, logger, cacheDir },\n moduleGraph\n } = server\n\n // determine the url prefix of files inside cache directory\n let cacheDirPrefix: string | undefined\n if (cacheDir) {\n const cacheDirRelative = normalizePath(path.relative(root, cacheDir))\n if (cacheDirRelative.startsWith('../')) {\n // if the cache directory is outside root, the url prefix would be something\n // like '/@fs/absolute/path/to/node_modules/.vite'\n cacheDirPrefix = `/@fs/${normalizePath(cacheDir).replace(/^\\//, '')}`\n } else {\n // if the cache directory is inside root, the url prefix would be something\n // like '/node_modules/.vite'\n cacheDirPrefix = `/${cacheDirRelative}`\n }\n }\n\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return async function viteTransformMiddleware(req, res, next) {\n if (req.method !== 'GET' || knownIgnoreList.has(req.url!)) {\n return next()\n }\n\n if (\n server._pendingReload &&\n // always allow vite client requests so that it can trigger page reload\n !req.url?.startsWith(CLIENT_PUBLIC_PATH) &&\n !req.url?.includes('vite/dist/client')\n ) {\n // missing dep pending reload, hold request until reload happens\n server._pendingReload.then(() =>\n // If the refresh has not happened after timeout, Vite considers\n // something unexpected has happened. In this case, Vite\n // returns an empty response that will error.\n setTimeout(() => {\n // Don't do anything if response has already been sent\n if (res.writableEnded) return\n // status code request timeout\n res.statusCode = 408\n res.end(\n `

[vite] Something unexpected happened while optimizing \"${req.url}\"

` +\n `

The current page should have reloaded by now

`\n )\n }, NEW_DEPENDENCY_BUILD_TIMEOUT)\n )\n return\n }\n\n let url = decodeURI(removeTimestampQuery(req.url!)).replace(\n NULL_BYTE_PLACEHOLDER,\n '\\0'\n )\n\n const withoutQuery = cleanUrl(url)\n\n try {\n const isSourceMap = withoutQuery.endsWith('.map')\n // since we generate source map references, handle those requests here\n if (isSourceMap) {\n const originalUrl = url.replace(/\\.map($|\\?)/, '$1')\n const map = (await moduleGraph.getModuleByUrl(originalUrl))\n ?.transformResult?.map\n if (map) {\n return send(req, res, JSON.stringify(map), 'json')\n } else {\n return next()\n }\n }\n\n const publicPath =\n normalizePath(server.config.publicDir).slice(\n server.config.root.length\n ) + '/'\n // warn explicit public paths\n if (url.startsWith(publicPath)) {\n logger.warn(\n chalk.yellow(\n `files in the public directory are served at the root path.\\n` +\n `Instead of ${chalk.cyan(url)}, use ${chalk.cyan(\n url.replace(publicPath, '/')\n )}.`\n )\n )\n }\n\n if (\n isJSRequest(url) ||\n isImportRequest(url) ||\n isCSSRequest(url) ||\n isHTMLProxy(url)\n ) {\n // strip ?import\n url = removeImportQuery(url)\n // Strip valid id prefix. This is prepended to resolved Ids that are\n // not valid browser import specifiers by the importAnalysis plugin.\n url = unwrapId(url)\n\n // for CSS, we need to differentiate between normal CSS requests and\n // imports\n if (\n isCSSRequest(url) &&\n !isDirectRequest(url) &&\n req.headers.accept?.includes('text/css')\n ) {\n url = injectQuery(url, 'direct')\n }\n\n // check if we can return 304 early\n const ifNoneMatch = req.headers['if-none-match']\n if (\n ifNoneMatch &&\n (await moduleGraph.getModuleByUrl(url))?.transformResult?.etag ===\n ifNoneMatch\n ) {\n isDebug && debugCache(`[304] ${prettifyUrl(url, root)}`)\n res.statusCode = 304\n return res.end()\n }\n\n // resolve, load and transform using the plugin container\n const result = await transformRequest(url, server, {\n html: req.headers.accept?.includes('text/html')\n })\n if (result) {\n const type = isDirectCSSRequest(url) ? 'css' : 'js'\n const isDep =\n DEP_VERSION_RE.test(url) ||\n (cacheDirPrefix && url.startsWith(cacheDirPrefix))\n return send(\n req,\n res,\n result.code,\n type,\n result.etag,\n // allow browser to cache npm deps!\n isDep ? 'max-age=31536000,immutable' : 'no-cache',\n result.map\n )\n }\n }\n } catch (e) {\n return next(e)\n }\n\n next()\n }\n}\n","import fs from 'fs'\nimport path from 'path'\nimport MagicString from 'magic-string'\nimport { AttributeNode, NodeTypes } from '@vue/compiler-dom'\nimport { Connect } from 'types/connect'\nimport {\n applyHtmlTransforms,\n getScriptInfo,\n IndexHtmlTransformHook,\n resolveHtmlTransforms,\n traverseHtml\n} from '../../plugins/html'\nimport { ResolvedConfig, ViteDevServer } from '../..'\nimport { send } from '../send'\nimport { CLIENT_PUBLIC_PATH, FS_PREFIX } from '../../constants'\nimport { cleanUrl, fsPathFromId } from '../../utils'\nimport { assetAttrsConfig } from '../../plugins/html'\n\nexport function createDevHtmlTransformFn(\n server: ViteDevServer\n): (url: string, html: string, originalUrl: string) => Promise {\n const [preHooks, postHooks] = resolveHtmlTransforms(server.config.plugins)\n\n return (url: string, html: string, originalUrl: string): Promise => {\n return applyHtmlTransforms(html, [...preHooks, devHtmlHook, ...postHooks], {\n path: url,\n filename: getHtmlFilename(url, server),\n server,\n originalUrl\n })\n }\n}\n\nfunction getHtmlFilename(url: string, server: ViteDevServer) {\n if (url.startsWith(FS_PREFIX)) {\n return fsPathFromId(url)\n } else {\n return path.join(server.config.root, url.slice(1))\n }\n}\n\nconst startsWithSingleSlashRE = /^\\/(?!\\/)/\nconst processNodeUrl = (\n node: AttributeNode,\n s: MagicString,\n config: ResolvedConfig,\n htmlPath: string,\n originalUrl?: string\n) => {\n const url = node.value?.content || ''\n if (startsWithSingleSlashRE.test(url)) {\n // prefix with base\n s.overwrite(\n node.value!.loc.start.offset,\n node.value!.loc.end.offset,\n `\"${config.base + url.slice(1)}\"`\n )\n } else if (\n url.startsWith('.') &&\n originalUrl &&\n originalUrl !== '/' &&\n htmlPath === '/index.html'\n ) {\n // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets\n // path will add `/a/` prefix, it will caused 404.\n // rewrite before `./index.js` -> `localhost:3000/a/index.js`.\n // rewrite after `../index.js` -> `localhost:3000/index.js`.\n s.overwrite(\n node.value!.loc.start.offset,\n node.value!.loc.end.offset,\n `\"${path.posix.join(\n path.posix.relative(originalUrl, '/'),\n url.slice(1)\n )}\"`\n )\n }\n}\nconst devHtmlHook: IndexHtmlTransformHook = async (\n html,\n { path: htmlPath, server, originalUrl }\n) => {\n // TODO: solve this design issue\n // Optional chain expressions can return undefined by design\n // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain\n const config = server?.config!\n const base = config.base || '/'\n\n const s = new MagicString(html)\n let scriptModuleIndex = -1\n\n await traverseHtml(html, htmlPath, (node) => {\n if (node.type !== NodeTypes.ELEMENT) {\n return\n }\n\n // script tags\n if (node.tag === 'script') {\n const { src, isModule } = getScriptInfo(node)\n if (isModule) {\n scriptModuleIndex++\n }\n\n if (src) {\n processNodeUrl(src, s, config, htmlPath, originalUrl)\n } else if (isModule) {\n // inline js module. convert to src=\"proxy\"\n s.overwrite(\n node.loc.start.offset,\n node.loc.end.offset,\n ``\n )\n }\n }\n\n // elements with [href/src] attrs\n const assetAttrs = assetAttrsConfig[node.tag]\n if (assetAttrs) {\n for (const p of node.props) {\n if (\n p.type === NodeTypes.ATTRIBUTE &&\n p.value &&\n assetAttrs.includes(p.name)\n ) {\n processNodeUrl(p, s, config, htmlPath, originalUrl)\n }\n }\n }\n })\n\n html = s.toString()\n\n return {\n html,\n tags: [\n {\n tag: 'script',\n attrs: {\n type: 'module',\n src: path.posix.join(base, CLIENT_PUBLIC_PATH)\n },\n injectTo: 'head-prepend'\n }\n ]\n }\n}\n\nexport function indexHtmlMiddleware(\n server: ViteDevServer\n): Connect.NextHandleFunction {\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return async function viteIndexHtmlMiddleware(req, res, next) {\n const url = req.url && cleanUrl(req.url)\n // spa-fallback always redirects to /index.html\n if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') {\n const filename = getHtmlFilename(url, server)\n if (fs.existsSync(filename)) {\n try {\n let html = fs.readFileSync(filename, 'utf-8')\n html = await server.transformIndexHtml(url, html, req.originalUrl)\n return send(req, res, html, 'html')\n } catch (e) {\n return next(e)\n }\n }\n }\n next()\n }\n}\n","'use strict';\n\nvar url = require('url');\n\nexports = module.exports = function historyApiFallback(options) {\n options = options || {};\n var logger = getLogger(options);\n\n return function(req, res, next) {\n var headers = req.headers;\n if (req.method !== 'GET') {\n logger(\n 'Not rewriting',\n req.method,\n req.url,\n 'because the method is not GET.'\n );\n return next();\n } else if (!headers || typeof headers.accept !== 'string') {\n logger(\n 'Not rewriting',\n req.method,\n req.url,\n 'because the client did not send an HTTP accept header.'\n );\n return next();\n } else if (headers.accept.indexOf('application/json') === 0) {\n logger(\n 'Not rewriting',\n req.method,\n req.url,\n 'because the client prefers JSON.'\n );\n return next();\n } else if (!acceptsHtml(headers.accept, options)) {\n logger(\n 'Not rewriting',\n req.method,\n req.url,\n 'because the client does not accept HTML.'\n );\n return next();\n }\n\n var parsedUrl = url.parse(req.url);\n var rewriteTarget;\n options.rewrites = options.rewrites || [];\n for (var i = 0; i < options.rewrites.length; i++) {\n var rewrite = options.rewrites[i];\n var match = parsedUrl.pathname.match(rewrite.from);\n if (match !== null) {\n rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req);\n\n if(rewriteTarget.charAt(0) !== '/') {\n logger(\n 'We recommend using an absolute path for the rewrite target.',\n 'Received a non-absolute rewrite target',\n rewriteTarget,\n 'for URL',\n req.url\n );\n }\n\n logger('Rewriting', req.method, req.url, 'to', rewriteTarget);\n req.url = rewriteTarget;\n return next();\n }\n }\n\n var pathname = parsedUrl.pathname;\n if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') &&\n options.disableDotRule !== true) {\n logger(\n 'Not rewriting',\n req.method,\n req.url,\n 'because the path includes a dot (.) character.'\n );\n return next();\n }\n\n rewriteTarget = options.index || '/index.html';\n logger('Rewriting', req.method, req.url, 'to', rewriteTarget);\n req.url = rewriteTarget;\n next();\n };\n};\n\nfunction evaluateRewriteRule(parsedUrl, match, rule, req) {\n if (typeof rule === 'string') {\n return rule;\n } else if (typeof rule !== 'function') {\n throw new Error('Rewrite rule can only be of type string or function.');\n }\n\n return rule({\n parsedUrl: parsedUrl,\n match: match,\n request: req\n });\n}\n\nfunction acceptsHtml(header, options) {\n options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*'];\n for (var i = 0; i < options.htmlAcceptHeaders.length; i++) {\n if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) {\n return true;\n }\n }\n return false;\n}\n\nfunction getLogger(options) {\n if (options && options.logger) {\n return options.logger;\n } else if (options && options.verbose) {\n return console.log.bind(console);\n }\n return function(){};\n}\n","import { Connect } from 'types/connect'\nimport { createDebugger, prettifyUrl, timeFrom } from '../../utils'\n\nconst logTime = createDebugger('vite:time')\n\nexport function timeMiddleware(root: string): Connect.NextHandleFunction {\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return function viteTimeMiddleware(req, res, next) {\n const start = Date.now()\n const end = res.end\n res.end = (...args: any[]) => {\n logTime(`${timeFrom(start)} ${prettifyUrl(req.url!, root)}`)\n // @ts-ignore\n return end.call(res, ...args)\n }\n next()\n }\n}\n","import { extname } from 'path'\nimport { isDirectCSSRequest } from '../plugins/css'\nimport {\n cleanUrl,\n normalizePath,\n removeImportQuery,\n removeTimestampQuery\n} from '../utils'\nimport { FS_PREFIX } from '../constants'\nimport { TransformResult } from './transformRequest'\nimport { PluginContainer } from './pluginContainer'\nimport { parse as parseUrl } from 'url'\n\nexport class ModuleNode {\n /**\n * Public served url path, starts with /\n */\n url: string\n /**\n * Resolved file system path + query\n */\n id: string | null = null\n file: string | null = null\n type: 'js' | 'css'\n importers = new Set()\n importedModules = new Set()\n acceptedHmrDeps = new Set()\n isSelfAccepting = false\n transformResult: TransformResult | null = null\n ssrTransformResult: TransformResult | null = null\n ssrModule: Record | null = null\n lastHMRTimestamp = 0\n\n constructor(url: string) {\n this.url = url\n this.type = isDirectCSSRequest(url) ? 'css' : 'js'\n }\n}\n\nfunction invalidateSSRModule(mod: ModuleNode, seen: Set) {\n if (seen.has(mod)) {\n return\n }\n seen.add(mod)\n mod.ssrModule = null\n mod.importers.forEach((importer) => invalidateSSRModule(importer, seen))\n}\nexport class ModuleGraph {\n urlToModuleMap = new Map()\n idToModuleMap = new Map()\n // a single file may corresponds to multiple modules with different queries\n fileToModulesMap = new Map>()\n safeModulesPath = new Set()\n container: PluginContainer\n\n constructor(container: PluginContainer) {\n this.container = container\n }\n\n async getModuleByUrl(rawUrl: string): Promise {\n const [url] = await this.resolveUrl(rawUrl)\n return this.urlToModuleMap.get(url)\n }\n\n getModuleById(id: string): ModuleNode | undefined {\n return this.idToModuleMap.get(removeTimestampQuery(id))\n }\n\n getModulesByFile(file: string): Set | undefined {\n return this.fileToModulesMap.get(file)\n }\n\n onFileChange(file: string): void {\n const mods = this.getModulesByFile(file)\n if (mods) {\n const seen = new Set()\n mods.forEach((mod) => {\n this.invalidateModule(mod, seen)\n })\n }\n }\n\n invalidateModule(mod: ModuleNode, seen: Set = new Set()): void {\n mod.transformResult = null\n mod.ssrTransformResult = null\n invalidateSSRModule(mod, seen)\n }\n\n invalidateAll(): void {\n const seen = new Set()\n this.idToModuleMap.forEach((mod) => {\n this.invalidateModule(mod, seen)\n })\n }\n\n /**\n * Update the module graph based on a module's updated imports information\n * If there are dependencies that no longer have any importers, they are\n * returned as a Set.\n */\n async updateModuleInfo(\n mod: ModuleNode,\n importedModules: Set,\n acceptedModules: Set,\n isSelfAccepting: boolean\n ): Promise | undefined> {\n mod.isSelfAccepting = isSelfAccepting\n const prevImports = mod.importedModules\n const nextImports = (mod.importedModules = new Set())\n let noLongerImported: Set | undefined\n // update import graph\n for (const imported of importedModules) {\n const dep =\n typeof imported === 'string'\n ? await this.ensureEntryFromUrl(imported)\n : imported\n dep.importers.add(mod)\n nextImports.add(dep)\n }\n // remove the importer from deps that were imported but no longer are.\n prevImports.forEach((dep) => {\n if (!nextImports.has(dep)) {\n dep.importers.delete(mod)\n if (!dep.importers.size) {\n // dependency no longer imported\n ;(noLongerImported || (noLongerImported = new Set())).add(dep)\n }\n }\n })\n // update accepted hmr deps\n const deps = (mod.acceptedHmrDeps = new Set())\n for (const accepted of acceptedModules) {\n const dep =\n typeof accepted === 'string'\n ? await this.ensureEntryFromUrl(accepted)\n : accepted\n deps.add(dep)\n }\n return noLongerImported\n }\n\n async ensureEntryFromUrl(rawUrl: string): Promise {\n const [url, resolvedId] = await this.resolveUrl(rawUrl)\n let mod = this.urlToModuleMap.get(url)\n if (!mod) {\n mod = new ModuleNode(url)\n this.urlToModuleMap.set(url, mod)\n mod.id = resolvedId\n this.idToModuleMap.set(resolvedId, mod)\n const file = (mod.file = cleanUrl(resolvedId))\n let fileMappedModules = this.fileToModulesMap.get(file)\n if (!fileMappedModules) {\n fileMappedModules = new Set()\n this.fileToModulesMap.set(file, fileMappedModules)\n }\n fileMappedModules.add(mod)\n }\n return mod\n }\n\n // some deps, like a css file referenced via @import, don't have its own\n // url because they are inlined into the main css import. But they still\n // need to be represented in the module graph so that they can trigger\n // hmr in the importing css file.\n createFileOnlyEntry(file: string): ModuleNode {\n file = normalizePath(file)\n let fileMappedModules = this.fileToModulesMap.get(file)\n if (!fileMappedModules) {\n fileMappedModules = new Set()\n this.fileToModulesMap.set(file, fileMappedModules)\n }\n\n const url = `${FS_PREFIX}${file}`\n for (const m of fileMappedModules) {\n if (m.url === url || m.id === file) {\n return m\n }\n }\n\n const mod = new ModuleNode(url)\n mod.file = file\n fileMappedModules.add(mod)\n return mod\n }\n\n // for incoming urls, it is important to:\n // 1. remove the HMR timestamp query (?t=xxxx)\n // 2. resolve its extension so that urls with or without extension all map to\n // the same module\n async resolveUrl(url: string): Promise<[string, string]> {\n url = removeImportQuery(removeTimestampQuery(url))\n const resolvedId = (await this.container.resolveId(url))?.id || url\n const ext = extname(cleanUrl(resolvedId))\n const { pathname, search, hash } = parseUrl(url)\n if (ext && !pathname!.endsWith(ext)) {\n url = pathname + ext + (search || '') + (hash || '')\n }\n return [url, resolvedId]\n }\n}\n","import fs from 'fs'\nimport path from 'path'\nimport chalk from 'chalk'\nimport { createServer, ViteDevServer } from '..'\nimport { createDebugger, normalizePath } from '../utils'\nimport { ModuleNode } from './moduleGraph'\nimport { Update } from 'types/hmrPayload'\nimport { CLIENT_DIR } from '../constants'\nimport { RollupError } from 'rollup'\nimport match from 'minimatch'\nimport { Server } from 'http'\nimport { isCSSRequest } from '../plugins/css'\n\nexport const debugHmr = createDebugger('vite:hmr')\n\nconst normalizedClientDir = normalizePath(CLIENT_DIR)\n\nexport interface HmrOptions {\n protocol?: string\n host?: string\n port?: number\n clientPort?: number\n path?: string\n timeout?: number\n overlay?: boolean\n server?: Server\n}\n\nexport interface HmrContext {\n file: string\n timestamp: number\n modules: Array\n read: () => string | Promise\n server: ViteDevServer\n}\n\nfunction getShortName(file: string, root: string) {\n return file.startsWith(root + '/') ? path.posix.relative(root, file) : file\n}\n\nexport async function handleHMRUpdate(\n file: string,\n server: ViteDevServer\n): Promise {\n const { ws, config, moduleGraph } = server\n const shortFile = getShortName(file, config.root)\n\n const isConfig = file === config.configFile\n const isConfigDependency = config.configFileDependencies.some(\n (name) => file === path.resolve(name)\n )\n const isEnv = config.inlineConfig.envFile !== false && file.endsWith('.env')\n if (isConfig || isConfigDependency || isEnv) {\n // auto restart server\n debugHmr(`[config change] ${chalk.dim(shortFile)}`)\n config.logger.info(\n chalk.green(\n `${path.relative(process.cwd(), file)} changed, restarting server...`\n ),\n { clear: true, timestamp: true }\n )\n await restartServer(server)\n return\n }\n\n debugHmr(`[file change] ${chalk.dim(shortFile)}`)\n\n // (dev only) the client itself cannot be hot updated.\n if (file.startsWith(normalizedClientDir)) {\n ws.send({\n type: 'full-reload',\n path: '*'\n })\n return\n }\n\n const mods = moduleGraph.getModulesByFile(file)\n\n // check if any plugin wants to perform custom HMR handling\n const timestamp = Date.now()\n const hmrContext: HmrContext = {\n file,\n timestamp,\n modules: mods ? [...mods] : [],\n read: () => readModifiedFile(file),\n server\n }\n\n for (const plugin of config.plugins) {\n if (plugin.handleHotUpdate) {\n const filteredModules = await plugin.handleHotUpdate(hmrContext)\n if (filteredModules) {\n hmrContext.modules = filteredModules\n }\n }\n }\n\n if (!hmrContext.modules.length) {\n // html file cannot be hot updated\n if (file.endsWith('.html')) {\n config.logger.info(chalk.green(`page reload `) + chalk.dim(shortFile), {\n clear: true,\n timestamp: true\n })\n ws.send({\n type: 'full-reload',\n path: config.server.middlewareMode\n ? '*'\n : '/' + normalizePath(path.relative(config.root, file))\n })\n } else {\n // loaded but not in the module graph, probably not js\n debugHmr(`[no modules matched] ${chalk.dim(shortFile)}`)\n }\n return\n }\n\n updateModules(shortFile, hmrContext.modules, timestamp, server)\n}\n\nfunction updateModules(\n file: string,\n modules: ModuleNode[],\n timestamp: number,\n { config, ws }: ViteDevServer\n) {\n const updates: Update[] = []\n const invalidatedModules = new Set()\n let needFullReload = false\n\n for (const mod of modules) {\n invalidate(mod, timestamp, invalidatedModules)\n if (needFullReload) {\n continue\n }\n\n const boundaries = new Set<{\n boundary: ModuleNode\n acceptedVia: ModuleNode\n }>()\n const hasDeadEnd = propagateUpdate(mod, boundaries)\n if (hasDeadEnd) {\n needFullReload = true\n continue\n }\n\n updates.push(\n ...[...boundaries].map(({ boundary, acceptedVia }) => ({\n type: `${boundary.type}-update` as Update['type'],\n timestamp,\n path: boundary.url,\n acceptedPath: acceptedVia.url\n }))\n )\n }\n\n if (needFullReload) {\n config.logger.info(chalk.green(`page reload `) + chalk.dim(file), {\n clear: true,\n timestamp: true\n })\n ws.send({\n type: 'full-reload'\n })\n } else {\n config.logger.info(\n updates\n .map(({ path }) => chalk.green(`hmr update `) + chalk.dim(path))\n .join('\\n'),\n { clear: true, timestamp: true }\n )\n ws.send({\n type: 'update',\n updates\n })\n }\n}\n\nexport async function handleFileAddUnlink(\n file: string,\n server: ViteDevServer,\n isUnlink = false\n): Promise {\n const modules = [...(server.moduleGraph.getModulesByFile(file) ?? [])]\n if (isUnlink && file in server._globImporters) {\n delete server._globImporters[file]\n } else {\n for (const i in server._globImporters) {\n const { module, importGlobs } = server._globImporters[i]\n for (const { base, pattern } of importGlobs) {\n if (match(file, pattern) || match(path.relative(base, file), pattern)) {\n modules.push(module)\n // We use `onFileChange` to invalidate `module.file` so that subsequent `ssrLoadModule()`\n // calls get fresh glob import results with(out) the newly added(/removed) `file`.\n server.moduleGraph.onFileChange(module.file!)\n break\n }\n }\n }\n }\n if (modules.length > 0) {\n updateModules(\n getShortName(file, server.config.root),\n modules,\n Date.now(),\n server\n )\n }\n}\n\nfunction propagateUpdate(\n node: ModuleNode,\n boundaries: Set<{\n boundary: ModuleNode\n acceptedVia: ModuleNode\n }>,\n currentChain: ModuleNode[] = [node]\n): boolean /* hasDeadEnd */ {\n if (node.isSelfAccepting) {\n boundaries.add({\n boundary: node,\n acceptedVia: node\n })\n\n // additionally check for CSS importers, since a PostCSS plugin like\n // Tailwind JIT may register any file as a dependency to a CSS file.\n for (const importer of node.importers) {\n if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {\n propagateUpdate(importer, boundaries, currentChain.concat(importer))\n }\n }\n\n return false\n }\n\n if (!node.importers.size) {\n return true\n }\n\n // #3716, #3913\n // For a non-CSS file, if all of its importers are CSS files (registered via\n // PostCSS plugins) it should be considered a dead end and force full reload.\n if (\n !isCSSRequest(node.url) &&\n [...node.importers].every((i) => isCSSRequest(i.url))\n ) {\n return true\n }\n\n for (const importer of node.importers) {\n const subChain = currentChain.concat(importer)\n if (importer.acceptedHmrDeps.has(node)) {\n boundaries.add({\n boundary: importer,\n acceptedVia: node\n })\n continue\n }\n\n if (currentChain.includes(importer)) {\n // circular deps is considered dead end\n return true\n }\n\n if (propagateUpdate(importer, boundaries, subChain)) {\n return true\n }\n }\n return false\n}\n\nfunction invalidate(mod: ModuleNode, timestamp: number, seen: Set) {\n if (seen.has(mod)) {\n return\n }\n seen.add(mod)\n mod.lastHMRTimestamp = timestamp\n mod.transformResult = null\n mod.ssrModule = null\n mod.ssrTransformResult = null\n mod.importers.forEach((importer) => {\n if (!importer.acceptedHmrDeps.has(mod)) {\n invalidate(importer, timestamp, seen)\n }\n })\n}\n\nexport function handlePrunedModules(\n mods: Set,\n { ws }: ViteDevServer\n): void {\n // update the disposed modules' hmr timestamp\n // since if it's re-imported, it should re-apply side effects\n // and without the timestamp the browser will not re-import it!\n const t = Date.now()\n mods.forEach((mod) => {\n mod.lastHMRTimestamp = t\n debugHmr(`[dispose] ${chalk.dim(mod.file)}`)\n })\n ws.send({\n type: 'prune',\n paths: [...mods].map((m) => m.url)\n })\n}\n\nconst enum LexerState {\n inCall,\n inSingleQuoteString,\n inDoubleQuoteString,\n inTemplateString,\n inArray\n}\n\n/**\n * Lex import.meta.hot.accept() for accepted deps.\n * Since hot.accept() can only accept string literals or array of string\n * literals, we don't really need a heavy @babel/parse call on the entire source.\n *\n * @returns selfAccepts\n */\nexport function lexAcceptedHmrDeps(\n code: string,\n start: number,\n urls: Set<{ url: string; start: number; end: number }>\n): boolean {\n let state: LexerState = LexerState.inCall\n // the state can only be 2 levels deep so no need for a stack\n let prevState: LexerState = LexerState.inCall\n let currentDep: string = ''\n\n function addDep(index: number) {\n urls.add({\n url: currentDep,\n start: index - currentDep.length - 1,\n end: index + 1\n })\n currentDep = ''\n }\n\n for (let i = start; i < code.length; i++) {\n const char = code.charAt(i)\n switch (state) {\n case LexerState.inCall:\n case LexerState.inArray:\n if (char === `'`) {\n prevState = state\n state = LexerState.inSingleQuoteString\n } else if (char === `\"`) {\n prevState = state\n state = LexerState.inDoubleQuoteString\n } else if (char === '`') {\n prevState = state\n state = LexerState.inTemplateString\n } else if (/\\s/.test(char)) {\n continue\n } else {\n if (state === LexerState.inCall) {\n if (char === `[`) {\n state = LexerState.inArray\n } else {\n // reaching here means the first arg is neither a string literal\n // nor an Array literal (direct callback) or there is no arg\n // in both case this indicates a self-accepting module\n return true // done\n }\n } else if (state === LexerState.inArray) {\n if (char === `]`) {\n return false // done\n } else if (char === ',') {\n continue\n } else {\n error(i)\n }\n }\n }\n break\n case LexerState.inSingleQuoteString:\n if (char === `'`) {\n addDep(i)\n if (prevState === LexerState.inCall) {\n // accept('foo', ...)\n return false\n } else {\n state = prevState\n }\n } else {\n currentDep += char\n }\n break\n case LexerState.inDoubleQuoteString:\n if (char === `\"`) {\n addDep(i)\n if (prevState === LexerState.inCall) {\n // accept('foo', ...)\n return false\n } else {\n state = prevState\n }\n } else {\n currentDep += char\n }\n break\n case LexerState.inTemplateString:\n if (char === '`') {\n addDep(i)\n if (prevState === LexerState.inCall) {\n // accept('foo', ...)\n return false\n } else {\n state = prevState\n }\n } else if (char === '$' && code.charAt(i + 1) === '{') {\n error(i)\n } else {\n currentDep += char\n }\n break\n default:\n throw new Error('unknown import.meta.hot lexer state')\n }\n }\n return false\n}\n\nfunction error(pos: number) {\n const err = new Error(\n `import.meta.accept() can only accept string literals or an ` +\n `Array of string literals.`\n ) as RollupError\n err.pos = pos\n throw err\n}\n\n// vitejs/vite#610 when hot-reloading Vue files, we read immediately on file\n// change event and sometimes this can be too early and get an empty buffer.\n// Poll until the file's modified time has changed before reading again.\nasync function readModifiedFile(file: string): Promise {\n const content = fs.readFileSync(file, 'utf-8')\n if (!content) {\n const mtime = fs.statSync(file).mtimeMs\n await new Promise((r) => {\n let n = 0\n const poll = async () => {\n n++\n const newMtime = fs.statSync(file).mtimeMs\n if (newMtime !== mtime || n > 10) {\n r(0)\n } else {\n setTimeout(poll, 10)\n }\n }\n setTimeout(poll, 10)\n })\n return fs.readFileSync(file, 'utf-8')\n } else {\n return content\n }\n}\n\nasync function restartServer(server: ViteDevServer) {\n // @ts-ignore\n global.__vite_start_time = Date.now()\n const { port } = server.config.server\n \n await server.close()\n \n let newServer = null\n try {\n newServer = await createServer(server.config.inlineConfig)\n } catch (err) {\n server.config.logger.error(err.message, {\n timestamp: true,\n })\n return\n }\n\n for (const key in newServer) {\n if (key !== 'app') {\n // @ts-ignore\n server[key] = newServer[key]\n }\n }\n if (!server.config.server.middlewareMode) {\n await server.listen(port, true)\n } else {\n server.config.logger.info('server restarted.', { timestamp: true })\n }\n}\n","'use strict';\nconst fs = require('fs');\n\nlet isDocker;\n\nfunction hasDockerEnv() {\n\ttry {\n\t\tfs.statSync('/.dockerenv');\n\t\treturn true;\n\t} catch (_) {\n\t\treturn false;\n\t}\n}\n\nfunction hasDockerCGroup() {\n\ttry {\n\t\treturn fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');\n\t} catch (_) {\n\t\treturn false;\n\t}\n}\n\nmodule.exports = () => {\n\tif (isDocker === undefined) {\n\t\tisDocker = hasDockerEnv() || hasDockerCGroup();\n\t}\n\n\treturn isDocker;\n};\n","'use strict';\nconst os = require('os');\nconst fs = require('fs');\nconst isDocker = require('is-docker');\n\nconst isWsl = () => {\n\tif (process.platform !== 'linux') {\n\t\treturn false;\n\t}\n\n\tif (os.release().toLowerCase().includes('microsoft')) {\n\t\tif (isDocker()) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\ttry {\n\t\treturn fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ?\n\t\t\t!isDocker() : false;\n\t} catch (_) {\n\t\treturn false;\n\t}\n};\n\nif (process.env.__IS_WSL_TEST__) {\n\tmodule.exports = isWsl;\n} else {\n\tmodule.exports = isWsl();\n}\n","'use strict';\nmodule.exports = (object, propertyName, fn) => {\n\tconst define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});\n\n\tObject.defineProperty(object, propertyName, {\n\t\tconfigurable: true,\n\t\tenumerable: true,\n\t\tget() {\n\t\t\tconst result = fn();\n\t\t\tdefine(result);\n\t\t\treturn result;\n\t\t},\n\t\tset(value) {\n\t\t\tdefine(value);\n\t\t}\n\t});\n\n\treturn object;\n};\n","const path = require('path');\nconst childProcess = require('child_process');\nconst {promises: fs, constants: fsConstants} = require('fs');\nconst isWsl = require('is-wsl');\nconst isDocker = require('is-docker');\nconst defineLazyProperty = require('define-lazy-prop');\n\n// Path to included `xdg-open`.\nconst localXdgOpenPath = path.join(__dirname, 'xdg-open');\n\nconst {platform, arch} = process;\n\n/**\nGet the mount point for fixed drives in WSL.\n\n@inner\n@returns {string} The mount point.\n*/\nconst getWslDrivesMountPoint = (() => {\n\t// Default value for \"root\" param\n\t// according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config\n\tconst defaultMountPoint = '/mnt/';\n\n\tlet mountPoint;\n\n\treturn async function () {\n\t\tif (mountPoint) {\n\t\t\t// Return memoized mount point value\n\t\t\treturn mountPoint;\n\t\t}\n\n\t\tconst configFilePath = '/etc/wsl.conf';\n\n\t\tlet isConfigFileExists = false;\n\t\ttry {\n\t\t\tawait fs.access(configFilePath, fsConstants.F_OK);\n\t\t\tisConfigFileExists = true;\n\t\t} catch {}\n\n\t\tif (!isConfigFileExists) {\n\t\t\treturn defaultMountPoint;\n\t\t}\n\n\t\tconst configContent = await fs.readFile(configFilePath, {encoding: 'utf8'});\n\t\tconst configMountPoint = /(?.*)/g.exec(configContent);\n\n\t\tif (!configMountPoint) {\n\t\t\treturn defaultMountPoint;\n\t\t}\n\n\t\tmountPoint = configMountPoint.groups.mountPoint.trim();\n\t\tmountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;\n\n\t\treturn mountPoint;\n\t};\n})();\n\nconst pTryEach = async (array, mapper) => {\n\tlet latestError;\n\n\tfor (const item of array) {\n\t\ttry {\n\t\t\treturn await mapper(item); // eslint-disable-line no-await-in-loop\n\t\t} catch (error) {\n\t\t\tlatestError = error;\n\t\t}\n\t}\n\n\tthrow latestError;\n};\n\nconst open = async (target, options) => {\n\tif (typeof target !== 'string') {\n\t\tthrow new TypeError('Expected a `target`');\n\t}\n\n\toptions = {\n\t\twait: false,\n\t\tbackground: false,\n\t\tnewInstance: false,\n\t\tallowNonzeroExitCode: false,\n\t\t...options\n\t};\n\n\tif (Array.isArray(options.app)) {\n\t\treturn pTryEach(options.app, singleApp => open(target, {\n\t\t\t...options,\n\t\t\tapp: singleApp\n\t\t}));\n\t}\n\n\tlet {name: app, arguments: appArguments = []} = options.app || {};\n\tappArguments = [...appArguments];\n\n\tif (Array.isArray(app)) {\n\t\treturn pTryEach(app, appName => open(target, {\n\t\t\t...options,\n\t\t\tapp: {\n\t\t\t\tname: appName,\n\t\t\t\targuments: appArguments\n\t\t\t}\n\t\t}));\n\t}\n\n\tlet command;\n\tconst cliArguments = [];\n\tconst childProcessOptions = {};\n\n\tif (platform === 'darwin') {\n\t\tcommand = 'open';\n\n\t\tif (options.wait) {\n\t\t\tcliArguments.push('--wait-apps');\n\t\t}\n\n\t\tif (options.background) {\n\t\t\tcliArguments.push('--background');\n\t\t}\n\n\t\tif (options.newInstance) {\n\t\t\tcliArguments.push('--new');\n\t\t}\n\n\t\tif (app) {\n\t\t\tcliArguments.push('-a', app);\n\t\t}\n\t} else if (platform === 'win32' || (isWsl && !isDocker())) {\n\t\tconst mountPoint = await getWslDrivesMountPoint();\n\n\t\tcommand = isWsl ?\n\t\t\t`${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :\n\t\t\t`${process.env.SYSTEMROOT}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell`;\n\n\t\tcliArguments.push(\n\t\t\t'-NoProfile',\n\t\t\t'-NonInteractive',\n\t\t\t'–ExecutionPolicy',\n\t\t\t'Bypass',\n\t\t\t'-EncodedCommand'\n\t\t);\n\n\t\tif (!isWsl) {\n\t\t\tchildProcessOptions.windowsVerbatimArguments = true;\n\t\t}\n\n\t\tconst encodedArguments = ['Start'];\n\n\t\tif (options.wait) {\n\t\t\tencodedArguments.push('-Wait');\n\t\t}\n\n\t\tif (app) {\n\t\t\t// Double quote with double quotes to ensure the inner quotes are passed through.\n\t\t\t// Inner quotes are delimited for PowerShell interpretation with backticks.\n\t\t\tencodedArguments.push(`\"\\`\"${app}\\`\"\"`, '-ArgumentList');\n\t\t\tappArguments.unshift(target);\n\t\t} else {\n\t\t\tencodedArguments.push(`\"${target}\"`);\n\t\t}\n\n\t\tif (appArguments.length > 0) {\n\t\t\tappArguments = appArguments.map(arg => `\"\\`\"${arg}\\`\"\"`);\n\t\t\tencodedArguments.push(appArguments.join(','));\n\t\t}\n\n\t\t// Using Base64-encoded command, accepted by PowerShell, to allow special characters.\n\t\ttarget = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');\n\t} else {\n\t\tif (app) {\n\t\t\tcommand = app;\n\t\t} else {\n\t\t\t// When bundled by Webpack, there's no actual package file path and no local `xdg-open`.\n\t\t\tconst isBundled = !__dirname || __dirname === '/';\n\n\t\t\t// Check if local `xdg-open` exists and is executable.\n\t\t\tlet exeLocalXdgOpen = false;\n\t\t\ttry {\n\t\t\t\tawait fs.access(localXdgOpenPath, fsConstants.X_OK);\n\t\t\t\texeLocalXdgOpen = true;\n\t\t\t} catch {}\n\n\t\t\tconst useSystemXdgOpen = process.versions.electron ||\n\t\t\t\tplatform === 'android' || isBundled || !exeLocalXdgOpen;\n\t\t\tcommand = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;\n\t\t}\n\n\t\tif (appArguments.length > 0) {\n\t\t\tcliArguments.push(...appArguments);\n\t\t}\n\n\t\tif (!options.wait) {\n\t\t\t// `xdg-open` will block the process unless stdio is ignored\n\t\t\t// and it's detached from the parent even if it's unref'd.\n\t\t\tchildProcessOptions.stdio = 'ignore';\n\t\t\tchildProcessOptions.detached = true;\n\t\t}\n\t}\n\n\tcliArguments.push(target);\n\n\tif (platform === 'darwin' && appArguments.length > 0) {\n\t\tcliArguments.push('--args', ...appArguments);\n\t}\n\n\tconst subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);\n\n\tif (options.wait) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tsubprocess.once('error', reject);\n\n\t\t\tsubprocess.once('close', exitCode => {\n\t\t\t\tif (options.allowNonzeroExitCode && exitCode > 0) {\n\t\t\t\t\treject(new Error(`Exited with code ${exitCode}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresolve(subprocess);\n\t\t\t});\n\t\t});\n\t}\n\n\tsubprocess.unref();\n\n\treturn subprocess;\n};\n\nfunction detectArchBinary(binary) {\n\tif (typeof binary === 'string' || Array.isArray(binary)) {\n\t\treturn binary;\n\t}\n\n\tconst {[arch]: archBinary} = binary;\n\n\tif (!archBinary) {\n\t\tthrow new Error(`${arch} is not supported`);\n\t}\n\n\treturn archBinary;\n}\n\nfunction detectPlatformBinary({[platform]: platformBinary}, {wsl}) {\n\tif (wsl && isWsl) {\n\t\treturn detectArchBinary(wsl);\n\t}\n\n\tif (!platformBinary) {\n\t\tthrow new Error(`${platform} is not supported`);\n\t}\n\n\treturn detectArchBinary(platformBinary);\n}\n\nconst apps = {};\n\ndefineLazyProperty(apps, 'chrome', () => detectPlatformBinary({\n\tdarwin: 'google chrome',\n\twin32: 'chrome',\n\tlinux: ['google-chrome', 'google-chrome-stable']\n}, {\n\twsl: {\n\t\tia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',\n\t\tx64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe']\n\t}\n}));\n\ndefineLazyProperty(apps, 'firefox', () => detectPlatformBinary({\n\tdarwin: 'firefox',\n\twin32: 'C:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe',\n\tlinux: 'firefox'\n}, {\n\twsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe'\n}));\n\ndefineLazyProperty(apps, 'edge', () => detectPlatformBinary({\n\tdarwin: 'microsoft edge',\n\twin32: 'msedge',\n\tlinux: 'microsoft-edge'\n}, {\n\twsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'\n}));\n\nopen.apps = apps;\n\nmodule.exports = open;\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n var pathext = options.pathExt !== undefined ?\n options.pathExt : process.env.PATHEXT\n\n if (!pathext) {\n return true\n }\n\n pathext = pathext.split(';')\n if (pathext.indexOf('') !== -1) {\n return true\n }\n for (var i = 0; i < pathext.length; i++) {\n var p = pathext[i].toLowerCase()\n if (p && path.substr(-p.length).toLowerCase() === p) {\n return true\n }\n }\n return false\n}\n\nfunction checkStat (stat, path, options) {\n if (!stat.isSymbolicLink() && !stat.isFile()) {\n return false\n }\n return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, path, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), path, options)\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n var mod = stat.mode\n var uid = stat.uid\n var gid = stat.gid\n\n var myUid = options.uid !== undefined ?\n options.uid : process.getuid && process.getuid()\n var myGid = options.gid !== undefined ?\n options.gid : process.getgid && process.getgid()\n\n var u = parseInt('100', 8)\n var g = parseInt('010', 8)\n var o = parseInt('001', 8)\n var ug = u | g\n\n var ret = (mod & o) ||\n (mod & g) && gid === myGid ||\n (mod & u) && uid === myUid ||\n (mod & ug) && myUid === 0\n\n return ret\n}\n","var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n core = require('./windows.js')\n} else {\n core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = {}\n }\n\n if (!cb) {\n if (typeof Promise !== 'function') {\n throw new TypeError('callback not provided')\n }\n\n return new Promise(function (resolve, reject) {\n isexe(path, options || {}, function (er, is) {\n if (er) {\n reject(er)\n } else {\n resolve(is)\n }\n })\n })\n }\n\n core(path, options || {}, function (er, is) {\n // ignore EACCES because that just means we aren't allowed to run it\n if (er) {\n if (er.code === 'EACCES' || options && options.ignoreErrors) {\n er = null\n is = false\n }\n }\n cb(er, is)\n })\n}\n\nfunction sync (path, options) {\n // my kingdom for a filtered catch\n try {\n return core.sync(path, options || {})\n } catch (er) {\n if (options && options.ignoreErrors || er.code === 'EACCES') {\n return false\n } else {\n throw er\n }\n }\n}\n","const isWindows = process.platform === 'win32' ||\n process.env.OSTYPE === 'cygwin' ||\n process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n const colon = opt.colon || COLON\n\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n : (\n [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(opt.path || process.env.PATH ||\n /* istanbul ignore next: very unusual */ '').split(colon),\n ]\n )\n const pathExtExe = isWindows\n ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n : ''\n const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n if (isWindows) {\n if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n pathExt.unshift('')\n }\n\n return {\n pathEnv,\n pathExt,\n pathExtExe,\n }\n}\n\nconst which = (cmd, opt, cb) => {\n if (typeof opt === 'function') {\n cb = opt\n opt = {}\n }\n if (!opt)\n opt = {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n const step = i => new Promise((resolve, reject) => {\n if (i === pathEnv.length)\n return opt.all && found.length ? resolve(found)\n : reject(getNotFoundError(cmd))\n\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n resolve(subStep(p, i, 0))\n })\n\n const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n if (ii === pathExt.length)\n return resolve(step(i + 1))\n const ext = pathExt[ii]\n isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n if (!er && is) {\n if (opt.all)\n found.push(p + ext)\n else\n return resolve(p + ext)\n }\n return resolve(subStep(p, i, ii + 1))\n })\n })\n\n return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n opt = opt || {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (let i = 0; i < pathEnv.length; i ++) {\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n for (let j = 0; j < pathExt.length; j ++) {\n const cur = p + pathExt[j]\n try {\n const is = isexe.sync(cur, { pathExt: pathExtExe })\n if (is) {\n if (opt.all)\n found.push(cur)\n else\n return cur\n }\n } catch (ex) {}\n }\n }\n\n if (opt.all && found.length)\n return found\n\n if (opt.nothrow)\n return null\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n const env = parsed.options.env || process.env;\n const cwd = process.cwd();\n const hasCustomCwd = parsed.options.cwd != null;\n // Worker threads do not have process.chdir()\n const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n // If a custom `cwd` was specified, we need to change the process cwd\n // because `which` will do stat calls but does not support a custom cwd\n if (shouldSwitchCwd) {\n try {\n process.chdir(parsed.options.cwd);\n } catch (err) {\n /* Empty */\n }\n }\n\n let resolved;\n\n try {\n resolved = which.sync(parsed.command, {\n path: env[getPathKey({ env })],\n pathExt: withoutPathExt ? path.delimiter : undefined,\n });\n } catch (e) {\n /* Empty */\n } finally {\n if (shouldSwitchCwd) {\n process.chdir(cwd);\n }\n }\n\n // If we successfully resolved, ensure that an absolute path is returned\n // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n if (resolved) {\n resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n }\n\n return resolved;\n}\n\nfunction resolveCommand(parsed) {\n return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n","'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n // Convert to string\n arg = `${arg}`;\n\n // Algorithm below is based on https://qntm.org/cmd\n\n // Sequence of backslashes followed by a double quote:\n // double up all the backslashes and escape the double quote\n arg = arg.replace(/(\\\\*)\"/g, '$1$1\\\\\"');\n\n // Sequence of backslashes followed by the end of the string\n // (which will become a double quote later):\n // double up all the backslashes\n arg = arg.replace(/(\\\\*)$/, '$1$1');\n\n // All other backslashes occur literally\n\n // Quote the whole thing:\n arg = `\"${arg}\"`;\n\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n // Double escape meta chars if necessary\n if (doubleEscapeMetaChars) {\n arg = arg.replace(metaCharsRegExp, '^$1');\n }\n\n return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n","'use strict';\nmodule.exports = /^#!(.*)/;\n","'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n","'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n // Read the first 150 bytes from the file\n const size = 150;\n const buffer = Buffer.alloc(size);\n\n let fd;\n\n try {\n fd = fs.openSync(command, 'r');\n fs.readSync(fd, buffer, 0, size, 0);\n fs.closeSync(fd);\n } catch (e) { /* Empty */ }\n\n // Attempt to extract shebang (null is returned if not a shebang)\n return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n","'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n parsed.file = resolveCommand(parsed);\n\n const shebang = parsed.file && readShebang(parsed.file);\n\n if (shebang) {\n parsed.args.unshift(parsed.file);\n parsed.command = shebang;\n\n return resolveCommand(parsed);\n }\n\n return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n if (!isWin) {\n return parsed;\n }\n\n // Detect & add support for shebangs\n const commandFile = detectShebang(parsed);\n\n // We don't need a shell if the command filename is an executable\n const needsShell = !isExecutableRegExp.test(commandFile);\n\n // If a shell is required, use cmd.exe and take care of escaping everything correctly\n // Note that `forceShell` is an hidden option used only in tests\n if (parsed.options.forceShell || needsShell) {\n // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n // we need to double escape them\n const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n // This is necessary otherwise it will always fail with ENOENT in those cases\n parsed.command = path.normalize(parsed.command);\n\n // Escape command & arguments\n parsed.command = escape.command(parsed.command);\n parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n parsed.command = process.env.comspec || 'cmd.exe';\n parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n }\n\n return parsed;\n}\n\nfunction parse(command, args, options) {\n // Normalize arguments, similar to nodejs\n if (args && !Array.isArray(args)) {\n options = args;\n args = null;\n }\n\n args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n options = Object.assign({}, options); // Clone object to avoid changing the original\n\n // Build our parsed object\n const parsed = {\n command,\n args,\n options,\n file: undefined,\n original: {\n command,\n args,\n },\n };\n\n // Delegate further parsing to shell or non-shell\n return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n","'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n code: 'ENOENT',\n errno: 'ENOENT',\n syscall: `${syscall} ${original.command}`,\n path: original.command,\n spawnargs: original.args,\n });\n}\n\nfunction hookChildProcess(cp, parsed) {\n if (!isWin) {\n return;\n }\n\n const originalEmit = cp.emit;\n\n cp.emit = function (name, arg1) {\n // If emitting \"exit\" event and exit code is 1, we need to check if\n // the command exists and emit an \"error\" instead\n // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n if (name === 'exit') {\n const err = verifyENOENT(arg1, parsed, 'spawn');\n\n if (err) {\n return originalEmit.call(cp, 'error', err);\n }\n }\n\n return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n };\n}\n\nfunction verifyENOENT(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawn');\n }\n\n return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawnSync');\n }\n\n return null;\n}\n\nmodule.exports = {\n hookChildProcess,\n verifyENOENT,\n verifyENOENTSync,\n notFoundError,\n};\n","'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n // Hook into child process \"exit\" event to emit an error if the command\n // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n enoent.hookChildProcess(spawned, parsed);\n\n return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n","'use strict';\n\nmodule.exports = input => {\n\tconst LF = typeof input === 'string' ? '\\n' : '\\n'.charCodeAt();\n\tconst CR = typeof input === 'string' ? '\\r' : '\\r'.charCodeAt();\n\n\tif (input[input.length - 1] === LF) {\n\t\tinput = input.slice(0, input.length - 1);\n\t}\n\n\tif (input[input.length - 1] === CR) {\n\t\tinput = input.slice(0, input.length - 1);\n\t}\n\n\treturn input;\n};\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\nconst path = require('path');\nconst pathKey = require('path-key');\n\nconst npmRunPath = options => {\n\toptions = {\n\t\tcwd: process.cwd(),\n\t\tpath: process.env[pathKey()],\n\t\texecPath: process.execPath,\n\t\t...options\n\t};\n\n\tlet previous;\n\tlet cwdPath = path.resolve(options.cwd);\n\tconst result = [];\n\n\twhile (previous !== cwdPath) {\n\t\tresult.push(path.join(cwdPath, 'node_modules/.bin'));\n\t\tprevious = cwdPath;\n\t\tcwdPath = path.resolve(cwdPath, '..');\n\t}\n\n\t// Ensure the running `node` binary is used\n\tconst execPathDir = path.resolve(options.cwd, options.execPath, '..');\n\tresult.push(execPathDir);\n\n\treturn result.concat(options.path).join(path.delimiter);\n};\n\nmodule.exports = npmRunPath;\n// TODO: Remove this for the next major release\nmodule.exports.default = npmRunPath;\n\nmodule.exports.env = options => {\n\toptions = {\n\t\tenv: process.env,\n\t\t...options\n\t};\n\n\tconst env = {...options.env};\n\tconst path = pathKey({env});\n\n\toptions.path = env[path];\n\tenv[path] = module.exports(options);\n\n\treturn env;\n};\n","'use strict';\n\nconst mimicFn = (to, from) => {\n\tfor (const prop of Reflect.ownKeys(from)) {\n\t\tObject.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));\n\t}\n\n\treturn to;\n};\n\nmodule.exports = mimicFn;\n// TODO: Remove this for the next major release\nmodule.exports.default = mimicFn;\n","'use strict';\nconst mimicFn = require('mimic-fn');\n\nconst calledFunctions = new WeakMap();\n\nconst onetime = (function_, options = {}) => {\n\tif (typeof function_ !== 'function') {\n\t\tthrow new TypeError('Expected a function');\n\t}\n\n\tlet returnValue;\n\tlet callCount = 0;\n\tconst functionName = function_.displayName || function_.name || '';\n\n\tconst onetime = function (...arguments_) {\n\t\tcalledFunctions.set(onetime, ++callCount);\n\n\t\tif (callCount === 1) {\n\t\t\treturnValue = function_.apply(this, arguments_);\n\t\t\tfunction_ = null;\n\t\t} else if (options.throw === true) {\n\t\t\tthrow new Error(`Function \\`${functionName}\\` can only be called once`);\n\t\t}\n\n\t\treturn returnValue;\n\t};\n\n\tmimicFn(onetime, function_);\n\tcalledFunctions.set(onetime, callCount);\n\n\treturn onetime;\n};\n\nmodule.exports = onetime;\n// TODO: Remove this for the next major release\nmodule.exports.default = onetime;\n\nmodule.exports.callCount = function_ => {\n\tif (!calledFunctions.has(function_)) {\n\t\tthrow new Error(`The given function \\`${function_.name}\\` is not wrapped by the \\`onetime\\` package`);\n\t}\n\n\treturn calledFunctions.get(function_);\n};\n","\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:true});exports.SIGNALS=void 0;\n\nconst SIGNALS=[\n{\nname:\"SIGHUP\",\nnumber:1,\naction:\"terminate\",\ndescription:\"Terminal closed\",\nstandard:\"posix\"},\n\n{\nname:\"SIGINT\",\nnumber:2,\naction:\"terminate\",\ndescription:\"User interruption with CTRL-C\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGQUIT\",\nnumber:3,\naction:\"core\",\ndescription:\"User interruption with CTRL-\\\\\",\nstandard:\"posix\"},\n\n{\nname:\"SIGILL\",\nnumber:4,\naction:\"core\",\ndescription:\"Invalid machine instruction\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGTRAP\",\nnumber:5,\naction:\"core\",\ndescription:\"Debugger breakpoint\",\nstandard:\"posix\"},\n\n{\nname:\"SIGABRT\",\nnumber:6,\naction:\"core\",\ndescription:\"Aborted\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGIOT\",\nnumber:6,\naction:\"core\",\ndescription:\"Aborted\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGBUS\",\nnumber:7,\naction:\"core\",\ndescription:\n\"Bus error due to misaligned, non-existing address or paging error\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGEMT\",\nnumber:7,\naction:\"terminate\",\ndescription:\"Command should be emulated but is not implemented\",\nstandard:\"other\"},\n\n{\nname:\"SIGFPE\",\nnumber:8,\naction:\"core\",\ndescription:\"Floating point arithmetic error\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGKILL\",\nnumber:9,\naction:\"terminate\",\ndescription:\"Forced termination\",\nstandard:\"posix\",\nforced:true},\n\n{\nname:\"SIGUSR1\",\nnumber:10,\naction:\"terminate\",\ndescription:\"Application-specific signal\",\nstandard:\"posix\"},\n\n{\nname:\"SIGSEGV\",\nnumber:11,\naction:\"core\",\ndescription:\"Segmentation fault\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGUSR2\",\nnumber:12,\naction:\"terminate\",\ndescription:\"Application-specific signal\",\nstandard:\"posix\"},\n\n{\nname:\"SIGPIPE\",\nnumber:13,\naction:\"terminate\",\ndescription:\"Broken pipe or socket\",\nstandard:\"posix\"},\n\n{\nname:\"SIGALRM\",\nnumber:14,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"posix\"},\n\n{\nname:\"SIGTERM\",\nnumber:15,\naction:\"terminate\",\ndescription:\"Termination\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGSTKFLT\",\nnumber:16,\naction:\"terminate\",\ndescription:\"Stack is empty or overflowed\",\nstandard:\"other\"},\n\n{\nname:\"SIGCHLD\",\nnumber:17,\naction:\"ignore\",\ndescription:\"Child process terminated, paused or unpaused\",\nstandard:\"posix\"},\n\n{\nname:\"SIGCLD\",\nnumber:17,\naction:\"ignore\",\ndescription:\"Child process terminated, paused or unpaused\",\nstandard:\"other\"},\n\n{\nname:\"SIGCONT\",\nnumber:18,\naction:\"unpause\",\ndescription:\"Unpaused\",\nstandard:\"posix\",\nforced:true},\n\n{\nname:\"SIGSTOP\",\nnumber:19,\naction:\"pause\",\ndescription:\"Paused\",\nstandard:\"posix\",\nforced:true},\n\n{\nname:\"SIGTSTP\",\nnumber:20,\naction:\"pause\",\ndescription:\"Paused using CTRL-Z or \\\"suspend\\\"\",\nstandard:\"posix\"},\n\n{\nname:\"SIGTTIN\",\nnumber:21,\naction:\"pause\",\ndescription:\"Background process cannot read terminal input\",\nstandard:\"posix\"},\n\n{\nname:\"SIGBREAK\",\nnumber:21,\naction:\"terminate\",\ndescription:\"User interruption with CTRL-BREAK\",\nstandard:\"other\"},\n\n{\nname:\"SIGTTOU\",\nnumber:22,\naction:\"pause\",\ndescription:\"Background process cannot write to terminal output\",\nstandard:\"posix\"},\n\n{\nname:\"SIGURG\",\nnumber:23,\naction:\"ignore\",\ndescription:\"Socket received out-of-band data\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGXCPU\",\nnumber:24,\naction:\"core\",\ndescription:\"Process timed out\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGXFSZ\",\nnumber:25,\naction:\"core\",\ndescription:\"File too big\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGVTALRM\",\nnumber:26,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGPROF\",\nnumber:27,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGWINCH\",\nnumber:28,\naction:\"ignore\",\ndescription:\"Terminal window size changed\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGIO\",\nnumber:29,\naction:\"terminate\",\ndescription:\"I/O is available\",\nstandard:\"other\"},\n\n{\nname:\"SIGPOLL\",\nnumber:29,\naction:\"terminate\",\ndescription:\"Watched event\",\nstandard:\"other\"},\n\n{\nname:\"SIGINFO\",\nnumber:29,\naction:\"ignore\",\ndescription:\"Request for process information\",\nstandard:\"other\"},\n\n{\nname:\"SIGPWR\",\nnumber:30,\naction:\"terminate\",\ndescription:\"Device running out of power\",\nstandard:\"systemv\"},\n\n{\nname:\"SIGSYS\",\nnumber:31,\naction:\"core\",\ndescription:\"Invalid system call\",\nstandard:\"other\"},\n\n{\nname:\"SIGUNUSED\",\nnumber:31,\naction:\"terminate\",\ndescription:\"Invalid system call\",\nstandard:\"other\"}];exports.SIGNALS=SIGNALS;\n//# sourceMappingURL=core.js.map","\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:true});exports.SIGRTMAX=exports.getRealtimeSignals=void 0;\nconst getRealtimeSignals=function(){\nconst length=SIGRTMAX-SIGRTMIN+1;\nreturn Array.from({length},getRealtimeSignal);\n};exports.getRealtimeSignals=getRealtimeSignals;\n\nconst getRealtimeSignal=function(value,index){\nreturn{\nname:`SIGRT${index+1}`,\nnumber:SIGRTMIN+index,\naction:\"terminate\",\ndescription:\"Application-specific signal (realtime)\",\nstandard:\"posix\"};\n\n};\n\nconst SIGRTMIN=34;\nconst SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX;\n//# sourceMappingURL=realtime.js.map","\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:true});exports.getSignals=void 0;var _os=require(\"os\");\n\nvar _core=require(\"./core.js\");\nvar _realtime=require(\"./realtime.js\");\n\n\n\nconst getSignals=function(){\nconst realtimeSignals=(0,_realtime.getRealtimeSignals)();\nconst signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal);\nreturn signals;\n};exports.getSignals=getSignals;\n\n\n\n\n\n\n\nconst normalizeSignal=function({\nname,\nnumber:defaultNumber,\ndescription,\naction,\nforced=false,\nstandard})\n{\nconst{\nsignals:{[name]:constantSignal}}=\n_os.constants;\nconst supported=constantSignal!==undefined;\nconst number=supported?constantSignal:defaultNumber;\nreturn{name,number,description,supported,action,forced,standard};\n};\n//# sourceMappingURL=signals.js.map","\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:true});exports.signalsByNumber=exports.signalsByName=void 0;var _os=require(\"os\");\n\nvar _signals=require(\"./signals.js\");\nvar _realtime=require(\"./realtime.js\");\n\n\n\nconst getSignalsByName=function(){\nconst signals=(0,_signals.getSignals)();\nreturn signals.reduce(getSignalByName,{});\n};\n\nconst getSignalByName=function(\nsignalByNameMemo,\n{name,number,description,supported,action,forced,standard})\n{\nreturn{\n...signalByNameMemo,\n[name]:{name,number,description,supported,action,forced,standard}};\n\n};\n\nconst signalsByName=getSignalsByName();exports.signalsByName=signalsByName;\n\n\n\n\nconst getSignalsByNumber=function(){\nconst signals=(0,_signals.getSignals)();\nconst length=_realtime.SIGRTMAX+1;\nconst signalsA=Array.from({length},(value,number)=>\ngetSignalByNumber(number,signals));\n\nreturn Object.assign({},...signalsA);\n};\n\nconst getSignalByNumber=function(number,signals){\nconst signal=findSignalByNumber(number,signals);\n\nif(signal===undefined){\nreturn{};\n}\n\nconst{name,description,supported,action,forced,standard}=signal;\nreturn{\n[number]:{\nname,\nnumber,\ndescription,\nsupported,\naction,\nforced,\nstandard}};\n\n\n};\n\n\n\nconst findSignalByNumber=function(number,signals){\nconst signal=signals.find(({name})=>_os.constants.signals[name]===number);\n\nif(signal!==undefined){\nreturn signal;\n}\n\nreturn signals.find(signalA=>signalA.number===number);\n};\n\nconst signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber;\n//# sourceMappingURL=main.js.map","'use strict';\nconst {signalsByName} = require('human-signals');\n\nconst getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {\n\tif (timedOut) {\n\t\treturn `timed out after ${timeout} milliseconds`;\n\t}\n\n\tif (isCanceled) {\n\t\treturn 'was canceled';\n\t}\n\n\tif (errorCode !== undefined) {\n\t\treturn `failed with ${errorCode}`;\n\t}\n\n\tif (signal !== undefined) {\n\t\treturn `was killed with ${signal} (${signalDescription})`;\n\t}\n\n\tif (exitCode !== undefined) {\n\t\treturn `failed with exit code ${exitCode}`;\n\t}\n\n\treturn 'failed';\n};\n\nconst makeError = ({\n\tstdout,\n\tstderr,\n\tall,\n\terror,\n\tsignal,\n\texitCode,\n\tcommand,\n\tescapedCommand,\n\ttimedOut,\n\tisCanceled,\n\tkilled,\n\tparsed: {options: {timeout}}\n}) => {\n\t// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.\n\t// We normalize them to `undefined`\n\texitCode = exitCode === null ? undefined : exitCode;\n\tsignal = signal === null ? undefined : signal;\n\tconst signalDescription = signal === undefined ? undefined : signalsByName[signal].description;\n\n\tconst errorCode = error && error.code;\n\n\tconst prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});\n\tconst execaMessage = `Command ${prefix}: ${command}`;\n\tconst isError = Object.prototype.toString.call(error) === '[object Error]';\n\tconst shortMessage = isError ? `${execaMessage}\\n${error.message}` : execaMessage;\n\tconst message = [shortMessage, stderr, stdout].filter(Boolean).join('\\n');\n\n\tif (isError) {\n\t\terror.originalMessage = error.message;\n\t\terror.message = message;\n\t} else {\n\t\terror = new Error(message);\n\t}\n\n\terror.shortMessage = shortMessage;\n\terror.command = command;\n\terror.escapedCommand = escapedCommand;\n\terror.exitCode = exitCode;\n\terror.signal = signal;\n\terror.signalDescription = signalDescription;\n\terror.stdout = stdout;\n\terror.stderr = stderr;\n\n\tif (all !== undefined) {\n\t\terror.all = all;\n\t}\n\n\tif ('bufferedData' in error) {\n\t\tdelete error.bufferedData;\n\t}\n\n\terror.failed = true;\n\terror.timedOut = Boolean(timedOut);\n\terror.isCanceled = isCanceled;\n\terror.killed = killed && !timedOut;\n\n\treturn error;\n};\n\nmodule.exports = makeError;\n","'use strict';\nconst aliases = ['stdin', 'stdout', 'stderr'];\n\nconst hasAlias = options => aliases.some(alias => options[alias] !== undefined);\n\nconst normalizeStdio = options => {\n\tif (!options) {\n\t\treturn;\n\t}\n\n\tconst {stdio} = options;\n\n\tif (stdio === undefined) {\n\t\treturn aliases.map(alias => options[alias]);\n\t}\n\n\tif (hasAlias(options)) {\n\t\tthrow new Error(`It's not possible to provide \\`stdio\\` in combination with one of ${aliases.map(alias => `\\`${alias}\\``).join(', ')}`);\n\t}\n\n\tif (typeof stdio === 'string') {\n\t\treturn stdio;\n\t}\n\n\tif (!Array.isArray(stdio)) {\n\t\tthrow new TypeError(`Expected \\`stdio\\` to be of type \\`string\\` or \\`Array\\`, got \\`${typeof stdio}\\``);\n\t}\n\n\tconst length = Math.max(stdio.length, aliases.length);\n\treturn Array.from({length}, (value, index) => stdio[index]);\n};\n\nmodule.exports = normalizeStdio;\n\n// `ipc` is pushed unless it is already present\nmodule.exports.node = options => {\n\tconst stdio = normalizeStdio(options);\n\n\tif (stdio === 'ipc') {\n\t\treturn 'ipc';\n\t}\n\n\tif (stdio === undefined || typeof stdio === 'string') {\n\t\treturn [stdio, stdio, stdio, 'ipc'];\n\t}\n\n\tif (stdio.includes('ipc')) {\n\t\treturn stdio;\n\t}\n\n\treturn [...stdio, 'ipc'];\n};\n","// This is not the set of all possible signals.\n//\n// It IS, however, the set of all signals that trigger\n// an exit on either Linux or BSD systems. Linux is a\n// superset of the signal names supported on BSD, and\n// the unknown signals just fail to register, so we can\n// catch that easily enough.\n//\n// Don't bother with SIGKILL. It's uncatchable, which\n// means that we can't fire any callbacks anyway.\n//\n// If a user does happen to register a handler on a non-\n// fatal signal like SIGWINCH or something, and then\n// exit, it'll end up firing `process.emit('exit')`, so\n// the handler will be fired anyway.\n//\n// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n// artificially, inherently leave the process in a\n// state from which it is not safe to try and enter JS\n// listeners.\nmodule.exports = [\n 'SIGABRT',\n 'SIGALRM',\n 'SIGHUP',\n 'SIGINT',\n 'SIGTERM'\n]\n\nif (process.platform !== 'win32') {\n module.exports.push(\n 'SIGVTALRM',\n 'SIGXCPU',\n 'SIGXFSZ',\n 'SIGUSR2',\n 'SIGTRAP',\n 'SIGSYS',\n 'SIGQUIT',\n 'SIGIOT'\n // should detect profiler and enable/disable accordingly.\n // see #21\n // 'SIGPROF'\n )\n}\n\nif (process.platform === 'linux') {\n module.exports.push(\n 'SIGIO',\n 'SIGPOLL',\n 'SIGPWR',\n 'SIGSTKFLT',\n 'SIGUNUSED'\n )\n}\n","// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\nvar assert = require('assert')\nvar signals = require('./signals.js')\nvar isWin = /^win/i.test(process.platform)\n\nvar EE = require('events')\n/* istanbul ignore if */\nif (typeof EE !== 'function') {\n EE = EE.EventEmitter\n}\n\nvar emitter\nif (process.__signal_exit_emitter__) {\n emitter = process.__signal_exit_emitter__\n} else {\n emitter = process.__signal_exit_emitter__ = new EE()\n emitter.count = 0\n emitter.emitted = {}\n}\n\n// Because this emitter is a global, we have to check to see if a\n// previous version of this library failed to enable infinite listeners.\n// I know what you're about to say. But literally everything about\n// signal-exit is a compromise with evil. Get used to it.\nif (!emitter.infinite) {\n emitter.setMaxListeners(Infinity)\n emitter.infinite = true\n}\n\nmodule.exports = function (cb, opts) {\n assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler')\n\n if (loaded === false) {\n load()\n }\n\n var ev = 'exit'\n if (opts && opts.alwaysLast) {\n ev = 'afterexit'\n }\n\n var remove = function () {\n emitter.removeListener(ev, cb)\n if (emitter.listeners('exit').length === 0 &&\n emitter.listeners('afterexit').length === 0) {\n unload()\n }\n }\n emitter.on(ev, cb)\n\n return remove\n}\n\nmodule.exports.unload = unload\nfunction unload () {\n if (!loaded) {\n return\n }\n loaded = false\n\n signals.forEach(function (sig) {\n try {\n process.removeListener(sig, sigListeners[sig])\n } catch (er) {}\n })\n process.emit = originalProcessEmit\n process.reallyExit = originalProcessReallyExit\n emitter.count -= 1\n}\n\nfunction emit (event, code, signal) {\n if (emitter.emitted[event]) {\n return\n }\n emitter.emitted[event] = true\n emitter.emit(event, code, signal)\n}\n\n// { : , ... }\nvar sigListeners = {}\nsignals.forEach(function (sig) {\n sigListeners[sig] = function listener () {\n // If there are no other listeners, an exit is coming!\n // Simplest way: remove us and then re-send the signal.\n // We know that this will kill the process, so we can\n // safely emit now.\n var listeners = process.listeners(sig)\n if (listeners.length === emitter.count) {\n unload()\n emit('exit', null, sig)\n /* istanbul ignore next */\n emit('afterexit', null, sig)\n /* istanbul ignore next */\n if (isWin && sig === 'SIGHUP') {\n // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n // so use a supported signal instead\n sig = 'SIGINT'\n }\n process.kill(process.pid, sig)\n }\n }\n})\n\nmodule.exports.signals = function () {\n return signals\n}\n\nmodule.exports.load = load\n\nvar loaded = false\n\nfunction load () {\n if (loaded) {\n return\n }\n loaded = true\n\n // This is the number of onSignalExit's that are in play.\n // It's important so that we can count the correct number of\n // listeners on signals, and don't wait for the other one to\n // handle it instead of us.\n emitter.count += 1\n\n signals = signals.filter(function (sig) {\n try {\n process.on(sig, sigListeners[sig])\n return true\n } catch (er) {\n return false\n }\n })\n\n process.emit = processEmit\n process.reallyExit = processReallyExit\n}\n\nvar originalProcessReallyExit = process.reallyExit\nfunction processReallyExit (code) {\n process.exitCode = code || 0\n emit('exit', process.exitCode, null)\n /* istanbul ignore next */\n emit('afterexit', process.exitCode, null)\n /* istanbul ignore next */\n originalProcessReallyExit.call(process, process.exitCode)\n}\n\nvar originalProcessEmit = process.emit\nfunction processEmit (ev, arg) {\n if (ev === 'exit') {\n if (arg !== undefined) {\n process.exitCode = arg\n }\n var ret = originalProcessEmit.apply(this, arguments)\n emit('exit', process.exitCode, null)\n /* istanbul ignore next */\n emit('afterexit', process.exitCode, null)\n return ret\n } else {\n return originalProcessEmit.apply(this, arguments)\n }\n}\n","'use strict';\nconst os = require('os');\nconst onExit = require('signal-exit');\n\nconst DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;\n\n// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior\nconst spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {\n\tconst killResult = kill(signal);\n\tsetKillTimeout(kill, signal, options, killResult);\n\treturn killResult;\n};\n\nconst setKillTimeout = (kill, signal, options, killResult) => {\n\tif (!shouldForceKill(signal, options, killResult)) {\n\t\treturn;\n\t}\n\n\tconst timeout = getForceKillAfterTimeout(options);\n\tconst t = setTimeout(() => {\n\t\tkill('SIGKILL');\n\t}, timeout);\n\n\t// Guarded because there's no `.unref()` when `execa` is used in the renderer\n\t// process in Electron. This cannot be tested since we don't run tests in\n\t// Electron.\n\t// istanbul ignore else\n\tif (t.unref) {\n\t\tt.unref();\n\t}\n};\n\nconst shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {\n\treturn isSigterm(signal) && forceKillAfterTimeout !== false && killResult;\n};\n\nconst isSigterm = signal => {\n\treturn signal === os.constants.signals.SIGTERM ||\n\t\t(typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');\n};\n\nconst getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {\n\tif (forceKillAfterTimeout === true) {\n\t\treturn DEFAULT_FORCE_KILL_TIMEOUT;\n\t}\n\n\tif (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {\n\t\tthrow new TypeError(`Expected the \\`forceKillAfterTimeout\\` option to be a non-negative integer, got \\`${forceKillAfterTimeout}\\` (${typeof forceKillAfterTimeout})`);\n\t}\n\n\treturn forceKillAfterTimeout;\n};\n\n// `childProcess.cancel()`\nconst spawnedCancel = (spawned, context) => {\n\tconst killResult = spawned.kill();\n\n\tif (killResult) {\n\t\tcontext.isCanceled = true;\n\t}\n};\n\nconst timeoutKill = (spawned, signal, reject) => {\n\tspawned.kill(signal);\n\treject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));\n};\n\n// `timeout` option handling\nconst setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {\n\tif (timeout === 0 || timeout === undefined) {\n\t\treturn spawnedPromise;\n\t}\n\n\tlet timeoutId;\n\tconst timeoutPromise = new Promise((resolve, reject) => {\n\t\ttimeoutId = setTimeout(() => {\n\t\t\ttimeoutKill(spawned, killSignal, reject);\n\t\t}, timeout);\n\t});\n\n\tconst safeSpawnedPromise = spawnedPromise.finally(() => {\n\t\tclearTimeout(timeoutId);\n\t});\n\n\treturn Promise.race([timeoutPromise, safeSpawnedPromise]);\n};\n\nconst validateTimeout = ({timeout}) => {\n\tif (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {\n\t\tthrow new TypeError(`Expected the \\`timeout\\` option to be a non-negative integer, got \\`${timeout}\\` (${typeof timeout})`);\n\t}\n};\n\n// `cleanup` option handling\nconst setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {\n\tif (!cleanup || detached) {\n\t\treturn timedPromise;\n\t}\n\n\tconst removeExitHandler = onExit(() => {\n\t\tspawned.kill();\n\t});\n\n\treturn timedPromise.finally(() => {\n\t\tremoveExitHandler();\n\t});\n};\n\nmodule.exports = {\n\tspawnedKill,\n\tspawnedCancel,\n\tsetupTimeout,\n\tvalidateTimeout,\n\tsetExitHandler\n};\n","'use strict';\n\nconst isStream = stream =>\n\tstream !== null &&\n\ttypeof stream === 'object' &&\n\ttypeof stream.pipe === 'function';\n\nisStream.writable = stream =>\n\tisStream(stream) &&\n\tstream.writable !== false &&\n\ttypeof stream._write === 'function' &&\n\ttypeof stream._writableState === 'object';\n\nisStream.readable = stream =>\n\tisStream(stream) &&\n\tstream.readable !== false &&\n\ttypeof stream._read === 'function' &&\n\ttypeof stream._readableState === 'object';\n\nisStream.duplex = stream =>\n\tisStream.writable(stream) &&\n\tisStream.readable(stream);\n\nisStream.transform = stream =>\n\tisStream.duplex(stream) &&\n\ttypeof stream._transform === 'function';\n\nmodule.exports = isStream;\n","'use strict';\nconst {PassThrough: PassThroughStream} = require('stream');\n\nmodule.exports = options => {\n\toptions = {...options};\n\n\tconst {array} = options;\n\tlet {encoding} = options;\n\tconst isBuffer = encoding === 'buffer';\n\tlet objectMode = false;\n\n\tif (array) {\n\t\tobjectMode = !(encoding || isBuffer);\n\t} else {\n\t\tencoding = encoding || 'utf8';\n\t}\n\n\tif (isBuffer) {\n\t\tencoding = null;\n\t}\n\n\tconst stream = new PassThroughStream({objectMode});\n\n\tif (encoding) {\n\t\tstream.setEncoding(encoding);\n\t}\n\n\tlet length = 0;\n\tconst chunks = [];\n\n\tstream.on('data', chunk => {\n\t\tchunks.push(chunk);\n\n\t\tif (objectMode) {\n\t\t\tlength = chunks.length;\n\t\t} else {\n\t\t\tlength += chunk.length;\n\t\t}\n\t});\n\n\tstream.getBufferedValue = () => {\n\t\tif (array) {\n\t\t\treturn chunks;\n\t\t}\n\n\t\treturn isBuffer ? Buffer.concat(chunks, length) : chunks.join('');\n\t};\n\n\tstream.getBufferedLength = () => length;\n\n\treturn stream;\n};\n","'use strict';\nconst {constants: BufferConstants} = require('buffer');\nconst stream = require('stream');\nconst {promisify} = require('util');\nconst bufferStream = require('./buffer-stream');\n\nconst streamPipelinePromisified = promisify(stream.pipeline);\n\nclass MaxBufferError extends Error {\n\tconstructor() {\n\t\tsuper('maxBuffer exceeded');\n\t\tthis.name = 'MaxBufferError';\n\t}\n}\n\nasync function getStream(inputStream, options) {\n\tif (!inputStream) {\n\t\tthrow new Error('Expected a stream');\n\t}\n\n\toptions = {\n\t\tmaxBuffer: Infinity,\n\t\t...options\n\t};\n\n\tconst {maxBuffer} = options;\n\tconst stream = bufferStream(options);\n\n\tawait new Promise((resolve, reject) => {\n\t\tconst rejectPromise = error => {\n\t\t\t// Don't retrieve an oversized buffer.\n\t\t\tif (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {\n\t\t\t\terror.bufferedData = stream.getBufferedValue();\n\t\t\t}\n\n\t\t\treject(error);\n\t\t};\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tawait streamPipelinePromisified(inputStream, stream);\n\t\t\t\tresolve();\n\t\t\t} catch (error) {\n\t\t\t\trejectPromise(error);\n\t\t\t}\n\t\t})();\n\n\t\tstream.on('data', () => {\n\t\t\tif (stream.getBufferedLength() > maxBuffer) {\n\t\t\t\trejectPromise(new MaxBufferError());\n\t\t\t}\n\t\t});\n\t});\n\n\treturn stream.getBufferedValue();\n}\n\nmodule.exports = getStream;\nmodule.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});\nmodule.exports.array = (stream, options) => getStream(stream, {...options, array: true});\nmodule.exports.MaxBufferError = MaxBufferError;\n","'use strict';\n\nconst { PassThrough } = require('stream');\n\nmodule.exports = function (/*streams...*/) {\n var sources = []\n var output = new PassThrough({objectMode: true})\n\n output.setMaxListeners(0)\n\n output.add = add\n output.isEmpty = isEmpty\n\n output.on('unpipe', remove)\n\n Array.prototype.slice.call(arguments).forEach(add)\n\n return output\n\n function add (source) {\n if (Array.isArray(source)) {\n source.forEach(add)\n return this\n }\n\n sources.push(source);\n source.once('end', remove.bind(null, source))\n source.once('error', output.emit.bind(output, 'error'))\n source.pipe(output, {end: false})\n return this\n }\n\n function isEmpty () {\n return sources.length == 0;\n }\n\n function remove (source) {\n sources = sources.filter(function (it) { return it !== source })\n if (!sources.length && output.readable) { output.end() }\n }\n}\n","'use strict';\nconst isStream = require('is-stream');\nconst getStream = require('get-stream');\nconst mergeStream = require('merge-stream');\n\n// `input` option\nconst handleInput = (spawned, input) => {\n\t// Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852\n\t// @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0\n\tif (input === undefined || spawned.stdin === undefined) {\n\t\treturn;\n\t}\n\n\tif (isStream(input)) {\n\t\tinput.pipe(spawned.stdin);\n\t} else {\n\t\tspawned.stdin.end(input);\n\t}\n};\n\n// `all` interleaves `stdout` and `stderr`\nconst makeAllStream = (spawned, {all}) => {\n\tif (!all || (!spawned.stdout && !spawned.stderr)) {\n\t\treturn;\n\t}\n\n\tconst mixed = mergeStream();\n\n\tif (spawned.stdout) {\n\t\tmixed.add(spawned.stdout);\n\t}\n\n\tif (spawned.stderr) {\n\t\tmixed.add(spawned.stderr);\n\t}\n\n\treturn mixed;\n};\n\n// On failure, `result.stdout|stderr|all` should contain the currently buffered stream\nconst getBufferedData = async (stream, streamPromise) => {\n\tif (!stream) {\n\t\treturn;\n\t}\n\n\tstream.destroy();\n\n\ttry {\n\t\treturn await streamPromise;\n\t} catch (error) {\n\t\treturn error.bufferedData;\n\t}\n};\n\nconst getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {\n\tif (!stream || !buffer) {\n\t\treturn;\n\t}\n\n\tif (encoding) {\n\t\treturn getStream(stream, {encoding, maxBuffer});\n\t}\n\n\treturn getStream.buffer(stream, {maxBuffer});\n};\n\n// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)\nconst getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {\n\tconst stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});\n\tconst stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});\n\tconst allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});\n\n\ttry {\n\t\treturn await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);\n\t} catch (error) {\n\t\treturn Promise.all([\n\t\t\t{error, signal: error.signal, timedOut: error.timedOut},\n\t\t\tgetBufferedData(stdout, stdoutPromise),\n\t\t\tgetBufferedData(stderr, stderrPromise),\n\t\t\tgetBufferedData(all, allPromise)\n\t\t]);\n\t}\n};\n\nconst validateInputSync = ({input}) => {\n\tif (isStream(input)) {\n\t\tthrow new TypeError('The `input` option cannot be a stream in sync mode');\n\t}\n};\n\nmodule.exports = {\n\thandleInput,\n\tmakeAllStream,\n\tgetSpawnedResult,\n\tvalidateInputSync\n};\n\n","'use strict';\n\nconst nativePromisePrototype = (async () => {})().constructor.prototype;\nconst descriptors = ['then', 'catch', 'finally'].map(property => [\n\tproperty,\n\tReflect.getOwnPropertyDescriptor(nativePromisePrototype, property)\n]);\n\n// The return value is a mixin of `childProcess` and `Promise`\nconst mergePromise = (spawned, promise) => {\n\tfor (const [property, descriptor] of descriptors) {\n\t\t// Starting the main `promise` is deferred to avoid consuming streams\n\t\tconst value = typeof promise === 'function' ?\n\t\t\t(...args) => Reflect.apply(descriptor.value, promise(), args) :\n\t\t\tdescriptor.value.bind(promise);\n\n\t\tReflect.defineProperty(spawned, property, {...descriptor, value});\n\t}\n\n\treturn spawned;\n};\n\n// Use promises instead of `child_process` events\nconst getSpawnedPromise = spawned => {\n\treturn new Promise((resolve, reject) => {\n\t\tspawned.on('exit', (exitCode, signal) => {\n\t\t\tresolve({exitCode, signal});\n\t\t});\n\n\t\tspawned.on('error', error => {\n\t\t\treject(error);\n\t\t});\n\n\t\tif (spawned.stdin) {\n\t\t\tspawned.stdin.on('error', error => {\n\t\t\t\treject(error);\n\t\t\t});\n\t\t}\n\t});\n};\n\nmodule.exports = {\n\tmergePromise,\n\tgetSpawnedPromise\n};\n\n","'use strict';\nconst normalizeArgs = (file, args = []) => {\n\tif (!Array.isArray(args)) {\n\t\treturn [file];\n\t}\n\n\treturn [file, ...args];\n};\n\nconst NO_ESCAPE_REGEXP = /^[\\w.-]+$/;\nconst DOUBLE_QUOTES_REGEXP = /\"/g;\n\nconst escapeArg = arg => {\n\tif (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) {\n\t\treturn arg;\n\t}\n\n\treturn `\"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\\\\"')}\"`;\n};\n\nconst joinCommand = (file, args) => {\n\treturn normalizeArgs(file, args).join(' ');\n};\n\nconst getEscapedCommand = (file, args) => {\n\treturn normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');\n};\n\nconst SPACES_REGEXP = / +/g;\n\n// Handle `execa.command()`\nconst parseCommand = command => {\n\tconst tokens = [];\n\tfor (const token of command.trim().split(SPACES_REGEXP)) {\n\t\t// Allow spaces to be escaped by a backslash if not meant as a delimiter\n\t\tconst previousToken = tokens[tokens.length - 1];\n\t\tif (previousToken && previousToken.endsWith('\\\\')) {\n\t\t\t// Merge previous token with current one\n\t\t\ttokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;\n\t\t} else {\n\t\t\ttokens.push(token);\n\t\t}\n\t}\n\n\treturn tokens;\n};\n\nmodule.exports = {\n\tjoinCommand,\n\tgetEscapedCommand,\n\tparseCommand\n};\n","'use strict';\nconst path = require('path');\nconst childProcess = require('child_process');\nconst crossSpawn = require('cross-spawn');\nconst stripFinalNewline = require('strip-final-newline');\nconst npmRunPath = require('npm-run-path');\nconst onetime = require('onetime');\nconst makeError = require('./lib/error');\nconst normalizeStdio = require('./lib/stdio');\nconst {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = require('./lib/kill');\nconst {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream');\nconst {mergePromise, getSpawnedPromise} = require('./lib/promise');\nconst {joinCommand, parseCommand, getEscapedCommand} = require('./lib/command');\n\nconst DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;\n\nconst getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {\n\tconst env = extendEnv ? {...process.env, ...envOption} : envOption;\n\n\tif (preferLocal) {\n\t\treturn npmRunPath.env({env, cwd: localDir, execPath});\n\t}\n\n\treturn env;\n};\n\nconst handleArguments = (file, args, options = {}) => {\n\tconst parsed = crossSpawn._parse(file, args, options);\n\tfile = parsed.command;\n\targs = parsed.args;\n\toptions = parsed.options;\n\n\toptions = {\n\t\tmaxBuffer: DEFAULT_MAX_BUFFER,\n\t\tbuffer: true,\n\t\tstripFinalNewline: true,\n\t\textendEnv: true,\n\t\tpreferLocal: false,\n\t\tlocalDir: options.cwd || process.cwd(),\n\t\texecPath: process.execPath,\n\t\tencoding: 'utf8',\n\t\treject: true,\n\t\tcleanup: true,\n\t\tall: false,\n\t\twindowsHide: true,\n\t\t...options\n\t};\n\n\toptions.env = getEnv(options);\n\n\toptions.stdio = normalizeStdio(options);\n\n\tif (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {\n\t\t// #116\n\t\targs.unshift('/q');\n\t}\n\n\treturn {file, args, options, parsed};\n};\n\nconst handleOutput = (options, value, error) => {\n\tif (typeof value !== 'string' && !Buffer.isBuffer(value)) {\n\t\t// When `execa.sync()` errors, we normalize it to '' to mimic `execa()`\n\t\treturn error === undefined ? undefined : '';\n\t}\n\n\tif (options.stripFinalNewline) {\n\t\treturn stripFinalNewline(value);\n\t}\n\n\treturn value;\n};\n\nconst execa = (file, args, options) => {\n\tconst parsed = handleArguments(file, args, options);\n\tconst command = joinCommand(file, args);\n\tconst escapedCommand = getEscapedCommand(file, args);\n\n\tvalidateTimeout(parsed.options);\n\n\tlet spawned;\n\ttry {\n\t\tspawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);\n\t} catch (error) {\n\t\t// Ensure the returned error is always both a promise and a child process\n\t\tconst dummySpawned = new childProcess.ChildProcess();\n\t\tconst errorPromise = Promise.reject(makeError({\n\t\t\terror,\n\t\t\tstdout: '',\n\t\t\tstderr: '',\n\t\t\tall: '',\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tparsed,\n\t\t\ttimedOut: false,\n\t\t\tisCanceled: false,\n\t\t\tkilled: false\n\t\t}));\n\t\treturn mergePromise(dummySpawned, errorPromise);\n\t}\n\n\tconst spawnedPromise = getSpawnedPromise(spawned);\n\tconst timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);\n\tconst processDone = setExitHandler(spawned, parsed.options, timedPromise);\n\n\tconst context = {isCanceled: false};\n\n\tspawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));\n\tspawned.cancel = spawnedCancel.bind(null, spawned, context);\n\n\tconst handlePromise = async () => {\n\t\tconst [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);\n\t\tconst stdout = handleOutput(parsed.options, stdoutResult);\n\t\tconst stderr = handleOutput(parsed.options, stderrResult);\n\t\tconst all = handleOutput(parsed.options, allResult);\n\n\t\tif (error || exitCode !== 0 || signal !== null) {\n\t\t\tconst returnedError = makeError({\n\t\t\t\terror,\n\t\t\t\texitCode,\n\t\t\t\tsignal,\n\t\t\t\tstdout,\n\t\t\t\tstderr,\n\t\t\t\tall,\n\t\t\t\tcommand,\n\t\t\t\tescapedCommand,\n\t\t\t\tparsed,\n\t\t\t\ttimedOut,\n\t\t\t\tisCanceled: context.isCanceled,\n\t\t\t\tkilled: spawned.killed\n\t\t\t});\n\n\t\t\tif (!parsed.options.reject) {\n\t\t\t\treturn returnedError;\n\t\t\t}\n\n\t\t\tthrow returnedError;\n\t\t}\n\n\t\treturn {\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\texitCode: 0,\n\t\t\tstdout,\n\t\t\tstderr,\n\t\t\tall,\n\t\t\tfailed: false,\n\t\t\ttimedOut: false,\n\t\t\tisCanceled: false,\n\t\t\tkilled: false\n\t\t};\n\t};\n\n\tconst handlePromiseOnce = onetime(handlePromise);\n\n\thandleInput(spawned, parsed.options.input);\n\n\tspawned.all = makeAllStream(spawned, parsed.options);\n\n\treturn mergePromise(spawned, handlePromiseOnce);\n};\n\nmodule.exports = execa;\n\nmodule.exports.sync = (file, args, options) => {\n\tconst parsed = handleArguments(file, args, options);\n\tconst command = joinCommand(file, args);\n\tconst escapedCommand = getEscapedCommand(file, args);\n\n\tvalidateInputSync(parsed.options);\n\n\tlet result;\n\ttry {\n\t\tresult = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);\n\t} catch (error) {\n\t\tthrow makeError({\n\t\t\terror,\n\t\t\tstdout: '',\n\t\t\tstderr: '',\n\t\t\tall: '',\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tparsed,\n\t\t\ttimedOut: false,\n\t\t\tisCanceled: false,\n\t\t\tkilled: false\n\t\t});\n\t}\n\n\tconst stdout = handleOutput(parsed.options, result.stdout, result.error);\n\tconst stderr = handleOutput(parsed.options, result.stderr, result.error);\n\n\tif (result.error || result.status !== 0 || result.signal !== null) {\n\t\tconst error = makeError({\n\t\t\tstdout,\n\t\t\tstderr,\n\t\t\terror: result.error,\n\t\t\tsignal: result.signal,\n\t\t\texitCode: result.status,\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tparsed,\n\t\t\ttimedOut: result.error && result.error.code === 'ETIMEDOUT',\n\t\t\tisCanceled: false,\n\t\t\tkilled: result.signal !== null\n\t\t});\n\n\t\tif (!parsed.options.reject) {\n\t\t\treturn error;\n\t\t}\n\n\t\tthrow error;\n\t}\n\n\treturn {\n\t\tcommand,\n\t\tescapedCommand,\n\t\texitCode: 0,\n\t\tstdout,\n\t\tstderr,\n\t\tfailed: false,\n\t\ttimedOut: false,\n\t\tisCanceled: false,\n\t\tkilled: false\n\t};\n};\n\nmodule.exports.command = (command, options) => {\n\tconst [file, ...args] = parseCommand(command);\n\treturn execa(file, args, options);\n};\n\nmodule.exports.commandSync = (command, options) => {\n\tconst [file, ...args] = parseCommand(command);\n\treturn execa.sync(file, args, options);\n};\n\nmodule.exports.node = (scriptPath, args, options = {}) => {\n\tif (args && !Array.isArray(args) && typeof args === 'object') {\n\t\toptions = args;\n\t\targs = [];\n\t}\n\n\tconst stdio = normalizeStdio.node(options);\n\tconst defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));\n\n\tconst {\n\t\tnodePath = process.execPath,\n\t\tnodeOptions = defaultExecArgv\n\t} = options;\n\n\treturn execa(\n\t\tnodePath,\n\t\t[\n\t\t\t...nodeOptions,\n\t\t\tscriptPath,\n\t\t\t...(Array.isArray(args) ? args : [])\n\t\t],\n\t\t{\n\t\t\t...options,\n\t\t\tstdin: undefined,\n\t\t\tstdout: undefined,\n\t\t\tstderr: undefined,\n\t\t\tstdio,\n\t\t\tshell: false\n\t\t}\n\t);\n};\n","/**\n * The following is modified based on source found in\n * https://github.com/facebook/create-react-app\n *\n * MIT Licensed\n * Copyright (c) 2015-present, Facebook, Inc.\n * https://github.com/facebook/create-react-app/blob/master/LICENSE\n *\n */\n\nimport path from 'path'\nimport open from 'open'\nimport execa from 'execa'\nimport chalk from 'chalk'\nimport { execSync } from 'child_process'\nimport { Logger } from '../logger'\n\n// https://github.com/sindresorhus/open#app\nconst OSX_CHROME = 'google chrome'\n\n/**\n * Reads the BROWSER environment variable and decides what to do with it.\n * Returns true if it opened a browser or ran a node.js script, otherwise false.\n */\nexport function openBrowser(\n url: string,\n opt: string | true,\n logger: Logger\n): boolean {\n // The browser executable to open.\n // See https://github.com/sindresorhus/open#app for documentation.\n const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''\n if (browser.toLowerCase().endsWith('.js')) {\n return executeNodeScript(browser, url, logger)\n } else if (browser.toLowerCase() !== 'none') {\n return startBrowserProcess(browser, url)\n }\n return false\n}\n\nfunction executeNodeScript(scriptPath: string, url: string, logger: Logger) {\n const extraArgs = process.argv.slice(2)\n const child = execa('node', [scriptPath, ...extraArgs, url], {\n stdio: 'inherit'\n })\n child.on('close', (code) => {\n if (code !== 0) {\n logger.error(\n chalk.red(\n `\\nThe script specified as BROWSER environment variable failed.\\n\\n${chalk.cyan(\n scriptPath\n )} exited with code ${code}.`\n ),\n { error: null }\n )\n }\n })\n return true\n}\n\nfunction startBrowserProcess(browser: string | undefined, url: string) {\n // If we're on OS X, the user hasn't specifically\n // requested a different browser, we can try opening\n // Chrome with AppleScript. This lets us reuse an\n // existing tab when possible instead of creating a new one.\n const shouldTryOpenChromeWithAppleScript =\n process.platform === 'darwin' && (browser === '' || browser === OSX_CHROME)\n\n if (shouldTryOpenChromeWithAppleScript) {\n try {\n // Try our best to reuse existing tab\n // on OS X Google Chrome with AppleScript\n execSync('ps cax | grep \"Google Chrome\"')\n execSync('osascript openChrome.applescript \"' + encodeURI(url) + '\"', {\n cwd: path.dirname(require.resolve('vite/bin/openChrome.applescript')),\n stdio: 'ignore'\n })\n return true\n } catch (err) {\n // Ignore errors\n }\n }\n\n // Another special case: on OS X, check if BROWSER has been set to \"open\".\n // In this case, instead of passing the string `open` to `open` function (which won't work),\n // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):\n // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768\n if (process.platform === 'darwin' && browser === 'open') {\n browser = undefined\n }\n\n // Fallback to open\n // (It will always open new tab)\n try {\n const options: open.Options = browser ? { app: { name: browser } } : {}\n open(url, options).catch(() => {}) // Prevent `unhandledRejection` error.\n return true\n } catch (err) {\n return false\n }\n}\n","'use strict';\n\nvar matchOperatorsRe = /[|\\\\{}()[\\]^$+*?.]/g;\n\nmodule.exports = function (str) {\n\tif (typeof str !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\treturn str.replace(matchOperatorsRe, '\\\\$&');\n};\n","'use strict'\r\n\r\nmodule.exports = {\r\n\t\"aliceblue\": [240, 248, 255],\r\n\t\"antiquewhite\": [250, 235, 215],\r\n\t\"aqua\": [0, 255, 255],\r\n\t\"aquamarine\": [127, 255, 212],\r\n\t\"azure\": [240, 255, 255],\r\n\t\"beige\": [245, 245, 220],\r\n\t\"bisque\": [255, 228, 196],\r\n\t\"black\": [0, 0, 0],\r\n\t\"blanchedalmond\": [255, 235, 205],\r\n\t\"blue\": [0, 0, 255],\r\n\t\"blueviolet\": [138, 43, 226],\r\n\t\"brown\": [165, 42, 42],\r\n\t\"burlywood\": [222, 184, 135],\r\n\t\"cadetblue\": [95, 158, 160],\r\n\t\"chartreuse\": [127, 255, 0],\r\n\t\"chocolate\": [210, 105, 30],\r\n\t\"coral\": [255, 127, 80],\r\n\t\"cornflowerblue\": [100, 149, 237],\r\n\t\"cornsilk\": [255, 248, 220],\r\n\t\"crimson\": [220, 20, 60],\r\n\t\"cyan\": [0, 255, 255],\r\n\t\"darkblue\": [0, 0, 139],\r\n\t\"darkcyan\": [0, 139, 139],\r\n\t\"darkgoldenrod\": [184, 134, 11],\r\n\t\"darkgray\": [169, 169, 169],\r\n\t\"darkgreen\": [0, 100, 0],\r\n\t\"darkgrey\": [169, 169, 169],\r\n\t\"darkkhaki\": [189, 183, 107],\r\n\t\"darkmagenta\": [139, 0, 139],\r\n\t\"darkolivegreen\": [85, 107, 47],\r\n\t\"darkorange\": [255, 140, 0],\r\n\t\"darkorchid\": [153, 50, 204],\r\n\t\"darkred\": [139, 0, 0],\r\n\t\"darksalmon\": [233, 150, 122],\r\n\t\"darkseagreen\": [143, 188, 143],\r\n\t\"darkslateblue\": [72, 61, 139],\r\n\t\"darkslategray\": [47, 79, 79],\r\n\t\"darkslategrey\": [47, 79, 79],\r\n\t\"darkturquoise\": [0, 206, 209],\r\n\t\"darkviolet\": [148, 0, 211],\r\n\t\"deeppink\": [255, 20, 147],\r\n\t\"deepskyblue\": [0, 191, 255],\r\n\t\"dimgray\": [105, 105, 105],\r\n\t\"dimgrey\": [105, 105, 105],\r\n\t\"dodgerblue\": [30, 144, 255],\r\n\t\"firebrick\": [178, 34, 34],\r\n\t\"floralwhite\": [255, 250, 240],\r\n\t\"forestgreen\": [34, 139, 34],\r\n\t\"fuchsia\": [255, 0, 255],\r\n\t\"gainsboro\": [220, 220, 220],\r\n\t\"ghostwhite\": [248, 248, 255],\r\n\t\"gold\": [255, 215, 0],\r\n\t\"goldenrod\": [218, 165, 32],\r\n\t\"gray\": [128, 128, 128],\r\n\t\"green\": [0, 128, 0],\r\n\t\"greenyellow\": [173, 255, 47],\r\n\t\"grey\": [128, 128, 128],\r\n\t\"honeydew\": [240, 255, 240],\r\n\t\"hotpink\": [255, 105, 180],\r\n\t\"indianred\": [205, 92, 92],\r\n\t\"indigo\": [75, 0, 130],\r\n\t\"ivory\": [255, 255, 240],\r\n\t\"khaki\": [240, 230, 140],\r\n\t\"lavender\": [230, 230, 250],\r\n\t\"lavenderblush\": [255, 240, 245],\r\n\t\"lawngreen\": [124, 252, 0],\r\n\t\"lemonchiffon\": [255, 250, 205],\r\n\t\"lightblue\": [173, 216, 230],\r\n\t\"lightcoral\": [240, 128, 128],\r\n\t\"lightcyan\": [224, 255, 255],\r\n\t\"lightgoldenrodyellow\": [250, 250, 210],\r\n\t\"lightgray\": [211, 211, 211],\r\n\t\"lightgreen\": [144, 238, 144],\r\n\t\"lightgrey\": [211, 211, 211],\r\n\t\"lightpink\": [255, 182, 193],\r\n\t\"lightsalmon\": [255, 160, 122],\r\n\t\"lightseagreen\": [32, 178, 170],\r\n\t\"lightskyblue\": [135, 206, 250],\r\n\t\"lightslategray\": [119, 136, 153],\r\n\t\"lightslategrey\": [119, 136, 153],\r\n\t\"lightsteelblue\": [176, 196, 222],\r\n\t\"lightyellow\": [255, 255, 224],\r\n\t\"lime\": [0, 255, 0],\r\n\t\"limegreen\": [50, 205, 50],\r\n\t\"linen\": [250, 240, 230],\r\n\t\"magenta\": [255, 0, 255],\r\n\t\"maroon\": [128, 0, 0],\r\n\t\"mediumaquamarine\": [102, 205, 170],\r\n\t\"mediumblue\": [0, 0, 205],\r\n\t\"mediumorchid\": [186, 85, 211],\r\n\t\"mediumpurple\": [147, 112, 219],\r\n\t\"mediumseagreen\": [60, 179, 113],\r\n\t\"mediumslateblue\": [123, 104, 238],\r\n\t\"mediumspringgreen\": [0, 250, 154],\r\n\t\"mediumturquoise\": [72, 209, 204],\r\n\t\"mediumvioletred\": [199, 21, 133],\r\n\t\"midnightblue\": [25, 25, 112],\r\n\t\"mintcream\": [245, 255, 250],\r\n\t\"mistyrose\": [255, 228, 225],\r\n\t\"moccasin\": [255, 228, 181],\r\n\t\"navajowhite\": [255, 222, 173],\r\n\t\"navy\": [0, 0, 128],\r\n\t\"oldlace\": [253, 245, 230],\r\n\t\"olive\": [128, 128, 0],\r\n\t\"olivedrab\": [107, 142, 35],\r\n\t\"orange\": [255, 165, 0],\r\n\t\"orangered\": [255, 69, 0],\r\n\t\"orchid\": [218, 112, 214],\r\n\t\"palegoldenrod\": [238, 232, 170],\r\n\t\"palegreen\": [152, 251, 152],\r\n\t\"paleturquoise\": [175, 238, 238],\r\n\t\"palevioletred\": [219, 112, 147],\r\n\t\"papayawhip\": [255, 239, 213],\r\n\t\"peachpuff\": [255, 218, 185],\r\n\t\"peru\": [205, 133, 63],\r\n\t\"pink\": [255, 192, 203],\r\n\t\"plum\": [221, 160, 221],\r\n\t\"powderblue\": [176, 224, 230],\r\n\t\"purple\": [128, 0, 128],\r\n\t\"rebeccapurple\": [102, 51, 153],\r\n\t\"red\": [255, 0, 0],\r\n\t\"rosybrown\": [188, 143, 143],\r\n\t\"royalblue\": [65, 105, 225],\r\n\t\"saddlebrown\": [139, 69, 19],\r\n\t\"salmon\": [250, 128, 114],\r\n\t\"sandybrown\": [244, 164, 96],\r\n\t\"seagreen\": [46, 139, 87],\r\n\t\"seashell\": [255, 245, 238],\r\n\t\"sienna\": [160, 82, 45],\r\n\t\"silver\": [192, 192, 192],\r\n\t\"skyblue\": [135, 206, 235],\r\n\t\"slateblue\": [106, 90, 205],\r\n\t\"slategray\": [112, 128, 144],\r\n\t\"slategrey\": [112, 128, 144],\r\n\t\"snow\": [255, 250, 250],\r\n\t\"springgreen\": [0, 255, 127],\r\n\t\"steelblue\": [70, 130, 180],\r\n\t\"tan\": [210, 180, 140],\r\n\t\"teal\": [0, 128, 128],\r\n\t\"thistle\": [216, 191, 216],\r\n\t\"tomato\": [255, 99, 71],\r\n\t\"turquoise\": [64, 224, 208],\r\n\t\"violet\": [238, 130, 238],\r\n\t\"wheat\": [245, 222, 179],\r\n\t\"white\": [255, 255, 255],\r\n\t\"whitesmoke\": [245, 245, 245],\r\n\t\"yellow\": [255, 255, 0],\r\n\t\"yellowgreen\": [154, 205, 50]\r\n};\r\n","/* MIT license */\nvar cssKeywords = require('color-name');\n\n// NOTE: conversions should only return primitive values (i.e. arrays, or\n// values that give correct `typeof` results).\n// do not use box values types (i.e. Number(), String(), etc.)\n\nvar reverseKeywords = {};\nfor (var key in cssKeywords) {\n\tif (cssKeywords.hasOwnProperty(key)) {\n\t\treverseKeywords[cssKeywords[key]] = key;\n\t}\n}\n\nvar convert = module.exports = {\n\trgb: {channels: 3, labels: 'rgb'},\n\thsl: {channels: 3, labels: 'hsl'},\n\thsv: {channels: 3, labels: 'hsv'},\n\thwb: {channels: 3, labels: 'hwb'},\n\tcmyk: {channels: 4, labels: 'cmyk'},\n\txyz: {channels: 3, labels: 'xyz'},\n\tlab: {channels: 3, labels: 'lab'},\n\tlch: {channels: 3, labels: 'lch'},\n\thex: {channels: 1, labels: ['hex']},\n\tkeyword: {channels: 1, labels: ['keyword']},\n\tansi16: {channels: 1, labels: ['ansi16']},\n\tansi256: {channels: 1, labels: ['ansi256']},\n\thcg: {channels: 3, labels: ['h', 'c', 'g']},\n\tapple: {channels: 3, labels: ['r16', 'g16', 'b16']},\n\tgray: {channels: 1, labels: ['gray']}\n};\n\n// hide .channels and .labels properties\nfor (var model in convert) {\n\tif (convert.hasOwnProperty(model)) {\n\t\tif (!('channels' in convert[model])) {\n\t\t\tthrow new Error('missing channels property: ' + model);\n\t\t}\n\n\t\tif (!('labels' in convert[model])) {\n\t\t\tthrow new Error('missing channel labels property: ' + model);\n\t\t}\n\n\t\tif (convert[model].labels.length !== convert[model].channels) {\n\t\t\tthrow new Error('channel and label counts mismatch: ' + model);\n\t\t}\n\n\t\tvar channels = convert[model].channels;\n\t\tvar labels = convert[model].labels;\n\t\tdelete convert[model].channels;\n\t\tdelete convert[model].labels;\n\t\tObject.defineProperty(convert[model], 'channels', {value: channels});\n\t\tObject.defineProperty(convert[model], 'labels', {value: labels});\n\t}\n}\n\nconvert.rgb.hsl = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar min = Math.min(r, g, b);\n\tvar max = Math.max(r, g, b);\n\tvar delta = max - min;\n\tvar h;\n\tvar s;\n\tvar l;\n\n\tif (max === min) {\n\t\th = 0;\n\t} else if (r === max) {\n\t\th = (g - b) / delta;\n\t} else if (g === max) {\n\t\th = 2 + (b - r) / delta;\n\t} else if (b === max) {\n\t\th = 4 + (r - g) / delta;\n\t}\n\n\th = Math.min(h * 60, 360);\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tl = (min + max) / 2;\n\n\tif (max === min) {\n\t\ts = 0;\n\t} else if (l <= 0.5) {\n\t\ts = delta / (max + min);\n\t} else {\n\t\ts = delta / (2 - max - min);\n\t}\n\n\treturn [h, s * 100, l * 100];\n};\n\nconvert.rgb.hsv = function (rgb) {\n\tvar rdif;\n\tvar gdif;\n\tvar bdif;\n\tvar h;\n\tvar s;\n\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar v = Math.max(r, g, b);\n\tvar diff = v - Math.min(r, g, b);\n\tvar diffc = function (c) {\n\t\treturn (v - c) / 6 / diff + 1 / 2;\n\t};\n\n\tif (diff === 0) {\n\t\th = s = 0;\n\t} else {\n\t\ts = diff / v;\n\t\trdif = diffc(r);\n\t\tgdif = diffc(g);\n\t\tbdif = diffc(b);\n\n\t\tif (r === v) {\n\t\t\th = bdif - gdif;\n\t\t} else if (g === v) {\n\t\t\th = (1 / 3) + rdif - bdif;\n\t\t} else if (b === v) {\n\t\t\th = (2 / 3) + gdif - rdif;\n\t\t}\n\t\tif (h < 0) {\n\t\t\th += 1;\n\t\t} else if (h > 1) {\n\t\t\th -= 1;\n\t\t}\n\t}\n\n\treturn [\n\t\th * 360,\n\t\ts * 100,\n\t\tv * 100\n\t];\n};\n\nconvert.rgb.hwb = function (rgb) {\n\tvar r = rgb[0];\n\tvar g = rgb[1];\n\tvar b = rgb[2];\n\tvar h = convert.rgb.hsl(rgb)[0];\n\tvar w = 1 / 255 * Math.min(r, Math.min(g, b));\n\n\tb = 1 - 1 / 255 * Math.max(r, Math.max(g, b));\n\n\treturn [h, w * 100, b * 100];\n};\n\nconvert.rgb.cmyk = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar c;\n\tvar m;\n\tvar y;\n\tvar k;\n\n\tk = Math.min(1 - r, 1 - g, 1 - b);\n\tc = (1 - r - k) / (1 - k) || 0;\n\tm = (1 - g - k) / (1 - k) || 0;\n\ty = (1 - b - k) / (1 - k) || 0;\n\n\treturn [c * 100, m * 100, y * 100, k * 100];\n};\n\n/**\n * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance\n * */\nfunction comparativeDistance(x, y) {\n\treturn (\n\t\tMath.pow(x[0] - y[0], 2) +\n\t\tMath.pow(x[1] - y[1], 2) +\n\t\tMath.pow(x[2] - y[2], 2)\n\t);\n}\n\nconvert.rgb.keyword = function (rgb) {\n\tvar reversed = reverseKeywords[rgb];\n\tif (reversed) {\n\t\treturn reversed;\n\t}\n\n\tvar currentClosestDistance = Infinity;\n\tvar currentClosestKeyword;\n\n\tfor (var keyword in cssKeywords) {\n\t\tif (cssKeywords.hasOwnProperty(keyword)) {\n\t\t\tvar value = cssKeywords[keyword];\n\n\t\t\t// Compute comparative distance\n\t\t\tvar distance = comparativeDistance(rgb, value);\n\n\t\t\t// Check if its less, if so set as closest\n\t\t\tif (distance < currentClosestDistance) {\n\t\t\t\tcurrentClosestDistance = distance;\n\t\t\t\tcurrentClosestKeyword = keyword;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn currentClosestKeyword;\n};\n\nconvert.keyword.rgb = function (keyword) {\n\treturn cssKeywords[keyword];\n};\n\nconvert.rgb.xyz = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\n\t// assume sRGB\n\tr = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);\n\tg = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);\n\tb = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);\n\n\tvar x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);\n\tvar y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);\n\tvar z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);\n\n\treturn [x * 100, y * 100, z * 100];\n};\n\nconvert.rgb.lab = function (rgb) {\n\tvar xyz = convert.rgb.xyz(rgb);\n\tvar x = xyz[0];\n\tvar y = xyz[1];\n\tvar z = xyz[2];\n\tvar l;\n\tvar a;\n\tvar b;\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);\n\n\tl = (116 * y) - 16;\n\ta = 500 * (x - y);\n\tb = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.hsl.rgb = function (hsl) {\n\tvar h = hsl[0] / 360;\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar t1;\n\tvar t2;\n\tvar t3;\n\tvar rgb;\n\tvar val;\n\n\tif (s === 0) {\n\t\tval = l * 255;\n\t\treturn [val, val, val];\n\t}\n\n\tif (l < 0.5) {\n\t\tt2 = l * (1 + s);\n\t} else {\n\t\tt2 = l + s - l * s;\n\t}\n\n\tt1 = 2 * l - t2;\n\n\trgb = [0, 0, 0];\n\tfor (var i = 0; i < 3; i++) {\n\t\tt3 = h + 1 / 3 * -(i - 1);\n\t\tif (t3 < 0) {\n\t\t\tt3++;\n\t\t}\n\t\tif (t3 > 1) {\n\t\t\tt3--;\n\t\t}\n\n\t\tif (6 * t3 < 1) {\n\t\t\tval = t1 + (t2 - t1) * 6 * t3;\n\t\t} else if (2 * t3 < 1) {\n\t\t\tval = t2;\n\t\t} else if (3 * t3 < 2) {\n\t\t\tval = t1 + (t2 - t1) * (2 / 3 - t3) * 6;\n\t\t} else {\n\t\t\tval = t1;\n\t\t}\n\n\t\trgb[i] = val * 255;\n\t}\n\n\treturn rgb;\n};\n\nconvert.hsl.hsv = function (hsl) {\n\tvar h = hsl[0];\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar smin = s;\n\tvar lmin = Math.max(l, 0.01);\n\tvar sv;\n\tvar v;\n\n\tl *= 2;\n\ts *= (l <= 1) ? l : 2 - l;\n\tsmin *= lmin <= 1 ? lmin : 2 - lmin;\n\tv = (l + s) / 2;\n\tsv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);\n\n\treturn [h, sv * 100, v * 100];\n};\n\nconvert.hsv.rgb = function (hsv) {\n\tvar h = hsv[0] / 60;\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\tvar hi = Math.floor(h) % 6;\n\n\tvar f = h - Math.floor(h);\n\tvar p = 255 * v * (1 - s);\n\tvar q = 255 * v * (1 - (s * f));\n\tvar t = 255 * v * (1 - (s * (1 - f)));\n\tv *= 255;\n\n\tswitch (hi) {\n\t\tcase 0:\n\t\t\treturn [v, t, p];\n\t\tcase 1:\n\t\t\treturn [q, v, p];\n\t\tcase 2:\n\t\t\treturn [p, v, t];\n\t\tcase 3:\n\t\t\treturn [p, q, v];\n\t\tcase 4:\n\t\t\treturn [t, p, v];\n\t\tcase 5:\n\t\t\treturn [v, p, q];\n\t}\n};\n\nconvert.hsv.hsl = function (hsv) {\n\tvar h = hsv[0];\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\tvar vmin = Math.max(v, 0.01);\n\tvar lmin;\n\tvar sl;\n\tvar l;\n\n\tl = (2 - s) * v;\n\tlmin = (2 - s) * vmin;\n\tsl = s * vmin;\n\tsl /= (lmin <= 1) ? lmin : 2 - lmin;\n\tsl = sl || 0;\n\tl /= 2;\n\n\treturn [h, sl * 100, l * 100];\n};\n\n// http://dev.w3.org/csswg/css-color/#hwb-to-rgb\nconvert.hwb.rgb = function (hwb) {\n\tvar h = hwb[0] / 360;\n\tvar wh = hwb[1] / 100;\n\tvar bl = hwb[2] / 100;\n\tvar ratio = wh + bl;\n\tvar i;\n\tvar v;\n\tvar f;\n\tvar n;\n\n\t// wh + bl cant be > 1\n\tif (ratio > 1) {\n\t\twh /= ratio;\n\t\tbl /= ratio;\n\t}\n\n\ti = Math.floor(6 * h);\n\tv = 1 - bl;\n\tf = 6 * h - i;\n\n\tif ((i & 0x01) !== 0) {\n\t\tf = 1 - f;\n\t}\n\n\tn = wh + f * (v - wh); // linear interpolation\n\n\tvar r;\n\tvar g;\n\tvar b;\n\tswitch (i) {\n\t\tdefault:\n\t\tcase 6:\n\t\tcase 0: r = v; g = n; b = wh; break;\n\t\tcase 1: r = n; g = v; b = wh; break;\n\t\tcase 2: r = wh; g = v; b = n; break;\n\t\tcase 3: r = wh; g = n; b = v; break;\n\t\tcase 4: r = n; g = wh; b = v; break;\n\t\tcase 5: r = v; g = wh; b = n; break;\n\t}\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.cmyk.rgb = function (cmyk) {\n\tvar c = cmyk[0] / 100;\n\tvar m = cmyk[1] / 100;\n\tvar y = cmyk[2] / 100;\n\tvar k = cmyk[3] / 100;\n\tvar r;\n\tvar g;\n\tvar b;\n\n\tr = 1 - Math.min(1, c * (1 - k) + k);\n\tg = 1 - Math.min(1, m * (1 - k) + k);\n\tb = 1 - Math.min(1, y * (1 - k) + k);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.rgb = function (xyz) {\n\tvar x = xyz[0] / 100;\n\tvar y = xyz[1] / 100;\n\tvar z = xyz[2] / 100;\n\tvar r;\n\tvar g;\n\tvar b;\n\n\tr = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);\n\tg = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);\n\tb = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);\n\n\t// assume sRGB\n\tr = r > 0.0031308\n\t\t? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)\n\t\t: r * 12.92;\n\n\tg = g > 0.0031308\n\t\t? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)\n\t\t: g * 12.92;\n\n\tb = b > 0.0031308\n\t\t? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)\n\t\t: b * 12.92;\n\n\tr = Math.min(Math.max(0, r), 1);\n\tg = Math.min(Math.max(0, g), 1);\n\tb = Math.min(Math.max(0, b), 1);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.lab = function (xyz) {\n\tvar x = xyz[0];\n\tvar y = xyz[1];\n\tvar z = xyz[2];\n\tvar l;\n\tvar a;\n\tvar b;\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);\n\n\tl = (116 * y) - 16;\n\ta = 500 * (x - y);\n\tb = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.lab.xyz = function (lab) {\n\tvar l = lab[0];\n\tvar a = lab[1];\n\tvar b = lab[2];\n\tvar x;\n\tvar y;\n\tvar z;\n\n\ty = (l + 16) / 116;\n\tx = a / 500 + y;\n\tz = y - b / 200;\n\n\tvar y2 = Math.pow(y, 3);\n\tvar x2 = Math.pow(x, 3);\n\tvar z2 = Math.pow(z, 3);\n\ty = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;\n\tx = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;\n\tz = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;\n\n\tx *= 95.047;\n\ty *= 100;\n\tz *= 108.883;\n\n\treturn [x, y, z];\n};\n\nconvert.lab.lch = function (lab) {\n\tvar l = lab[0];\n\tvar a = lab[1];\n\tvar b = lab[2];\n\tvar hr;\n\tvar h;\n\tvar c;\n\n\thr = Math.atan2(b, a);\n\th = hr * 360 / 2 / Math.PI;\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tc = Math.sqrt(a * a + b * b);\n\n\treturn [l, c, h];\n};\n\nconvert.lch.lab = function (lch) {\n\tvar l = lch[0];\n\tvar c = lch[1];\n\tvar h = lch[2];\n\tvar a;\n\tvar b;\n\tvar hr;\n\n\thr = h / 360 * 2 * Math.PI;\n\ta = c * Math.cos(hr);\n\tb = c * Math.sin(hr);\n\n\treturn [l, a, b];\n};\n\nconvert.rgb.ansi16 = function (args) {\n\tvar r = args[0];\n\tvar g = args[1];\n\tvar b = args[2];\n\tvar value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization\n\n\tvalue = Math.round(value / 50);\n\n\tif (value === 0) {\n\t\treturn 30;\n\t}\n\n\tvar ansi = 30\n\t\t+ ((Math.round(b / 255) << 2)\n\t\t| (Math.round(g / 255) << 1)\n\t\t| Math.round(r / 255));\n\n\tif (value === 2) {\n\t\tansi += 60;\n\t}\n\n\treturn ansi;\n};\n\nconvert.hsv.ansi16 = function (args) {\n\t// optimization here; we already know the value and don't need to get\n\t// it converted for us.\n\treturn convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);\n};\n\nconvert.rgb.ansi256 = function (args) {\n\tvar r = args[0];\n\tvar g = args[1];\n\tvar b = args[2];\n\n\t// we use the extended greyscale palette here, with the exception of\n\t// black and white. normal palette only has 4 greyscale shades.\n\tif (r === g && g === b) {\n\t\tif (r < 8) {\n\t\t\treturn 16;\n\t\t}\n\n\t\tif (r > 248) {\n\t\t\treturn 231;\n\t\t}\n\n\t\treturn Math.round(((r - 8) / 247) * 24) + 232;\n\t}\n\n\tvar ansi = 16\n\t\t+ (36 * Math.round(r / 255 * 5))\n\t\t+ (6 * Math.round(g / 255 * 5))\n\t\t+ Math.round(b / 255 * 5);\n\n\treturn ansi;\n};\n\nconvert.ansi16.rgb = function (args) {\n\tvar color = args % 10;\n\n\t// handle greyscale\n\tif (color === 0 || color === 7) {\n\t\tif (args > 50) {\n\t\t\tcolor += 3.5;\n\t\t}\n\n\t\tcolor = color / 10.5 * 255;\n\n\t\treturn [color, color, color];\n\t}\n\n\tvar mult = (~~(args > 50) + 1) * 0.5;\n\tvar r = ((color & 1) * mult) * 255;\n\tvar g = (((color >> 1) & 1) * mult) * 255;\n\tvar b = (((color >> 2) & 1) * mult) * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.ansi256.rgb = function (args) {\n\t// handle greyscale\n\tif (args >= 232) {\n\t\tvar c = (args - 232) * 10 + 8;\n\t\treturn [c, c, c];\n\t}\n\n\targs -= 16;\n\n\tvar rem;\n\tvar r = Math.floor(args / 36) / 5 * 255;\n\tvar g = Math.floor((rem = args % 36) / 6) / 5 * 255;\n\tvar b = (rem % 6) / 5 * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hex = function (args) {\n\tvar integer = ((Math.round(args[0]) & 0xFF) << 16)\n\t\t+ ((Math.round(args[1]) & 0xFF) << 8)\n\t\t+ (Math.round(args[2]) & 0xFF);\n\n\tvar string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.hex.rgb = function (args) {\n\tvar match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);\n\tif (!match) {\n\t\treturn [0, 0, 0];\n\t}\n\n\tvar colorString = match[0];\n\n\tif (match[0].length === 3) {\n\t\tcolorString = colorString.split('').map(function (char) {\n\t\t\treturn char + char;\n\t\t}).join('');\n\t}\n\n\tvar integer = parseInt(colorString, 16);\n\tvar r = (integer >> 16) & 0xFF;\n\tvar g = (integer >> 8) & 0xFF;\n\tvar b = integer & 0xFF;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hcg = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar max = Math.max(Math.max(r, g), b);\n\tvar min = Math.min(Math.min(r, g), b);\n\tvar chroma = (max - min);\n\tvar grayscale;\n\tvar hue;\n\n\tif (chroma < 1) {\n\t\tgrayscale = min / (1 - chroma);\n\t} else {\n\t\tgrayscale = 0;\n\t}\n\n\tif (chroma <= 0) {\n\t\thue = 0;\n\t} else\n\tif (max === r) {\n\t\thue = ((g - b) / chroma) % 6;\n\t} else\n\tif (max === g) {\n\t\thue = 2 + (b - r) / chroma;\n\t} else {\n\t\thue = 4 + (r - g) / chroma + 4;\n\t}\n\n\thue /= 6;\n\thue %= 1;\n\n\treturn [hue * 360, chroma * 100, grayscale * 100];\n};\n\nconvert.hsl.hcg = function (hsl) {\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar c = 1;\n\tvar f = 0;\n\n\tif (l < 0.5) {\n\t\tc = 2.0 * s * l;\n\t} else {\n\t\tc = 2.0 * s * (1.0 - l);\n\t}\n\n\tif (c < 1.0) {\n\t\tf = (l - 0.5 * c) / (1.0 - c);\n\t}\n\n\treturn [hsl[0], c * 100, f * 100];\n};\n\nconvert.hsv.hcg = function (hsv) {\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\n\tvar c = s * v;\n\tvar f = 0;\n\n\tif (c < 1.0) {\n\t\tf = (v - c) / (1 - c);\n\t}\n\n\treturn [hsv[0], c * 100, f * 100];\n};\n\nconvert.hcg.rgb = function (hcg) {\n\tvar h = hcg[0] / 360;\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tif (c === 0.0) {\n\t\treturn [g * 255, g * 255, g * 255];\n\t}\n\n\tvar pure = [0, 0, 0];\n\tvar hi = (h % 1) * 6;\n\tvar v = hi % 1;\n\tvar w = 1 - v;\n\tvar mg = 0;\n\n\tswitch (Math.floor(hi)) {\n\t\tcase 0:\n\t\t\tpure[0] = 1; pure[1] = v; pure[2] = 0; break;\n\t\tcase 1:\n\t\t\tpure[0] = w; pure[1] = 1; pure[2] = 0; break;\n\t\tcase 2:\n\t\t\tpure[0] = 0; pure[1] = 1; pure[2] = v; break;\n\t\tcase 3:\n\t\t\tpure[0] = 0; pure[1] = w; pure[2] = 1; break;\n\t\tcase 4:\n\t\t\tpure[0] = v; pure[1] = 0; pure[2] = 1; break;\n\t\tdefault:\n\t\t\tpure[0] = 1; pure[1] = 0; pure[2] = w;\n\t}\n\n\tmg = (1.0 - c) * g;\n\n\treturn [\n\t\t(c * pure[0] + mg) * 255,\n\t\t(c * pure[1] + mg) * 255,\n\t\t(c * pure[2] + mg) * 255\n\t];\n};\n\nconvert.hcg.hsv = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tvar v = c + g * (1.0 - c);\n\tvar f = 0;\n\n\tif (v > 0.0) {\n\t\tf = c / v;\n\t}\n\n\treturn [hcg[0], f * 100, v * 100];\n};\n\nconvert.hcg.hsl = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tvar l = g * (1.0 - c) + 0.5 * c;\n\tvar s = 0;\n\n\tif (l > 0.0 && l < 0.5) {\n\t\ts = c / (2 * l);\n\t} else\n\tif (l >= 0.5 && l < 1.0) {\n\t\ts = c / (2 * (1 - l));\n\t}\n\n\treturn [hcg[0], s * 100, l * 100];\n};\n\nconvert.hcg.hwb = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\tvar v = c + g * (1.0 - c);\n\treturn [hcg[0], (v - c) * 100, (1 - v) * 100];\n};\n\nconvert.hwb.hcg = function (hwb) {\n\tvar w = hwb[1] / 100;\n\tvar b = hwb[2] / 100;\n\tvar v = 1 - b;\n\tvar c = v - w;\n\tvar g = 0;\n\n\tif (c < 1) {\n\t\tg = (v - c) / (1 - c);\n\t}\n\n\treturn [hwb[0], c * 100, g * 100];\n};\n\nconvert.apple.rgb = function (apple) {\n\treturn [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];\n};\n\nconvert.rgb.apple = function (rgb) {\n\treturn [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];\n};\n\nconvert.gray.rgb = function (args) {\n\treturn [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];\n};\n\nconvert.gray.hsl = convert.gray.hsv = function (args) {\n\treturn [0, 0, args[0]];\n};\n\nconvert.gray.hwb = function (gray) {\n\treturn [0, 100, gray[0]];\n};\n\nconvert.gray.cmyk = function (gray) {\n\treturn [0, 0, 0, gray[0]];\n};\n\nconvert.gray.lab = function (gray) {\n\treturn [gray[0], 0, 0];\n};\n\nconvert.gray.hex = function (gray) {\n\tvar val = Math.round(gray[0] / 100 * 255) & 0xFF;\n\tvar integer = (val << 16) + (val << 8) + val;\n\n\tvar string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.rgb.gray = function (rgb) {\n\tvar val = (rgb[0] + rgb[1] + rgb[2]) / 3;\n\treturn [val / 255 * 100];\n};\n","var conversions = require('./conversions');\n\n/*\n\tthis function routes a model to all other models.\n\n\tall functions that are routed have a property `.conversion` attached\n\tto the returned synthetic function. This property is an array\n\tof strings, each with the steps in between the 'from' and 'to'\n\tcolor models (inclusive).\n\n\tconversions that are not possible simply are not included.\n*/\n\nfunction buildGraph() {\n\tvar graph = {};\n\t// https://jsperf.com/object-keys-vs-for-in-with-closure/3\n\tvar models = Object.keys(conversions);\n\n\tfor (var len = models.length, i = 0; i < len; i++) {\n\t\tgraph[models[i]] = {\n\t\t\t// http://jsperf.com/1-vs-infinity\n\t\t\t// micro-opt, but this is simple.\n\t\t\tdistance: -1,\n\t\t\tparent: null\n\t\t};\n\t}\n\n\treturn graph;\n}\n\n// https://en.wikipedia.org/wiki/Breadth-first_search\nfunction deriveBFS(fromModel) {\n\tvar graph = buildGraph();\n\tvar queue = [fromModel]; // unshift -> queue -> pop\n\n\tgraph[fromModel].distance = 0;\n\n\twhile (queue.length) {\n\t\tvar current = queue.pop();\n\t\tvar adjacents = Object.keys(conversions[current]);\n\n\t\tfor (var len = adjacents.length, i = 0; i < len; i++) {\n\t\t\tvar adjacent = adjacents[i];\n\t\t\tvar node = graph[adjacent];\n\n\t\t\tif (node.distance === -1) {\n\t\t\t\tnode.distance = graph[current].distance + 1;\n\t\t\t\tnode.parent = current;\n\t\t\t\tqueue.unshift(adjacent);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn graph;\n}\n\nfunction link(from, to) {\n\treturn function (args) {\n\t\treturn to(from(args));\n\t};\n}\n\nfunction wrapConversion(toModel, graph) {\n\tvar path = [graph[toModel].parent, toModel];\n\tvar fn = conversions[graph[toModel].parent][toModel];\n\n\tvar cur = graph[toModel].parent;\n\twhile (graph[cur].parent) {\n\t\tpath.unshift(graph[cur].parent);\n\t\tfn = link(conversions[graph[cur].parent][cur], fn);\n\t\tcur = graph[cur].parent;\n\t}\n\n\tfn.conversion = path;\n\treturn fn;\n}\n\nmodule.exports = function (fromModel) {\n\tvar graph = deriveBFS(fromModel);\n\tvar conversion = {};\n\n\tvar models = Object.keys(graph);\n\tfor (var len = models.length, i = 0; i < len; i++) {\n\t\tvar toModel = models[i];\n\t\tvar node = graph[toModel];\n\n\t\tif (node.parent === null) {\n\t\t\t// no possible conversion, or this node is the source model.\n\t\t\tcontinue;\n\t\t}\n\n\t\tconversion[toModel] = wrapConversion(toModel, graph);\n\t}\n\n\treturn conversion;\n};\n\n","var conversions = require('./conversions');\nvar route = require('./route');\n\nvar convert = {};\n\nvar models = Object.keys(conversions);\n\nfunction wrapRaw(fn) {\n\tvar wrappedFn = function (args) {\n\t\tif (args === undefined || args === null) {\n\t\t\treturn args;\n\t\t}\n\n\t\tif (arguments.length > 1) {\n\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t}\n\n\t\treturn fn(args);\n\t};\n\n\t// preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nfunction wrapRounded(fn) {\n\tvar wrappedFn = function (args) {\n\t\tif (args === undefined || args === null) {\n\t\t\treturn args;\n\t\t}\n\n\t\tif (arguments.length > 1) {\n\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t}\n\n\t\tvar result = fn(args);\n\n\t\t// we're assuming the result is an array here.\n\t\t// see notice in conversions.js; don't use box types\n\t\t// in conversion functions.\n\t\tif (typeof result === 'object') {\n\t\t\tfor (var len = result.length, i = 0; i < len; i++) {\n\t\t\t\tresult[i] = Math.round(result[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t};\n\n\t// preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nmodels.forEach(function (fromModel) {\n\tconvert[fromModel] = {};\n\n\tObject.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});\n\tObject.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});\n\n\tvar routes = route(fromModel);\n\tvar routeModels = Object.keys(routes);\n\n\trouteModels.forEach(function (toModel) {\n\t\tvar fn = routes[toModel];\n\n\t\tconvert[fromModel][toModel] = wrapRounded(fn);\n\t\tconvert[fromModel][toModel].raw = wrapRaw(fn);\n\t});\n});\n\nmodule.exports = convert;\n","'use strict';\nconst colorConvert = require('color-convert');\n\nconst wrapAnsi16 = (fn, offset) => function () {\n\tconst code = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${code + offset}m`;\n};\n\nconst wrapAnsi256 = (fn, offset) => function () {\n\tconst code = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${38 + offset};5;${code}m`;\n};\n\nconst wrapAnsi16m = (fn, offset) => function () {\n\tconst rgb = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;\n};\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\tconst styles = {\n\t\tmodifier: {\n\t\t\treset: [0, 0],\n\t\t\t// 21 isn't widely supported and 22 does the same thing\n\t\t\tbold: [1, 22],\n\t\t\tdim: [2, 22],\n\t\t\titalic: [3, 23],\n\t\t\tunderline: [4, 24],\n\t\t\tinverse: [7, 27],\n\t\t\thidden: [8, 28],\n\t\t\tstrikethrough: [9, 29]\n\t\t},\n\t\tcolor: {\n\t\t\tblack: [30, 39],\n\t\t\tred: [31, 39],\n\t\t\tgreen: [32, 39],\n\t\t\tyellow: [33, 39],\n\t\t\tblue: [34, 39],\n\t\t\tmagenta: [35, 39],\n\t\t\tcyan: [36, 39],\n\t\t\twhite: [37, 39],\n\t\t\tgray: [90, 39],\n\n\t\t\t// Bright color\n\t\t\tredBright: [91, 39],\n\t\t\tgreenBright: [92, 39],\n\t\t\tyellowBright: [93, 39],\n\t\t\tblueBright: [94, 39],\n\t\t\tmagentaBright: [95, 39],\n\t\t\tcyanBright: [96, 39],\n\t\t\twhiteBright: [97, 39]\n\t\t},\n\t\tbgColor: {\n\t\t\tbgBlack: [40, 49],\n\t\t\tbgRed: [41, 49],\n\t\t\tbgGreen: [42, 49],\n\t\t\tbgYellow: [43, 49],\n\t\t\tbgBlue: [44, 49],\n\t\t\tbgMagenta: [45, 49],\n\t\t\tbgCyan: [46, 49],\n\t\t\tbgWhite: [47, 49],\n\n\t\t\t// Bright color\n\t\t\tbgBlackBright: [100, 49],\n\t\t\tbgRedBright: [101, 49],\n\t\t\tbgGreenBright: [102, 49],\n\t\t\tbgYellowBright: [103, 49],\n\t\t\tbgBlueBright: [104, 49],\n\t\t\tbgMagentaBright: [105, 49],\n\t\t\tbgCyanBright: [106, 49],\n\t\t\tbgWhiteBright: [107, 49]\n\t\t}\n\t};\n\n\t// Fix humans\n\tstyles.color.grey = styles.color.gray;\n\n\tfor (const groupName of Object.keys(styles)) {\n\t\tconst group = styles[groupName];\n\n\t\tfor (const styleName of Object.keys(group)) {\n\t\t\tconst style = group[styleName];\n\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false\n\t\t});\n\n\t\tObject.defineProperty(styles, 'codes', {\n\t\t\tvalue: codes,\n\t\t\tenumerable: false\n\t\t});\n\t}\n\n\tconst ansi2ansi = n => n;\n\tconst rgb2rgb = (r, g, b) => [r, g, b];\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = {\n\t\tansi: wrapAnsi16(ansi2ansi, 0)\n\t};\n\tstyles.color.ansi256 = {\n\t\tansi256: wrapAnsi256(ansi2ansi, 0)\n\t};\n\tstyles.color.ansi16m = {\n\t\trgb: wrapAnsi16m(rgb2rgb, 0)\n\t};\n\n\tstyles.bgColor.ansi = {\n\t\tansi: wrapAnsi16(ansi2ansi, 10)\n\t};\n\tstyles.bgColor.ansi256 = {\n\t\tansi256: wrapAnsi256(ansi2ansi, 10)\n\t};\n\tstyles.bgColor.ansi16m = {\n\t\trgb: wrapAnsi16m(rgb2rgb, 10)\n\t};\n\n\tfor (let key of Object.keys(colorConvert)) {\n\t\tif (typeof colorConvert[key] !== 'object') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst suite = colorConvert[key];\n\n\t\tif (key === 'ansi16') {\n\t\t\tkey = 'ansi';\n\t\t}\n\n\t\tif ('ansi16' in suite) {\n\t\t\tstyles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);\n\t\t\tstyles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);\n\t\t}\n\n\t\tif ('ansi256' in suite) {\n\t\t\tstyles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);\n\t\t\tstyles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);\n\t\t}\n\n\t\tif ('rgb' in suite) {\n\t\t\tstyles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);\n\t\t\tstyles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);\n\t\t}\n\t}\n\n\treturn styles;\n}\n\n// Make the export immutable\nObject.defineProperty(module, 'exports', {\n\tenumerable: true,\n\tget: assembleStyles\n});\n","'use strict';\nmodule.exports = (flag, argv) => {\n\targv = argv || process.argv;\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst pos = argv.indexOf(prefix + flag);\n\tconst terminatorPos = argv.indexOf('--');\n\treturn pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);\n};\n","'use strict';\nconst os = require('os');\nconst hasFlag = require('has-flag');\n\nconst env = process.env;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false')) {\n\tforceColor = false;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = true;\n}\nif ('FORCE_COLOR' in env) {\n\tforceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(stream) {\n\tif (forceColor === false) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (stream && !stream.isTTY && forceColor !== true) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor ? 1 : 0;\n\n\tif (process.platform === 'win32') {\n\t\t// Node.js 7.5.0 is the first version of Node.js to include a patch to\n\t\t// libuv that enables 256 color output on Windows. Anything earlier and it\n\t\t// won't work. However, here we target Node.js 8 at minimum as it is an LTS\n\t\t// release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows\n\t\t// release that supports 256 colors. Windows 10 build 14931 is the first release\n\t\t// that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(process.versions.node.split('.')[0]) >= 8 &&\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: getSupportLevel(process.stdout),\n\tstderr: getSupportLevel(process.stderr)\n};\n","'use strict';\nconst TEMPLATE_REGEX = /(?:\\\\(u[a-f\\d]{4}|x[a-f\\d]{2}|.))|(?:\\{(~)?(\\w+(?:\\([^)]*\\))?(?:\\.\\w+(?:\\([^)]*\\))?)*)(?:[ \\t]|(?=\\r?\\n)))|(\\})|((?:.|[\\r\\n\\f])+?)/gi;\nconst STYLE_REGEX = /(?:^|\\.)(\\w+)(?:\\(([^)]*)\\))?/g;\nconst STRING_REGEX = /^(['\"])((?:\\\\.|(?!\\1)[^\\\\])*)\\1$/;\nconst ESCAPE_REGEX = /\\\\(u[a-f\\d]{4}|x[a-f\\d]{2}|.)|([^\\\\])/gi;\n\nconst ESCAPES = new Map([\n\t['n', '\\n'],\n\t['r', '\\r'],\n\t['t', '\\t'],\n\t['b', '\\b'],\n\t['f', '\\f'],\n\t['v', '\\v'],\n\t['0', '\\0'],\n\t['\\\\', '\\\\'],\n\t['e', '\\u001B'],\n\t['a', '\\u0007']\n]);\n\nfunction unescape(c) {\n\tif ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {\n\t\treturn String.fromCharCode(parseInt(c.slice(1), 16));\n\t}\n\n\treturn ESCAPES.get(c) || c;\n}\n\nfunction parseArguments(name, args) {\n\tconst results = [];\n\tconst chunks = args.trim().split(/\\s*,\\s*/g);\n\tlet matches;\n\n\tfor (const chunk of chunks) {\n\t\tif (!isNaN(chunk)) {\n\t\t\tresults.push(Number(chunk));\n\t\t} else if ((matches = chunk.match(STRING_REGEX))) {\n\t\t\tresults.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));\n\t\t} else {\n\t\t\tthrow new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nfunction parseStyle(style) {\n\tSTYLE_REGEX.lastIndex = 0;\n\n\tconst results = [];\n\tlet matches;\n\n\twhile ((matches = STYLE_REGEX.exec(style)) !== null) {\n\t\tconst name = matches[1];\n\n\t\tif (matches[2]) {\n\t\t\tconst args = parseArguments(name, matches[2]);\n\t\t\tresults.push([name].concat(args));\n\t\t} else {\n\t\t\tresults.push([name]);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nfunction buildStyle(chalk, styles) {\n\tconst enabled = {};\n\n\tfor (const layer of styles) {\n\t\tfor (const style of layer.styles) {\n\t\t\tenabled[style[0]] = layer.inverse ? null : style.slice(1);\n\t\t}\n\t}\n\n\tlet current = chalk;\n\tfor (const styleName of Object.keys(enabled)) {\n\t\tif (Array.isArray(enabled[styleName])) {\n\t\t\tif (!(styleName in current)) {\n\t\t\t\tthrow new Error(`Unknown Chalk style: ${styleName}`);\n\t\t\t}\n\n\t\t\tif (enabled[styleName].length > 0) {\n\t\t\t\tcurrent = current[styleName].apply(current, enabled[styleName]);\n\t\t\t} else {\n\t\t\t\tcurrent = current[styleName];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn current;\n}\n\nmodule.exports = (chalk, tmp) => {\n\tconst styles = [];\n\tconst chunks = [];\n\tlet chunk = [];\n\n\t// eslint-disable-next-line max-params\n\ttmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {\n\t\tif (escapeChar) {\n\t\t\tchunk.push(unescape(escapeChar));\n\t\t} else if (style) {\n\t\t\tconst str = chunk.join('');\n\t\t\tchunk = [];\n\t\t\tchunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));\n\t\t\tstyles.push({inverse, styles: parseStyle(style)});\n\t\t} else if (close) {\n\t\t\tif (styles.length === 0) {\n\t\t\t\tthrow new Error('Found extraneous } in Chalk template literal');\n\t\t\t}\n\n\t\t\tchunks.push(buildStyle(chalk, styles)(chunk.join('')));\n\t\t\tchunk = [];\n\t\t\tstyles.pop();\n\t\t} else {\n\t\t\tchunk.push(chr);\n\t\t}\n\t});\n\n\tchunks.push(chunk.join(''));\n\n\tif (styles.length > 0) {\n\t\tconst errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\\`}\\`)`;\n\t\tthrow new Error(errMsg);\n\t}\n\n\treturn chunks.join('');\n};\n","'use strict';\nconst escapeStringRegexp = require('escape-string-regexp');\nconst ansiStyles = require('ansi-styles');\nconst stdoutColor = require('supports-color').stdout;\n\nconst template = require('./templates.js');\n\nconst isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');\n\n// `supportsColor.level` → `ansiStyles.color[name]` mapping\nconst levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];\n\n// `color-convert` models to exclude from the Chalk API due to conflicts and such\nconst skipModels = new Set(['gray']);\n\nconst styles = Object.create(null);\n\nfunction applyOptions(obj, options) {\n\toptions = options || {};\n\n\t// Detect level if not set manually\n\tconst scLevel = stdoutColor ? stdoutColor.level : 0;\n\tobj.level = options.level === undefined ? scLevel : options.level;\n\tobj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;\n}\n\nfunction Chalk(options) {\n\t// We check for this.template here since calling `chalk.constructor()`\n\t// by itself will have a `this` of a previously constructed chalk object\n\tif (!this || !(this instanceof Chalk) || this.template) {\n\t\tconst chalk = {};\n\t\tapplyOptions(chalk, options);\n\n\t\tchalk.template = function () {\n\t\t\tconst args = [].slice.call(arguments);\n\t\t\treturn chalkTag.apply(null, [chalk.template].concat(args));\n\t\t};\n\n\t\tObject.setPrototypeOf(chalk, Chalk.prototype);\n\t\tObject.setPrototypeOf(chalk.template, chalk);\n\n\t\tchalk.template.constructor = Chalk;\n\n\t\treturn chalk.template;\n\t}\n\n\tapplyOptions(this, options);\n}\n\n// Use bright blue on Windows as the normal blue color is illegible\nif (isSimpleWindowsTerm) {\n\tansiStyles.blue.open = '\\u001B[94m';\n}\n\nfor (const key of Object.keys(ansiStyles)) {\n\tansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');\n\n\tstyles[key] = {\n\t\tget() {\n\t\t\tconst codes = ansiStyles[key];\n\t\t\treturn build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);\n\t\t}\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\treturn build.call(this, this._styles || [], true, 'visible');\n\t}\n};\n\nansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');\nfor (const model of Object.keys(ansiStyles.color.ansi)) {\n\tif (skipModels.has(model)) {\n\t\tcontinue;\n\t}\n\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst level = this.level;\n\t\t\treturn function () {\n\t\t\t\tconst open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);\n\t\t\t\tconst codes = {\n\t\t\t\t\topen,\n\t\t\t\t\tclose: ansiStyles.color.close,\n\t\t\t\t\tcloseRe: ansiStyles.color.closeRe\n\t\t\t\t};\n\t\t\t\treturn build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);\n\t\t\t};\n\t\t}\n\t};\n}\n\nansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');\nfor (const model of Object.keys(ansiStyles.bgColor.ansi)) {\n\tif (skipModels.has(model)) {\n\t\tcontinue;\n\t}\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst level = this.level;\n\t\t\treturn function () {\n\t\t\t\tconst open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);\n\t\t\t\tconst codes = {\n\t\t\t\t\topen,\n\t\t\t\t\tclose: ansiStyles.bgColor.close,\n\t\t\t\t\tcloseRe: ansiStyles.bgColor.closeRe\n\t\t\t\t};\n\t\t\t\treturn build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);\n\t\t\t};\n\t\t}\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, styles);\n\nfunction build(_styles, _empty, key) {\n\tconst builder = function () {\n\t\treturn applyStyle.apply(builder, arguments);\n\t};\n\n\tbuilder._styles = _styles;\n\tbuilder._empty = _empty;\n\n\tconst self = this;\n\n\tObject.defineProperty(builder, 'level', {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn self.level;\n\t\t},\n\t\tset(level) {\n\t\t\tself.level = level;\n\t\t}\n\t});\n\n\tObject.defineProperty(builder, 'enabled', {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn self.enabled;\n\t\t},\n\t\tset(enabled) {\n\t\t\tself.enabled = enabled;\n\t\t}\n\t});\n\n\t// See below for fix regarding invisible grey/dim combination on Windows\n\tbuilder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';\n\n\t// `__proto__` is used because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tbuilder.__proto__ = proto; // eslint-disable-line no-proto\n\n\treturn builder;\n}\n\nfunction applyStyle() {\n\t// Support varags, but simply cast to string in case there's only one arg\n\tconst args = arguments;\n\tconst argsLen = args.length;\n\tlet str = String(arguments[0]);\n\n\tif (argsLen === 0) {\n\t\treturn '';\n\t}\n\n\tif (argsLen > 1) {\n\t\t// Don't slice `arguments`, it prevents V8 optimizations\n\t\tfor (let a = 1; a < argsLen; a++) {\n\t\t\tstr += ' ' + args[a];\n\t\t}\n\t}\n\n\tif (!this.enabled || this.level <= 0 || !str) {\n\t\treturn this._empty ? '' : str;\n\t}\n\n\t// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,\n\t// see https://github.com/chalk/chalk/issues/58\n\t// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.\n\tconst originalDim = ansiStyles.dim.open;\n\tif (isSimpleWindowsTerm && this.hasGrey) {\n\t\tansiStyles.dim.open = '';\n\t}\n\n\tfor (const code of this._styles.slice().reverse()) {\n\t\t// Replace any instances already present with a re-opening code\n\t\t// otherwise only the part of the string until said closing code\n\t\t// will be colored, and the rest will simply be 'plain'.\n\t\tstr = code.open + str.replace(code.closeRe, code.open) + code.close;\n\n\t\t// Close the styling before a linebreak and reopen\n\t\t// after next line to fix a bleed issue on macOS\n\t\t// https://github.com/chalk/chalk/pull/92\n\t\tstr = str.replace(/\\r?\\n/g, `${code.close}$&${code.open}`);\n\t}\n\n\t// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue\n\tansiStyles.dim.open = originalDim;\n\n\treturn str;\n}\n\nfunction chalkTag(chalk, strings) {\n\tif (!Array.isArray(strings)) {\n\t\t// If chalk() was called by itself or with a string,\n\t\t// return the string itself as a string.\n\t\treturn [].slice.call(arguments, 1).join(' ');\n\t}\n\n\tconst args = [].slice.call(arguments, 2);\n\tconst parts = [strings.raw[0]];\n\n\tfor (let i = 1; i < strings.length; i++) {\n\t\tparts.push(String(args[i - 1]).replace(/[{}\\\\]/g, '\\\\$&'));\n\t\tparts.push(String(strings.raw[i]));\n\t}\n\n\treturn template(chalk, parts.join(''));\n}\n\nObject.defineProperties(Chalk.prototype, styles);\n\nmodule.exports = Chalk(); // eslint-disable-line new-cap\nmodule.exports.supportsColor = stdoutColor;\nmodule.exports.default = module.exports; // For TypeScript\n","exports.quote = function (xs) {\n return xs.map(function (s) {\n if (s && typeof s === 'object') {\n return s.op.replace(/(.)/g, '\\\\$1');\n }\n else if (/[\"\\s]/.test(s) && !/'/.test(s)) {\n return \"'\" + s.replace(/(['\\\\])/g, '\\\\$1') + \"'\";\n }\n else if (/[\"'\\s]/.test(s)) {\n return '\"' + s.replace(/([\"\\\\$`!])/g, '\\\\$1') + '\"';\n }\n else {\n return String(s).replace(/([A-z]:)?([#!\"$&'()*,:;<=>?@\\[\\\\\\]^`{|}])/g, '$1\\\\$2');\n }\n }).join(' ');\n};\n\n// '<(' is process substitution operator and\n// can be parsed the same as control operator\nvar CONTROL = '(?:' + [\n '\\\\|\\\\|', '\\\\&\\\\&', ';;', '\\\\|\\\\&', '\\\\<\\\\(', '>>', '>\\\\&', '[&;()|<>]'\n].join('|') + ')';\nvar META = '|&;()<> \\\\t';\nvar BAREWORD = '(\\\\\\\\[\\'\"' + META + ']|[^\\\\s\\'\"' + META + '])+';\nvar SINGLE_QUOTE = '\"((\\\\\\\\\"|[^\"])*?)\"';\nvar DOUBLE_QUOTE = '\\'((\\\\\\\\\\'|[^\\'])*?)\\'';\n\nvar TOKEN = '';\nfor (var i = 0; i < 4; i++) {\n TOKEN += (Math.pow(16,8)*Math.random()).toString(16);\n}\n\nexports.parse = function (s, env, opts) {\n var mapped = parse(s, env, opts);\n if (typeof env !== 'function') return mapped;\n return mapped.reduce(function (acc, s) {\n if (typeof s === 'object') return acc.concat(s);\n var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));\n if (xs.length === 1) return acc.concat(xs[0]);\n return acc.concat(xs.filter(Boolean).map(function (x) {\n if (RegExp('^' + TOKEN).test(x)) {\n return JSON.parse(x.split(TOKEN)[1]);\n }\n else return x;\n }));\n }, []);\n};\n\nfunction parse (s, env, opts) {\n var chunker = new RegExp([\n '(' + CONTROL + ')', // control chars\n '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*'\n ].join('|'), 'g');\n var match = s.match(chunker).filter(Boolean);\n var commented = false;\n\n if (!match) return [];\n if (!env) env = {};\n if (!opts) opts = {};\n return match.map(function (s, j) {\n if (commented) {\n return;\n }\n if (RegExp('^' + CONTROL + '$').test(s)) {\n return { op: s };\n }\n\n // Hand-written scanner/parser for Bash quoting rules:\n //\n // 1. inside single quotes, all characters are printed literally.\n // 2. inside double quotes, all characters are printed literally\n // except variables prefixed by '$' and backslashes followed by\n // either a double quote or another backslash.\n // 3. outside of any quotes, backslashes are treated as escape\n // characters and not printed (unless they are themselves escaped)\n // 4. quote context can switch mid-token if there is no whitespace\n // between the two quote contexts (e.g. all'one'\"token\" parses as\n // \"allonetoken\")\n var SQ = \"'\";\n var DQ = '\"';\n var DS = '$';\n var BS = opts.escape || '\\\\';\n var quote = false;\n var esc = false;\n var out = '';\n var isGlob = false;\n\n for (var i = 0, len = s.length; i < len; i++) {\n var c = s.charAt(i);\n isGlob = isGlob || (!quote && (c === '*' || c === '?'));\n if (esc) {\n out += c;\n esc = false;\n }\n else if (quote) {\n if (c === quote) {\n quote = false;\n }\n else if (quote == SQ) {\n out += c;\n }\n else { // Double quote\n if (c === BS) {\n i += 1;\n c = s.charAt(i);\n if (c === DQ || c === BS || c === DS) {\n out += c;\n } else {\n out += BS + c;\n }\n }\n else if (c === DS) {\n out += parseEnvVar();\n }\n else {\n out += c;\n }\n }\n }\n else if (c === DQ || c === SQ) {\n quote = c;\n }\n else if (RegExp('^' + CONTROL + '$').test(c)) {\n return { op: s };\n }\n else if (RegExp('^#$').test(c)) {\n commented = true;\n if (out.length){\n return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }];\n }\n return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }];\n }\n else if (c === BS) {\n esc = true;\n }\n else if (c === DS) {\n out += parseEnvVar();\n }\n else out += c;\n }\n\n if (isGlob) return {op: 'glob', pattern: out};\n\n return out;\n\n function parseEnvVar() {\n i += 1;\n var varend, varname;\n //debugger\n if (s.charAt(i) === '{') {\n i += 1;\n if (s.charAt(i) === '}') {\n throw new Error(\"Bad substitution: \" + s.substr(i - 2, 3));\n }\n varend = s.indexOf('}', i);\n if (varend < 0) {\n throw new Error(\"Bad substitution: \" + s.substr(i));\n }\n varname = s.substr(i, varend - i);\n i = varend;\n }\n else if (/[*@#?$!_\\-]/.test(s.charAt(i))) {\n varname = s.charAt(i);\n i += 1;\n }\n else {\n varend = s.substr(i).match(/[^\\w\\d_]/);\n if (!varend) {\n varname = s.substr(i);\n i = s.length;\n } else {\n varname = s.substr(i, varend.index);\n i += varend.index - 1;\n }\n }\n return getVar(null, '', varname);\n }\n })\n // finalize parsed aruments\n .reduce(function(prev, arg){\n if (arg === undefined){\n return prev;\n }\n return prev.concat(arg);\n },[]);\n\n function getVar (_, pre, key) {\n var r = typeof env === 'function' ? env(key) : env[key];\n if (r === undefined && key != '')\n r = '';\n else if (r === undefined)\n r = '$';\n\n if (typeof r === 'object') {\n return pre + TOKEN + JSON.stringify(r) + TOKEN;\n }\n else return pre + r;\n }\n}\n","module.exports = {\n '/Applications/Atom.app/Contents/MacOS/Atom': 'atom',\n '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':\n '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',\n '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',\n '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':\n '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',\n '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':\n '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',\n '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text':\n '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl',\n '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',\n '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron':\n 'code-insiders',\n '/Applications/AppCode.app/Contents/MacOS/appcode':\n '/Applications/AppCode.app/Contents/MacOS/appcode',\n '/Applications/CLion.app/Contents/MacOS/clion':\n '/Applications/CLion.app/Contents/MacOS/clion',\n '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea':\n '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',\n '/Applications/PhpStorm.app/Contents/MacOS/phpstorm':\n '/Applications/PhpStorm.app/Contents/MacOS/phpstorm',\n '/Applications/PyCharm.app/Contents/MacOS/pycharm':\n '/Applications/PyCharm.app/Contents/MacOS/pycharm',\n '/Applications/PyCharm CE.app/Contents/MacOS/pycharm':\n '/Applications/PyCharm CE.app/Contents/MacOS/pycharm',\n '/Applications/RubyMine.app/Contents/MacOS/rubymine':\n '/Applications/RubyMine.app/Contents/MacOS/rubymine',\n '/Applications/WebStorm.app/Contents/MacOS/webstorm':\n '/Applications/WebStorm.app/Contents/MacOS/webstorm'\n}\n","module.exports = {\n atom: 'atom',\n Brackets: 'brackets',\n code: 'code',\n emacs: 'emacs',\n 'idea.sh': 'idea',\n 'phpstorm.sh': 'phpstorm',\n 'pycharm.sh': 'pycharm',\n 'rubymine.sh': 'rubymine',\n sublime_text: 'subl',\n vim: 'vim',\n 'webstorm.sh': 'webstorm'\n}\n","module.exports = [\n 'Brackets.exe',\n 'Code.exe',\n 'atom.exe',\n 'sublime_text.exe',\n 'notepad++.exe',\n 'clion.exe',\n 'clion64.exe',\n 'idea.exe',\n 'idea64.exe',\n 'phpstorm.exe',\n 'phpstorm64.exe',\n 'pycharm.exe',\n 'pycharm64.exe',\n 'rubymine.exe',\n 'rubymine64.exe',\n 'webstorm.exe',\n 'webstorm64.exe'\n]\n","const path = require('path')\nconst shellQuote = require('shell-quote')\nconst childProcess = require('child_process')\n\n// Map from full process name to binary that starts the process\n// We can't just re-use full process name, because it will spawn a new instance\n// of the app every time\nconst COMMON_EDITORS_OSX = require('./editor-info/osx')\nconst COMMON_EDITORS_LINUX = require('./editor-info/linux')\nconst COMMON_EDITORS_WIN = require('./editor-info/windows')\n\nmodule.exports = function guessEditor (specifiedEditor) {\n if (specifiedEditor) {\n return shellQuote.parse(specifiedEditor)\n }\n // We can find out which editor is currently running by:\n // `ps x` on macOS and Linux\n // `Get-Process` on Windows\n try {\n if (process.platform === 'darwin') {\n const output = childProcess.execSync('ps x').toString()\n const processNames = Object.keys(COMMON_EDITORS_OSX)\n for (let i = 0; i < processNames.length; i++) {\n const processName = processNames[i]\n if (output.indexOf(processName) !== -1) {\n return [COMMON_EDITORS_OSX[processName]]\n }\n }\n } else if (process.platform === 'win32') {\n const output = childProcess\n .execSync('powershell -Command \"Get-Process | Select-Object Path\"', {\n stdio: ['pipe', 'pipe', 'ignore']\n })\n .toString()\n const runningProcesses = output.split('\\r\\n')\n for (let i = 0; i < runningProcesses.length; i++) {\n // `Get-Process` sometimes returns empty lines\n if (!runningProcesses[i]) {\n continue\n }\n\n const fullProcessPath = runningProcesses[i].trim()\n const shortProcessName = path.basename(fullProcessPath)\n\n if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {\n return [fullProcessPath]\n }\n }\n } else if (process.platform === 'linux') {\n // --no-heading No header line\n // x List all processes owned by you\n // -o comm Need only names column\n const output = childProcess\n .execSync('ps x --no-heading -o comm --sort=comm')\n .toString()\n const processNames = Object.keys(COMMON_EDITORS_LINUX)\n for (let i = 0; i < processNames.length; i++) {\n const processName = processNames[i]\n if (output.indexOf(processName) !== -1) {\n return [COMMON_EDITORS_LINUX[processName]]\n }\n }\n }\n } catch (error) {\n // Ignore...\n }\n\n // Last resort, use old skool env vars\n if (process.env.VISUAL) {\n return [process.env.VISUAL]\n } else if (process.env.EDITOR) {\n return [process.env.EDITOR]\n }\n\n return [null]\n}\n","const path = require('path')\n\n// normalize file/line numbers into command line args for specific editors\nmodule.exports = function getArgumentsForPosition (\n editor,\n fileName,\n lineNumber,\n columnNumber = 1\n) {\n const editorBasename = path.basename(editor).replace(/\\.(exe|cmd|bat)$/i, '')\n switch (editorBasename) {\n case 'atom':\n case 'Atom':\n case 'Atom Beta':\n case 'subl':\n case 'sublime':\n case 'sublime_text':\n case 'wstorm':\n case 'charm':\n return [`${fileName}:${lineNumber}:${columnNumber}`]\n case 'notepad++':\n return ['-n' + lineNumber, fileName]\n case 'vim':\n case 'mvim':\n return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName]\n case 'joe':\n return ['+' + `${lineNumber}`, fileName]\n case 'emacs':\n case 'emacsclient':\n return [`+${lineNumber}:${columnNumber}`, fileName]\n case 'rmate':\n case 'mate':\n case 'mine':\n return ['--line', lineNumber, fileName]\n case 'code':\n case 'code-insiders':\n case 'Code':\n return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`]\n case 'appcode':\n case 'clion':\n case 'clion64':\n case 'idea':\n case 'idea64':\n case 'phpstorm':\n case 'phpstorm64':\n case 'pycharm':\n case 'pycharm64':\n case 'rubymine':\n case 'rubymine64':\n case 'webstorm':\n case 'webstorm64':\n return ['--line', lineNumber, fileName]\n }\n\n // For all others, drop the lineNumber until we have\n // a mapping above, since providing the lineNumber incorrectly\n // can result in errors or confusing behavior.\n return [fileName]\n}\n","/**\n * Copyright (c) 2015-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file at\n * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE\n *\n * Modified by Yuxi Evan You\n */\n\nconst fs = require('fs')\nconst os = require('os')\nconst path = require('path')\nconst chalk = require('chalk')\nconst childProcess = require('child_process')\n\nconst guessEditor = require('./guess')\nconst getArgumentsForPosition = require('./get-args')\n\nfunction wrapErrorCallback (cb) {\n return (fileName, errorMessage) => {\n console.log()\n console.log(\n chalk.red('Could not open ' + path.basename(fileName) + ' in the editor.')\n )\n if (errorMessage) {\n if (errorMessage[errorMessage.length - 1] !== '.') {\n errorMessage += '.'\n }\n console.log(\n chalk.red('The editor process exited with an error: ' + errorMessage)\n )\n }\n console.log()\n if (cb) cb(fileName, errorMessage)\n }\n}\n\nfunction isTerminalEditor (editor) {\n switch (editor) {\n case 'vim':\n case 'emacs':\n case 'nano':\n return true\n }\n return false\n}\n\nconst positionRE = /:(\\d+)(:(\\d+))?$/\nfunction parseFile (file) {\n const fileName = file.replace(positionRE, '')\n const match = file.match(positionRE)\n const lineNumber = match && match[1]\n const columnNumber = match && match[3]\n return {\n fileName,\n lineNumber,\n columnNumber\n }\n}\n\nlet _childProcess = null\n\nfunction launchEditor (file, specifiedEditor, onErrorCallback) {\n const parsed = parseFile(file)\n let { fileName } = parsed\n const { lineNumber, columnNumber } = parsed\n\n if (!fs.existsSync(fileName)) {\n return\n }\n\n if (typeof specifiedEditor === 'function') {\n onErrorCallback = specifiedEditor\n specifiedEditor = undefined\n }\n\n onErrorCallback = wrapErrorCallback(onErrorCallback)\n\n const [editor, ...args] = guessEditor(specifiedEditor)\n if (!editor) {\n onErrorCallback(fileName, null)\n return\n }\n\n if (\n process.platform === 'linux' &&\n fileName.startsWith('/mnt/') &&\n /Microsoft/i.test(os.release())\n ) {\n // Assume WSL / \"Bash on Ubuntu on Windows\" is being used, and\n // that the file exists on the Windows file system.\n // `os.release()` is \"4.4.0-43-Microsoft\" in the current release\n // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364\n // When a Windows editor is specified, interop functionality can\n // handle the path translation, but only if a relative path is used.\n fileName = path.relative('', fileName)\n }\n\n if (lineNumber) {\n const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber)\n args.push.apply(args, extraArgs)\n } else {\n args.push(fileName)\n }\n\n if (_childProcess && isTerminalEditor(editor)) {\n // There's an existing editor process already and it's attached\n // to the terminal, so go kill it. Otherwise two separate editor\n // instances attach to the stdin/stdout which gets confusing.\n _childProcess.kill('SIGKILL')\n }\n\n if (process.platform === 'win32') {\n // On Windows, launch the editor in a shell because spawn can only\n // launch .exe files.\n _childProcess = childProcess.spawn(\n 'cmd.exe',\n ['/C', editor].concat(args),\n { stdio: 'inherit' }\n )\n } else {\n _childProcess = childProcess.spawn(editor, args, { stdio: 'inherit' })\n }\n _childProcess.on('exit', function (errorCode) {\n _childProcess = null\n\n if (errorCode) {\n onErrorCallback(fileName, '(code ' + errorCode + ')')\n }\n })\n\n _childProcess.on('error', function (error) {\n onErrorCallback(fileName, error.message)\n })\n}\n\nmodule.exports = launchEditor\n","const url = require('url')\nconst path = require('path')\nconst launch = require('launch-editor')\n\nmodule.exports = (specifiedEditor, srcRoot, onErrorCallback) => {\n if (typeof specifiedEditor === 'function') {\n onErrorCallback = specifiedEditor\n specifiedEditor = undefined\n }\n\n if (typeof srcRoot === 'function') {\n onErrorCallback = srcRoot\n srcRoot = undefined\n }\n\n srcRoot = srcRoot || process.cwd()\n\n return function launchEditorMiddleware (req, res, next) {\n const { file } = url.parse(req.url, true).query || {}\n if (!file) {\n res.statusCode = 500\n res.end(`launch-editor-middleware: required query param \"file\" is missing.`)\n } else {\n launch(path.resolve(srcRoot, file), specifiedEditor, onErrorCallback)\n res.end()\n }\n }\n}\n","import path from 'path'\nimport { Loader, Plugin, ImportKind } from 'esbuild'\nimport { KNOWN_ASSET_TYPES } from '../constants'\nimport { ResolvedConfig } from '..'\nimport {\n isRunningWithYarnPnp,\n flattenId,\n normalizePath,\n isExternalUrl\n} from '../utils'\nimport { browserExternalId } from '../plugins/resolve'\nimport { ExportsData } from '.'\n\nconst externalTypes = [\n 'css',\n // supported pre-processor types\n 'less',\n 'sass',\n 'scss',\n 'styl',\n 'stylus',\n 'pcss',\n 'postcss',\n // known SFC types\n 'vue',\n 'svelte',\n 'marko',\n // JSX/TSX may be configured to be compiled differently from how esbuild\n // handles it by default, so exclude them as well\n 'jsx',\n 'tsx',\n ...KNOWN_ASSET_TYPES\n]\n\nexport function esbuildDepPlugin(\n qualified: Record,\n exportsData: Record,\n config: ResolvedConfig,\n ssr?: boolean\n): Plugin {\n // default resolver which prefers ESM\n const _resolve = config.createResolver({ asSrc: false })\n\n // cjs resolver that prefers Node\n const _resolveRequire = config.createResolver({\n asSrc: false,\n isRequire: true\n })\n\n const resolve = (\n id: string,\n importer: string,\n kind: ImportKind,\n resolveDir?: string\n ): Promise => {\n let _importer: string\n // explicit resolveDir - this is passed only during yarn pnp resolve for\n // entries\n if (resolveDir) {\n _importer = normalizePath(path.join(resolveDir, '*'))\n } else {\n // map importer ids to file paths for correct resolution\n _importer = importer in qualified ? qualified[importer] : importer\n }\n const resolver = kind.startsWith('require') ? _resolveRequire : _resolve\n return resolver(id, _importer, undefined, ssr)\n }\n\n return {\n name: 'vite:dep-pre-bundle',\n setup(build) {\n // externalize assets and commonly known non-js file types\n build.onResolve(\n {\n filter: new RegExp(`\\\\.(` + externalTypes.join('|') + `)(\\\\?.*)?$`)\n },\n async ({ path: id, importer, kind }) => {\n const resolved = await resolve(id, importer, kind)\n if (resolved) {\n return {\n path: resolved,\n external: true\n }\n }\n }\n )\n\n function resolveEntry(id: string) {\n const flatId = flattenId(id)\n if (flatId in qualified) {\n return {\n path: flatId,\n namespace: 'dep'\n }\n }\n }\n\n build.onResolve(\n { filter: /^[\\w@][^:]/ },\n async ({ path: id, importer, kind }) => {\n // ensure esbuild uses our resolved entries\n let entry: { path: string; namespace: string } | undefined\n // if this is an entry, return entry namespace resolve result\n if (!importer) {\n if ((entry = resolveEntry(id))) return entry\n // check if this is aliased to an entry - also return entry namespace\n const aliased = await _resolve(id, undefined, true)\n if (aliased && (entry = resolveEntry(aliased))) {\n return entry\n }\n }\n\n // use vite's own resolver\n const resolved = await resolve(id, importer, kind)\n if (resolved) {\n if (resolved.startsWith(browserExternalId)) {\n return {\n path: id,\n namespace: 'browser-external'\n }\n }\n if (isExternalUrl(resolved)) {\n return {\n path: resolved,\n external: true\n }\n }\n return {\n path: path.resolve(resolved)\n }\n }\n }\n )\n\n // For entry files, we'll read it ourselves and construct a proxy module\n // to retain the entry's raw id instead of file path so that esbuild\n // outputs desired output file structure.\n // It is necessary to do the re-exporting to separate the virtual proxy\n // module from the actual module since the actual module may get\n // referenced via relative imports - if we don't separate the proxy and\n // the actual module, esbuild will create duplicated copies of the same\n // module!\n const root = path.resolve(config.root)\n build.onLoad({ filter: /.*/, namespace: 'dep' }, ({ path: id }) => {\n const entryFile = qualified[id]\n\n let relativePath = normalizePath(path.relative(root, entryFile))\n if (\n !relativePath.startsWith('./') &&\n !relativePath.startsWith('../') &&\n relativePath !== '.'\n ) {\n relativePath = `./${relativePath}`\n }\n\n let contents = ''\n const data = exportsData[id]\n const [imports, exports] = data\n if (!imports.length && !exports.length) {\n // cjs\n contents += `export default require(\"${relativePath}\");`\n } else {\n if (exports.includes('default')) {\n contents += `import d from \"${relativePath}\";export default d;`\n }\n if (\n data.hasReExports ||\n exports.length > 1 ||\n exports[0] !== 'default'\n ) {\n contents += `\\nexport * from \"${relativePath}\"`\n }\n }\n\n let ext = path.extname(entryFile).slice(1)\n if (ext === 'mjs') ext = 'js'\n return {\n loader: ext as Loader,\n contents,\n resolveDir: root\n }\n })\n\n build.onLoad(\n { filter: /.*/, namespace: 'browser-external' },\n ({ path: id }) => {\n return {\n contents:\n `export default new Proxy({}, {\n get() {\n throw new Error('Module \"${id}\" has been externalized for ` +\n `browser compatibility and cannot be accessed in client code.')\n }\n})`\n }\n }\n )\n\n // yarn 2 pnp compat\n if (isRunningWithYarnPnp) {\n build.onResolve(\n { filter: /.*/ },\n async ({ path, importer, kind, resolveDir }) => ({\n // pass along resolveDir for entries\n path: await resolve(path, importer, kind, resolveDir)\n })\n )\n build.onLoad({ filter: /.*/ }, async (args) => ({\n contents: await require('fs').promises.readFile(args.path),\n loader: 'default'\n }))\n }\n }\n }\n}\n","import fs from 'fs'\nimport path from 'path'\nimport chalk from 'chalk'\nimport { createHash } from 'crypto'\nimport { build, BuildOptions as EsbuildBuildOptions } from 'esbuild'\nimport { ResolvedConfig } from '../config'\nimport {\n createDebugger,\n emptyDir,\n lookupFile,\n normalizePath,\n writeFile,\n flattenId,\n normalizeId\n} from '../utils'\nimport { esbuildDepPlugin } from './esbuildDepPlugin'\nimport { ImportSpecifier, init, parse } from 'es-module-lexer'\nimport { scanImports } from './scan'\nimport { transformWithEsbuild } from '../plugins/esbuild'\n\nconst debug = createDebugger('vite:deps')\n\nexport type ExportsData = [ImportSpecifier[], string[]] & {\n // es-module-lexer has a facade detection but isn't always accurate for our\n // use case when the module has default export\n hasReExports?: true\n}\n\nexport interface DepOptimizationOptions {\n /**\n * By default, Vite will crawl your index.html to detect dependencies that\n * need to be pre-bundled. If build.rollupOptions.input is specified, Vite\n * will crawl those entry points instead.\n *\n * If neither of these fit your needs, you can specify custom entries using\n * this option - the value should be a fast-glob pattern or array of patterns\n * (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from\n * vite project root. This will overwrite default entries inference.\n */\n entries?: string | string[]\n /**\n * Force optimize listed dependencies (must be resolvable import paths,\n * cannot be globs).\n */\n include?: string[]\n /**\n * Do not optimize these dependencies (must be resolvable import paths,\n * cannot be globs).\n */\n exclude?: string[]\n /**\n * Options to pass to esbuild during the dep scanning and optimization\n *\n * Certain options are omitted since changing them would not be compatible\n * with Vite's dep optimization.\n *\n * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option\n * - `plugins` are merged with Vite's dep plugin\n * - `keepNames` takes precedence over the deprecated `optimizeDeps.keepNames`\n *\n * https://esbuild.github.io/api\n */\n esbuildOptions?: Omit<\n EsbuildBuildOptions,\n | 'bundle'\n | 'entryPoints'\n | 'external'\n | 'write'\n | 'watch'\n | 'outdir'\n | 'outfile'\n | 'outbase'\n | 'outExtension'\n | 'metafile'\n >\n /**\n * @deprecated use `esbuildOptions.keepNames`\n */\n keepNames?: boolean\n}\n\nexport interface DepOptimizationMetadata {\n /**\n * The main hash is determined by user config and dependency lockfiles.\n * This is checked on server startup to avoid unnecessary re-bundles.\n */\n hash: string\n /**\n * The browser hash is determined by the main hash plus additional dependencies\n * discovered at runtime. This is used to invalidate browser requests to\n * optimized deps.\n */\n browserHash: string\n optimized: Record<\n string,\n {\n file: string\n src: string\n needsInterop: boolean\n }\n >\n}\n\nexport async function optimizeDeps(\n config: ResolvedConfig,\n force = config.server.force,\n asCommand = false,\n newDeps?: Record, // missing imports encountered after server has started\n ssr?: boolean\n): Promise {\n config = {\n ...config,\n command: 'build'\n }\n\n const { root, logger, cacheDir } = config\n const log = asCommand ? logger.info : debug\n\n if (!cacheDir) {\n log(`No cache directory. Skipping.`)\n return null\n }\n\n const dataPath = path.join(cacheDir, '_metadata.json')\n const mainHash = getDepHash(root, config)\n const data: DepOptimizationMetadata = {\n hash: mainHash,\n browserHash: mainHash,\n optimized: {}\n }\n\n if (!force) {\n let prevData: DepOptimizationMetadata | undefined\n try {\n prevData = JSON.parse(fs.readFileSync(dataPath, 'utf-8'))\n } catch (e) {}\n // hash is consistent, no need to re-bundle\n if (prevData && prevData.hash === data.hash) {\n log('Hash is consistent. Skipping. Use --force to override.')\n return prevData\n }\n }\n\n if (fs.existsSync(cacheDir)) {\n emptyDir(cacheDir)\n } else {\n fs.mkdirSync(cacheDir, { recursive: true })\n }\n // a hint for Node.js\n // all files in the cache directory should be recognized as ES modules\n writeFile(\n path.resolve(cacheDir, 'package.json'),\n JSON.stringify({ type: 'module' })\n )\n\n let deps: Record, missing: Record\n if (!newDeps) {\n ;({ deps, missing } = await scanImports(config))\n } else {\n deps = newDeps\n missing = {}\n }\n\n // update browser hash\n data.browserHash = createHash('sha256')\n .update(data.hash + JSON.stringify(deps))\n .digest('hex')\n .substr(0, 8)\n\n const missingIds = Object.keys(missing)\n if (missingIds.length) {\n throw new Error(\n `The following dependencies are imported but could not be resolved:\\n\\n ${missingIds\n .map(\n (id) =>\n `${chalk.cyan(id)} ${chalk.white.dim(\n `(imported by ${missing[id]})`\n )}`\n )\n .join(`\\n `)}\\n\\nAre they installed?`\n )\n }\n\n const include = config.optimizeDeps?.include\n if (include) {\n const resolve = config.createResolver({ asSrc: false })\n for (const id of include) {\n // normalize 'foo >bar` as 'foo > bar' to prevent same id being added\n // and for pretty printing\n const normalizedId = normalizeId(id)\n if (!deps[normalizedId]) {\n const entry = await resolve(id)\n if (entry) {\n deps[normalizedId] = entry\n } else {\n throw new Error(\n `Failed to resolve force included dependency: ${chalk.cyan(id)}`\n )\n }\n }\n }\n }\n\n const qualifiedIds = Object.keys(deps)\n\n if (!qualifiedIds.length) {\n writeFile(dataPath, JSON.stringify(data, null, 2))\n log(`No dependencies to bundle. Skipping.\\n\\n\\n`)\n return data\n }\n\n const total = qualifiedIds.length\n const maxListed = 5\n const listed = Math.min(total, maxListed)\n const extra = Math.max(0, total - maxListed)\n const depsString = chalk.yellow(\n qualifiedIds.slice(0, listed).join(`\\n `) +\n (extra > 0 ? `\\n (...and ${extra} more)` : ``)\n )\n if (!asCommand) {\n if (!newDeps) {\n // This is auto run on server start - let the user know that we are\n // pre-optimizing deps\n logger.info(\n chalk.greenBright(`Pre-bundling dependencies:\\n ${depsString}`)\n )\n logger.info(\n `(this will be run only when your dependencies or config have changed)`\n )\n }\n } else {\n logger.info(chalk.greenBright(`Optimizing dependencies:\\n ${depsString}`))\n }\n\n // esbuild generates nested directory output with lowest common ancestor base\n // this is unpredictable and makes it difficult to analyze entry / output\n // mapping. So what we do here is:\n // 1. flatten all ids to eliminate slash\n // 2. in the plugin, read the entry ourselves as virtual files to retain the\n // path.\n const flatIdDeps: Record = {}\n const idToExports: Record = {}\n const flatIdToExports: Record = {}\n\n const { plugins = [], ...esbuildOptions } =\n config.optimizeDeps?.esbuildOptions ?? {}\n\n await init\n for (const id in deps) {\n const flatId = flattenId(id)\n const filePath = (flatIdDeps[flatId] = deps[id])\n const entryContent = fs.readFileSync(filePath, 'utf-8')\n let exportsData: ExportsData\n try {\n exportsData = parse(entryContent) as ExportsData\n } catch {\n debug(\n `Unable to parse dependency: ${id}. Trying again with a JSX transform.`\n )\n const transformed = await transformWithEsbuild(entryContent, filePath, {\n loader: 'jsx'\n })\n // Ensure that optimization won't fail by defaulting '.js' to the JSX parser.\n // This is useful for packages such as Gatsby.\n esbuildOptions.loader = {\n '.js': 'jsx',\n ...esbuildOptions.loader\n }\n exportsData = parse(transformed.code) as ExportsData\n }\n for (const { ss, se } of exportsData[0]) {\n const exp = entryContent.slice(ss, se)\n if (/export\\s+\\*\\s+from/.test(exp)) {\n exportsData.hasReExports = true\n }\n }\n idToExports[id] = exportsData\n flatIdToExports[flatId] = exportsData\n }\n\n const define: Record = {\n 'process.env.NODE_ENV': JSON.stringify(config.mode)\n }\n for (const key in config.define) {\n const value = config.define[key]\n define[key] = typeof value === 'string' ? value : JSON.stringify(value)\n }\n\n const start = Date.now()\n\n const result = await build({\n absWorkingDir: process.cwd(),\n entryPoints: Object.keys(flatIdDeps),\n bundle: true,\n format: 'esm',\n external: config.optimizeDeps?.exclude,\n logLevel: 'error',\n splitting: true,\n sourcemap: true,\n outdir: cacheDir,\n treeShaking: 'ignore-annotations',\n metafile: true,\n define,\n plugins: [\n ...plugins,\n esbuildDepPlugin(flatIdDeps, flatIdToExports, config, ssr)\n ],\n ...esbuildOptions\n })\n\n const meta = result.metafile!\n\n // the paths in `meta.outputs` are relative to `process.cwd()`\n const cacheDirOutputPath = path.relative(process.cwd(), cacheDir)\n\n for (const id in deps) {\n const entry = deps[id]\n data.optimized[id] = {\n file: normalizePath(path.resolve(cacheDir, flattenId(id) + '.js')),\n src: entry,\n needsInterop: needsInterop(\n id,\n idToExports[id],\n meta.outputs,\n cacheDirOutputPath\n )\n }\n }\n\n writeFile(dataPath, JSON.stringify(data, null, 2))\n\n debug(`deps bundled in ${Date.now() - start}ms`)\n return data\n}\n\n// https://github.com/vitejs/vite/issues/1724#issuecomment-767619642\n// a list of modules that pretends to be ESM but still uses `require`.\n// this causes esbuild to wrap them as CJS even when its entry appears to be ESM.\nconst KNOWN_INTEROP_IDS = new Set(['moment'])\n\nfunction needsInterop(\n id: string,\n exportsData: ExportsData,\n outputs: Record,\n cacheDirOutputPath: string\n): boolean {\n if (KNOWN_INTEROP_IDS.has(id)) {\n return true\n }\n const [imports, exports] = exportsData\n // entry has no ESM syntax - likely CJS or UMD\n if (!exports.length && !imports.length) {\n return true\n }\n\n // if a peer dependency used require() on a ESM dependency, esbuild turns the\n // ESM dependency's entry chunk into a single default export... detect\n // such cases by checking exports mismatch, and force interop.\n const flatId = flattenId(id) + '.js'\n let generatedExports: string[] | undefined\n for (const output in outputs) {\n if (\n normalizePath(output) ===\n normalizePath(path.join(cacheDirOutputPath, flatId))\n ) {\n generatedExports = outputs[output].exports\n break\n }\n }\n\n if (\n !generatedExports ||\n (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))\n ) {\n return true\n }\n return false\n}\n\nfunction isSingleDefaultExport(exports: string[]) {\n return exports.length === 1 && exports[0] === 'default'\n}\n\nconst lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']\n\nfunction getDepHash(root: string, config: ResolvedConfig): string {\n let content = lookupFile(root, lockfileFormats) || ''\n // also take config into account\n // only a subset of config options that can affect dep optimization\n content += JSON.stringify(\n {\n mode: config.mode,\n root: config.root,\n resolve: config.resolve,\n assetsInclude: config.assetsInclude,\n plugins: config.plugins.map((p) => p.name),\n optimizeDeps: {\n include: config.optimizeDeps?.include,\n exclude: config.optimizeDeps?.exclude\n }\n },\n (_, value) => {\n if (typeof value === 'function' || value instanceof RegExp) {\n return value.toString()\n }\n return value\n }\n )\n return createHash('sha256').update(content).digest('hex').substr(0, 8)\n}\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n","import { SourceMapConsumer, RawSourceMap } from 'source-map'\nimport { ModuleGraph } from '../server/moduleGraph'\n\nlet offset: number\ntry {\n new Function('throw new Error(1)')()\n} catch (e) {\n // in Node 12, stack traces account for the function wrapper.\n // in Node 13 and later, the function wrapper adds two lines,\n // which must be subtracted to generate a valid mapping\n const match = /:(\\d+):\\d+\\)$/.exec(e.stack.split('\\n')[1])\n offset = match ? +match[1] - 1 : 0\n}\n\nexport function ssrRewriteStacktrace(\n stack: string,\n moduleGraph: ModuleGraph\n): string {\n return stack\n .split('\\n')\n .map((line) => {\n return line.replace(\n /^ {4}at (?:(.+?)\\s+\\()?(?:(.+?):(\\d+)(?::(\\d+))?)\\)?/,\n (input, varName, url, line, column) => {\n if (!url) return input\n\n const mod = moduleGraph.urlToModuleMap.get(url)\n const rawSourceMap = mod?.ssrTransformResult?.map\n\n if (!rawSourceMap) {\n return input\n }\n\n const consumer = new SourceMapConsumer(\n rawSourceMap as unknown as RawSourceMap\n )\n\n const pos = consumer.originalPositionFor({\n line: Number(line) - offset,\n column: Number(column),\n bias: SourceMapConsumer.LEAST_UPPER_BOUND\n })\n\n if (!pos.source) {\n return input\n }\n\n const source = `${pos.source}:${pos.line || 0}:${pos.column || 0}`\n if (!varName || varName === 'eval') {\n return ` at ${source}`\n } else {\n return ` at ${varName} (${source})`\n }\n }\n )\n })\n .join('\\n')\n}\n\nexport function rebindErrorStacktrace(e: Error, stacktrace: string): void {\n const { configurable, writable } = Object.getOwnPropertyDescriptor(\n e,\n 'stack'\n )!\n if (configurable) {\n Object.defineProperty(e, 'stack', {\n value: stacktrace,\n enumerable: true,\n configurable: true,\n writable: true\n })\n } else if (writable) {\n e.stack = stacktrace\n }\n}\n","import fs from 'fs'\nimport path from 'path'\nimport { ViteDevServer } from '..'\nimport { cleanUrl, resolveFrom, unwrapId } from '../utils'\nimport { rebindErrorStacktrace, ssrRewriteStacktrace } from './ssrStacktrace'\nimport {\n ssrExportAllKey,\n ssrModuleExportsKey,\n ssrImportKey,\n ssrImportMetaKey,\n ssrDynamicImportKey\n} from './ssrTransform'\nimport { transformRequest } from '../server/transformRequest'\n\ninterface SSRContext {\n global: NodeJS.Global\n}\n\ntype SSRModule = Record\n\nconst pendingModules = new Map>()\nconst pendingImports = new Map()\n\nexport async function ssrLoadModule(\n url: string,\n server: ViteDevServer,\n context: SSRContext = { global },\n urlStack: string[] = []\n): Promise {\n url = unwrapId(url)\n\n // when we instantiate multiple dependency modules in parallel, they may\n // point to shared modules. We need to avoid duplicate instantiation attempts\n // by register every module as pending synchronously so that all subsequent\n // request to that module are simply waiting on the same promise.\n const pending = pendingModules.get(url)\n if (pending) {\n return pending\n }\n\n const modulePromise = instantiateModule(url, server, context, urlStack)\n pendingModules.set(url, modulePromise)\n modulePromise\n .catch(() => {\n pendingImports.delete(url)\n })\n .finally(() => {\n pendingModules.delete(url)\n })\n return modulePromise\n}\n\nasync function instantiateModule(\n url: string,\n server: ViteDevServer,\n context: SSRContext = { global },\n urlStack: string[] = []\n): Promise {\n const { moduleGraph } = server\n const mod = await moduleGraph.ensureEntryFromUrl(url)\n\n if (mod.ssrModule) {\n return mod.ssrModule\n }\n\n const result =\n mod.ssrTransformResult ||\n (await transformRequest(url, server, { ssr: true }))\n if (!result) {\n // TODO more info? is this even necessary?\n throw new Error(`failed to load module for ssr: ${url}`)\n }\n\n const ssrModule = {\n [Symbol.toStringTag]: 'Module'\n }\n Object.defineProperty(ssrModule, '__esModule', { value: true })\n\n // Tolerate circular imports by ensuring the module can be\n // referenced before it's been instantiated.\n mod.ssrModule = ssrModule\n\n const ssrImportMeta = { url }\n\n urlStack = urlStack.concat(url)\n const isCircular = (url: string) => urlStack.includes(url)\n\n // Since dynamic imports can happen in parallel, we need to\n // account for multiple pending deps and duplicate imports.\n const pendingDeps: string[] = []\n\n const ssrImport = async (dep: string) => {\n if (dep[0] !== '.' && dep[0] !== '/') {\n return nodeRequire(dep, mod.file, server.config.root)\n }\n dep = unwrapId(dep)\n if (!isCircular(dep) && !pendingImports.get(dep)?.some(isCircular)) {\n pendingDeps.push(dep)\n if (pendingDeps.length === 1) {\n pendingImports.set(url, pendingDeps)\n }\n await ssrLoadModule(dep, server, context, urlStack)\n if (pendingDeps.length === 1) {\n pendingImports.delete(url)\n } else {\n pendingDeps.splice(pendingDeps.indexOf(dep), 1)\n }\n }\n return moduleGraph.urlToModuleMap.get(dep)?.ssrModule\n }\n\n const ssrDynamicImport = (dep: string) => {\n // #3087 dynamic import vars is ignored at rewrite import path,\n // so here need process relative path\n if (dep[0] === '.') {\n dep = path.posix.resolve(path.dirname(url), dep)\n }\n return ssrImport(dep)\n }\n\n function ssrExportAll(sourceModule: any) {\n for (const key in sourceModule) {\n if (key !== 'default') {\n Object.defineProperty(ssrModule, key, {\n enumerable: true,\n configurable: true,\n get() {\n return sourceModule[key]\n }\n })\n }\n }\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n const AsyncFunction = async function () {}.constructor as typeof Function\n const initModule = new AsyncFunction(\n `global`,\n ssrModuleExportsKey,\n ssrImportMetaKey,\n ssrImportKey,\n ssrDynamicImportKey,\n ssrExportAllKey,\n result.code + `\\n//# sourceURL=${mod.url}`\n )\n await initModule(\n context.global,\n ssrModule,\n ssrImportMeta,\n ssrImport,\n ssrDynamicImport,\n ssrExportAll\n )\n } catch (e) {\n const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph)\n rebindErrorStacktrace(e, stacktrace)\n server.config.logger.error(\n `Error when evaluating SSR module ${url}:\\n${stacktrace}`,\n {\n timestamp: true,\n clear: server.config.clearScreen,\n error: e\n }\n )\n throw e\n }\n\n return Object.freeze(ssrModule)\n}\n\nfunction nodeRequire(id: string, importer: string | null, root: string) {\n const mod = require(resolve(id, importer, root))\n const defaultExport = mod.__esModule ? mod.default : mod\n // rollup-style default import interop for cjs\n return new Proxy(mod, {\n get(mod, prop) {\n if (prop === 'default') return defaultExport\n return mod[prop]\n }\n })\n}\n\nconst resolveCache = new Map()\n\nfunction resolve(id: string, importer: string | null, root: string) {\n const key = id + importer + root\n const cached = resolveCache.get(key)\n if (cached) {\n return cached\n }\n const resolveDir =\n importer && fs.existsSync(cleanUrl(importer))\n ? path.dirname(importer)\n : root\n const resolved = resolveFrom(id, resolveDir, true)\n resolveCache.set(key, resolved)\n return resolved\n}\n","import chalk from 'chalk'\nimport { optimizeDeps } from '.'\nimport { ViteDevServer } from '..'\nimport { resolveSSRExternal } from '../ssr/ssrExternal'\n\n/**\n * The amount to wait for requests to register newly found dependencies before triggering\n * a re-bundle + page reload\n */\nconst debounceMs = 100\n\nexport function createMissingImporterRegisterFn(\n server: ViteDevServer\n): (id: string, resolved: string, ssr?: boolean) => void {\n const { logger } = server.config\n let knownOptimized = server._optimizeDepsMetadata!.optimized\n let currentMissing: Record = {}\n let handle: NodeJS.Timeout\n\n let pendingResolve: (() => void) | null = null\n\n async function rerun(ssr: boolean | undefined) {\n const newDeps = currentMissing\n currentMissing = {}\n\n logger.info(\n chalk.yellow(\n `new dependencies found: ${Object.keys(newDeps).join(\n ', '\n )}, updating...`\n ),\n {\n timestamp: true\n }\n )\n\n for (const id in knownOptimized) {\n newDeps[id] = knownOptimized[id].src\n }\n\n try {\n // Nullify previous metadata so that the resolver won't\n // resolve to optimized files during the optimizer re-run\n server._isRunningOptimizer = true\n server._optimizeDepsMetadata = null\n\n const newData = (server._optimizeDepsMetadata = await optimizeDeps(\n server.config,\n true,\n false,\n newDeps,\n ssr\n ))\n knownOptimized = newData!.optimized\n\n // update ssr externals\n server._ssrExternals = resolveSSRExternal(\n server.config,\n Object.keys(knownOptimized)\n )\n\n logger.info(\n chalk.greenBright(`✨ dependencies updated, reloading page...`),\n { timestamp: true }\n )\n } catch (e) {\n logger.error(\n chalk.red(`error while updating dependencies:\\n${e.stack}`),\n { timestamp: true, error: e }\n )\n } finally {\n server._isRunningOptimizer = false\n pendingResolve && pendingResolve()\n server._pendingReload = pendingResolve = null\n }\n\n // Cached transform results have stale imports (resolved to\n // old locations) so they need to be invalidated before the page is\n // reloaded.\n server.moduleGraph.invalidateAll()\n\n server.ws.send({\n type: 'full-reload',\n path: '*'\n })\n }\n\n return function registerMissingImport(\n id: string,\n resolved: string,\n ssr?: boolean\n ) {\n if (!knownOptimized[id]) {\n currentMissing[id] = resolved\n if (handle) clearTimeout(handle)\n handle = setTimeout(() => rerun(ssr), debounceMs)\n server._pendingReload = new Promise((r) => {\n pendingResolve = r\n })\n }\n }\n}\n","import fs from 'fs'\nimport { dirname } from 'path'\nimport { join } from 'path'\n\n// https://github.com/vitejs/vite/issues/2820#issuecomment-812495079\nconst ROOT_FILES = [\n // '.git',\n\n // https://pnpm.js.org/workspaces/\n 'pnpm-workspace.yaml'\n\n // https://rushjs.io/pages/advanced/config_files/\n // 'rush.json',\n\n // https://nx.dev/latest/react/getting-started/nx-setup\n // 'workspace.json',\n // 'nx.json'\n]\n\n// npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces\n// yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it\nfunction hasWorkspacePackageJSON(root: string): boolean {\n const path = join(root, 'package.json')\n try {\n fs.accessSync(path, fs.constants.R_OK)\n } catch {\n return false\n }\n const content = JSON.parse(fs.readFileSync(path, 'utf-8')) || {}\n return !!content.workspaces\n}\n\nfunction hasRootFile(root: string): boolean {\n return ROOT_FILES.some((file) => fs.existsSync(join(root, file)))\n}\n\nfunction hasPackageJSON(root: string) {\n const path = join(root, 'package.json')\n return fs.existsSync(path)\n}\n\n/**\n * Search up for the nearest `package.json`\n */\nexport function searchForPackageRoot(current: string, root = current): string {\n if (hasPackageJSON(current)) return current\n\n const dir = dirname(current)\n // reach the fs root\n if (!dir || dir === current) return root\n\n return searchForPackageRoot(dir, root)\n}\n\n/**\n * Search up for the nearest workspace root\n */\nexport function searchForWorkspaceRoot(\n current: string,\n root = searchForPackageRoot(current)\n): string {\n if (hasRootFile(current)) return current\n if (hasWorkspacePackageJSON(current)) return current\n\n const dir = dirname(current)\n // reach the fs root\n if (!dir || dir === current) return root\n\n return searchForWorkspaceRoot(dir, root)\n}\n","import fs from 'fs'\nimport path from 'path'\nimport * as net from 'net'\nimport * as http from 'http'\nimport * as https from 'https'\nimport connect from 'connect'\nimport corsMiddleware from 'cors'\nimport chalk from 'chalk'\nimport { AddressInfo } from 'net'\nimport chokidar from 'chokidar'\nimport { resolveHttpsConfig, resolveHttpServer, httpServerStart } from './http'\nimport { resolveConfig, InlineConfig, ResolvedConfig } from '../config'\nimport { createPluginContainer, PluginContainer } from './pluginContainer'\nimport { FSWatcher, WatchOptions } from 'types/chokidar'\nimport { createWebSocketServer, WebSocketServer } from './ws'\nimport { baseMiddleware } from './middlewares/base'\nimport { proxyMiddleware, ProxyOptions } from './middlewares/proxy'\nimport { transformMiddleware } from './middlewares/transform'\nimport {\n createDevHtmlTransformFn,\n indexHtmlMiddleware\n} from './middlewares/indexHtml'\nimport history from 'connect-history-api-fallback'\nimport {\n serveRawFsMiddleware,\n servePublicMiddleware,\n serveStaticMiddleware\n} from './middlewares/static'\nimport { timeMiddleware } from './middlewares/time'\nimport { ModuleGraph, ModuleNode } from './moduleGraph'\nimport { Connect } from 'types/connect'\nimport { createDebugger, ensureLeadingSlash, normalizePath } from '../utils'\nimport { errorMiddleware, prepareError } from './middlewares/error'\nimport { handleHMRUpdate, HmrOptions, handleFileAddUnlink } from './hmr'\nimport { openBrowser } from './openBrowser'\nimport launchEditorMiddleware from 'launch-editor-middleware'\nimport { TransformResult } from 'rollup'\nimport { TransformOptions, transformRequest } from './transformRequest'\nimport {\n transformWithEsbuild,\n ESBuildTransformResult\n} from '../plugins/esbuild'\nimport { TransformOptions as EsbuildTransformOptions } from 'esbuild'\nimport { DepOptimizationMetadata, optimizeDeps } from '../optimizer'\nimport { ssrLoadModule } from '../ssr/ssrModuleLoader'\nimport { resolveSSRExternal } from '../ssr/ssrExternal'\nimport {\n rebindErrorStacktrace,\n ssrRewriteStacktrace\n} from '../ssr/ssrStacktrace'\nimport { createMissingImporterRegisterFn } from '../optimizer/registerMissing'\nimport { printServerUrls } from '../logger'\nimport { resolveHostname } from '../utils'\nimport { searchForWorkspaceRoot } from './searchRoot'\nimport { CLIENT_DIR } from '../constants'\n\nexport interface ServerOptions {\n host?: string | boolean\n port?: number\n /**\n * Enable TLS + HTTP/2.\n * Note: this downgrades to TLS only when the proxy option is also used.\n */\n https?: boolean | https.ServerOptions\n /**\n * Open browser window on startup\n */\n open?: boolean | string\n /**\n * Force dep pre-optimization regardless of whether deps have changed.\n */\n force?: boolean\n /**\n * Configure HMR-specific options (port, host, path & protocol)\n */\n hmr?: HmrOptions | boolean\n /**\n * chokidar watch options\n * https://github.com/paulmillr/chokidar#api\n */\n watch?: WatchOptions\n /**\n * Configure custom proxy rules for the dev server. Expects an object\n * of `{ key: options }` pairs.\n * Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).\n * Full options [here](https://github.com/http-party/node-http-proxy#options).\n *\n * Example `vite.config.js`:\n * ``` js\n * module.exports = {\n * proxy: {\n * // string shorthand\n * '/foo': 'http://localhost:4567/foo',\n * // with options\n * '/api': {\n * target: 'http://jsonplaceholder.typicode.com',\n * changeOrigin: true,\n * rewrite: path => path.replace(/^\\/api/, '')\n * }\n * }\n * }\n * ```\n */\n proxy?: Record\n /**\n * Configure CORS for the dev server.\n * Uses https://github.com/expressjs/cors.\n * Set to `true` to allow all methods from any origin, or configure separately\n * using an object.\n */\n cors?: CorsOptions | boolean\n /**\n * If enabled, vite will exit if specified port is already in use\n */\n strictPort?: boolean\n /**\n * Create Vite dev server to be used as a middleware in an existing server\n */\n middlewareMode?: boolean | 'html' | 'ssr'\n /**\n * Prepend this folder to http requests, for use when proxying vite as a subfolder\n * Should start and end with the `/` character\n */\n base?: string\n /**\n * Options for files served via '/\\@fs/'.\n */\n fs?: FileSystemServeOptions\n}\n\nexport interface ResolvedServerOptions extends ServerOptions {\n fs: Required\n}\n\nexport interface FileSystemServeOptions {\n /**\n * Strictly restrict file accessing outside of allowing paths.\n *\n * Set to `false` to disable the warning\n * Default to false at this moment, will enabled by default in the future versions.\n *\n * @expiremental\n * @default undefined\n */\n strict?: boolean | undefined\n\n /**\n * Restrict accessing files outside the allowed directories.\n *\n * Accepts absolute path or a path relative to project root.\n * Will try to search up for workspace root by default.\n *\n * @expiremental\n */\n allow?: string[]\n}\n\n/**\n * https://github.com/expressjs/cors#configuration-options\n */\nexport interface CorsOptions {\n origin?:\n | CorsOrigin\n | ((origin: string, cb: (err: Error, origins: CorsOrigin) => void) => void)\n methods?: string | string[]\n allowedHeaders?: string | string[]\n exposedHeaders?: string | string[]\n credentials?: boolean\n maxAge?: number\n preflightContinue?: boolean\n optionsSuccessStatus?: number\n}\n\nexport type CorsOrigin = boolean | string | RegExp | (string | RegExp)[]\n\nexport type ServerHook = (\n server: ViteDevServer\n) => (() => void) | void | Promise<(() => void) | void>\n\nexport interface ViteDevServer {\n /**\n * The resolved vite config object\n */\n config: ResolvedConfig\n /**\n * A connect app instance.\n * - Can be used to attach custom middlewares to the dev server.\n * - Can also be used as the handler function of a custom http server\n * or as a middleware in any connect-style Node.js frameworks\n *\n * https://github.com/senchalabs/connect#use-middleware\n */\n middlewares: Connect.Server\n /**\n * @deprecated use `server.middlewares` instead\n */\n app: Connect.Server\n /**\n * native Node http server instance\n * will be null in middleware mode\n */\n httpServer: http.Server | null\n /**\n * chokidar watcher instance\n * https://github.com/paulmillr/chokidar#api\n */\n watcher: FSWatcher\n /**\n * web socket server with `send(payload)` method\n */\n ws: WebSocketServer\n /**\n * Rollup plugin container that can run plugin hooks on a given file\n */\n pluginContainer: PluginContainer\n /**\n * Module graph that tracks the import relationships, url to file mapping\n * and hmr state.\n */\n moduleGraph: ModuleGraph\n /**\n * Programmatically resolve, load and transform a URL and get the result\n * without going through the http request pipeline.\n */\n transformRequest(\n url: string,\n options?: TransformOptions\n ): Promise\n /**\n * Apply vite built-in HTML transforms and any plugin HTML transforms.\n */\n transformIndexHtml(\n url: string,\n html: string,\n originalUrl?: string\n ): Promise\n /**\n * Util for transforming a file with esbuild.\n * Can be useful for certain plugins.\n */\n transformWithEsbuild(\n code: string,\n filename: string,\n options?: EsbuildTransformOptions,\n inMap?: object\n ): Promise\n /**\n * Load a given URL as an instantiated module for SSR.\n */\n ssrLoadModule(url: string): Promise>\n /**\n * Fix ssr error stacktrace\n */\n ssrFixStacktrace(e: Error): void\n /**\n * Start the server.\n */\n listen(port?: number, isRestart?: boolean): Promise\n /**\n * Stop the server.\n */\n close(): Promise\n /**\n * @internal\n */\n _optimizeDepsMetadata: DepOptimizationMetadata | null\n /**\n * Deps that are externalized\n * @internal\n */\n _ssrExternals: string[] | null\n /**\n * @internal\n */\n _globImporters: Record<\n string,\n {\n module: ModuleNode\n importGlobs: {\n base: string\n pattern: string\n }[]\n }\n >\n /**\n * @internal\n */\n _isRunningOptimizer: boolean\n /**\n * @internal\n */\n _registerMissingImport:\n | ((id: string, resolved: string, ssr: boolean | undefined) => void)\n | null\n /**\n * @internal\n */\n _pendingReload: Promise | null\n}\n\nexport async function createServer(\n inlineConfig: InlineConfig = {}\n): Promise {\n const config = await resolveConfig(inlineConfig, 'serve', 'development')\n const root = config.root\n const serverConfig = config.server\n const httpsOptions = await resolveHttpsConfig(config)\n let { middlewareMode } = serverConfig\n if (middlewareMode === true) {\n middlewareMode = 'ssr'\n }\n\n const middlewares = connect() as Connect.Server\n const httpServer = middlewareMode\n ? null\n : await resolveHttpServer(serverConfig, middlewares, httpsOptions)\n const ws = createWebSocketServer(httpServer, config, httpsOptions)\n\n const { ignored = [], ...watchOptions } = serverConfig.watch || {}\n const watcher = chokidar.watch(path.resolve(root), {\n ignored: [\n '**/node_modules/**',\n '**/.git/**',\n ...(Array.isArray(ignored) ? ignored : [ignored])\n ],\n ignoreInitial: true,\n ignorePermissionErrors: true,\n disableGlobbing: true,\n ...watchOptions\n }) as FSWatcher\n\n const plugins = config.plugins\n const container = await createPluginContainer(config, watcher)\n const moduleGraph = new ModuleGraph(container)\n const closeHttpServer = createServerCloseFn(httpServer)\n\n // eslint-disable-next-line prefer-const\n let exitProcess: () => void\n\n const server: ViteDevServer = {\n config: config,\n middlewares,\n get app() {\n config.logger.warn(\n `ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`\n )\n return middlewares\n },\n httpServer,\n watcher,\n pluginContainer: container,\n ws,\n moduleGraph,\n transformWithEsbuild,\n transformRequest(url, options) {\n return transformRequest(url, server, options)\n },\n transformIndexHtml: null!, // to be immediately set\n ssrLoadModule(url) {\n if (!server._ssrExternals) {\n server._ssrExternals = resolveSSRExternal(\n config,\n server._optimizeDepsMetadata\n ? Object.keys(server._optimizeDepsMetadata.optimized)\n : []\n )\n }\n return ssrLoadModule(url, server)\n },\n ssrFixStacktrace(e) {\n if (e.stack) {\n const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph)\n rebindErrorStacktrace(e, stacktrace)\n }\n },\n listen(port?: number, isRestart?: boolean) {\n return startServer(server, port, isRestart)\n },\n async close() {\n process.off('SIGTERM', exitProcess)\n\n if (!middlewareMode && process.env.CI !== 'true') {\n process.stdin.off('end', exitProcess)\n }\n\n await Promise.all([\n watcher.close(),\n ws.close(),\n container.close(),\n closeHttpServer()\n ])\n },\n _optimizeDepsMetadata: null,\n _ssrExternals: null,\n _globImporters: {},\n _isRunningOptimizer: false,\n _registerMissingImport: null,\n _pendingReload: null\n }\n\n server.transformIndexHtml = createDevHtmlTransformFn(server)\n\n exitProcess = async () => {\n try {\n await server.close()\n } finally {\n process.exit(0)\n }\n }\n\n process.once('SIGTERM', exitProcess)\n\n if (!middlewareMode && process.env.CI !== 'true') {\n process.stdin.on('end', exitProcess)\n }\n\n watcher.on('change', async (file) => {\n file = normalizePath(file)\n // invalidate module graph cache on file change\n moduleGraph.onFileChange(file)\n if (serverConfig.hmr !== false) {\n try {\n await handleHMRUpdate(file, server)\n } catch (err) {\n ws.send({\n type: 'error',\n err: prepareError(err)\n })\n }\n }\n })\n\n watcher.on('add', (file) => {\n handleFileAddUnlink(normalizePath(file), server)\n })\n\n watcher.on('unlink', (file) => {\n handleFileAddUnlink(normalizePath(file), server, true)\n })\n\n if (!middlewareMode && httpServer) {\n httpServer.once('listening', () => {\n // update actual port since this may be different from initial value\n serverConfig.port = (httpServer.address() as AddressInfo).port\n })\n }\n\n // apply server configuration hooks from plugins\n const postHooks: ((() => void) | void)[] = []\n for (const plugin of plugins) {\n if (plugin.configureServer) {\n postHooks.push(await plugin.configureServer(server))\n }\n }\n\n // Internal middlewares ------------------------------------------------------\n\n // request timer\n if (process.env.DEBUG) {\n middlewares.use(timeMiddleware(root))\n }\n\n // cors (enabled by default)\n const { cors } = serverConfig\n if (cors !== false) {\n middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors))\n }\n\n // proxy\n const { proxy } = serverConfig\n if (proxy) {\n middlewares.use(proxyMiddleware(httpServer, config))\n }\n\n // base\n if (config.base !== '/') {\n middlewares.use(baseMiddleware(server))\n }\n\n // open in editor support\n middlewares.use('/__open-in-editor', launchEditorMiddleware())\n\n // hmr reconnect ping\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n middlewares.use('/__vite_ping', function viteHMRPingMiddleware(_, res) {\n res.end('pong')\n })\n\n // serve static files under /public\n // this applies before the transform middleware so that these files are served\n // as-is without transforms.\n if (config.publicDir) {\n middlewares.use(servePublicMiddleware(config.publicDir))\n }\n\n // main transform middleware\n middlewares.use(transformMiddleware(server))\n\n // serve static files\n middlewares.use(serveRawFsMiddleware(server))\n middlewares.use(serveStaticMiddleware(root, config))\n\n // spa fallback\n if (!middlewareMode || middlewareMode === 'html') {\n middlewares.use(\n history({\n logger: createDebugger('vite:spa-fallback'),\n // support /dir/ without explicit index.html\n rewrites: [\n {\n from: /\\/$/,\n to({ parsedUrl }: any) {\n const rewritten = parsedUrl.pathname + 'index.html'\n if (fs.existsSync(path.join(root, rewritten))) {\n return rewritten\n } else {\n return `/index.html`\n }\n }\n }\n ]\n })\n )\n }\n\n // run post config hooks\n // This is applied before the html middleware so that user middleware can\n // serve custom content instead of index.html.\n postHooks.forEach((fn) => fn && fn())\n\n if (!middlewareMode || middlewareMode === 'html') {\n // transform index.html\n middlewares.use(indexHtmlMiddleware(server))\n // handle 404s\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n middlewares.use(function vite404Middleware(_, res) {\n res.statusCode = 404\n res.end()\n })\n }\n\n // error handler\n middlewares.use(errorMiddleware(server, !!middlewareMode))\n\n const runOptimize = async () => {\n if (config.cacheDir) {\n server._isRunningOptimizer = true\n try {\n server._optimizeDepsMetadata = await optimizeDeps(config)\n } finally {\n server._isRunningOptimizer = false\n }\n server._registerMissingImport = createMissingImporterRegisterFn(server)\n }\n }\n\n if (!middlewareMode && httpServer) {\n let isOptimized = false\n // overwrite listen to run optimizer before server start\n const listen = httpServer.listen.bind(httpServer)\n httpServer.listen = (async (port: number, ...args: any[]) => {\n if (!isOptimized) {\n try {\n await container.buildStart({})\n await runOptimize()\n isOptimized = true\n } catch (e) {\n httpServer.emit('error', e)\n return\n }\n }\n return listen(port, ...args)\n }) as any\n } else {\n await container.buildStart({})\n await runOptimize()\n }\n\n return server\n}\n\nasync function startServer(\n server: ViteDevServer,\n inlinePort?: number,\n isRestart: boolean = false\n): Promise {\n const httpServer = server.httpServer\n if (!httpServer) {\n throw new Error('Cannot call server.listen in middleware mode.')\n }\n\n const options = server.config.server\n const port = inlinePort || options.port || 3000\n const hostname = resolveHostname(options.host)\n\n const protocol = options.https ? 'https' : 'http'\n const info = server.config.logger.info\n const base = server.config.base\n\n const serverPort = await httpServerStart(httpServer, {\n port,\n strictPort: options.strictPort,\n host: hostname.host,\n logger: server.config.logger\n })\n\n info(\n chalk.cyan(`\\n vite v${require('vite/package.json').version}`) +\n chalk.green(` dev server running at:\\n`),\n {\n clear: !server.config.logger.hasWarned\n }\n )\n\n printServerUrls(hostname, protocol, serverPort, base, info)\n\n // @ts-ignore\n if (global.__vite_start_time) {\n info(\n chalk.cyan(\n // @ts-ignore\n `\\n ready in ${Date.now() - global.__vite_start_time}ms.\\n`\n )\n )\n }\n\n // @ts-ignore\n const profileSession = global.__vite_profile_session\n if (profileSession) {\n profileSession.post('Profiler.stop', (err: any, { profile }: any) => {\n // Write profile to disk, upload, etc.\n if (!err) {\n const outPath = path.resolve('./vite-profile.cpuprofile')\n fs.writeFileSync(outPath, JSON.stringify(profile))\n info(\n chalk.yellow(` CPU profile written to ${chalk.white.dim(outPath)}\\n`)\n )\n } else {\n throw err\n }\n })\n }\n\n if (options.open && !isRestart) {\n const path = typeof options.open === 'string' ? options.open : base\n openBrowser(\n `${protocol}://${hostname.name}:${serverPort}${path}`,\n true,\n server.config.logger\n )\n }\n\n return server\n}\n\nfunction createServerCloseFn(server: http.Server | null) {\n if (!server) {\n return () => {}\n }\n\n let hasListened = false\n const openSockets = new Set()\n\n server.on('connection', (socket) => {\n openSockets.add(socket)\n socket.on('close', () => {\n openSockets.delete(socket)\n })\n })\n\n server.once('listening', () => {\n hasListened = true\n })\n\n return () =>\n new Promise((resolve, reject) => {\n openSockets.forEach((s) => s.destroy())\n if (hasListened) {\n server.close((err) => {\n if (err) {\n reject(err)\n } else {\n resolve()\n }\n })\n } else {\n resolve()\n }\n })\n}\n\nfunction resolvedAllowDir(root: string, dir: string): string {\n return ensureLeadingSlash(normalizePath(path.resolve(root, dir)))\n}\n\nexport function resolveServerOptions(\n root: string,\n raw?: ServerOptions\n): ResolvedServerOptions {\n const server = raw || {}\n let allowDirs = server.fs?.allow\n\n if (!allowDirs) {\n allowDirs = [searchForWorkspaceRoot(root)]\n }\n\n allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i))\n\n // only push client dir when vite itself is outside-of-root\n const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR)\n if (!allowDirs.some((i) => resolvedClientDir.startsWith(i))) {\n allowDirs.push(resolvedClientDir)\n }\n\n server.fs = {\n // TODO: make strict by default\n strict: server.fs?.strict,\n allow: allowDirs\n }\n return server as ResolvedServerOptions\n}\n","const noop = () => null;\nfunction matches(pattern, importee) {\n if (pattern instanceof RegExp) {\n return pattern.test(importee);\n }\n if (importee.length < pattern.length) {\n return false;\n }\n if (importee === pattern) {\n return true;\n }\n const importeeStartsWithKey = importee.indexOf(pattern) === 0;\n const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/';\n return importeeStartsWithKey && importeeHasSlashAfterKey;\n}\nfunction normalizeId(id) {\n return id;\n}\nfunction getEntries({ entries }) {\n if (!entries) {\n return [];\n }\n if (Array.isArray(entries)) {\n return entries;\n }\n return Object.entries(entries).map(([key, value]) => {\n return { find: key, replacement: value };\n });\n}\nfunction getCustomResolver({ customResolver }, options) {\n if (typeof customResolver === 'function') {\n return customResolver;\n }\n if (customResolver && typeof customResolver.resolveId === 'function') {\n return customResolver.resolveId;\n }\n if (typeof options.customResolver === 'function') {\n return options.customResolver;\n }\n if (options.customResolver && typeof options.customResolver.resolveId === 'function') {\n return options.customResolver.resolveId;\n }\n return null;\n}\nfunction alias(options = {}) {\n const entries = getEntries(options);\n if (entries.length === 0) {\n return {\n name: 'alias',\n resolveId: noop\n };\n }\n return {\n name: 'alias',\n buildStart(inputOptions) {\n return Promise.all([...entries, options].map(({ customResolver }) => customResolver &&\n typeof customResolver === 'object' &&\n typeof customResolver.buildStart === 'function' &&\n customResolver.buildStart.call(this, inputOptions))).then(() => {\n // enforce void return value\n });\n },\n resolveId(importee, importer) {\n const importeeId = normalizeId(importee);\n const importerId = normalizeId(importer);\n // First match is supposed to be the correct one\n const matchedEntry = entries.find((entry) => matches(entry.find, importeeId));\n if (!matchedEntry || !importerId) {\n return null;\n }\n const updatedId = normalizeId(importeeId.replace(matchedEntry.find, matchedEntry.replacement));\n const customResolver = getCustomResolver(matchedEntry, options);\n if (customResolver) {\n return customResolver.call(this, updatedId, importerId, {});\n }\n return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => {\n let finalResult = resolved;\n if (!finalResult) {\n finalResult = { id: updatedId };\n }\n return finalResult;\n });\n }\n };\n}\n\nexport default alias;\n","/**\n * https://github.com/rollup/plugins/blob/master/packages/json/src/index.js\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file at\n * https://github.com/rollup/plugins/blob/master/LICENSE\n */\n\nimport { dataToEsm } from '@rollup/pluginutils'\nimport { Plugin } from 'rollup'\nimport { SPECIAL_QUERY_RE } from '../constants'\n\nexport interface JsonOptions {\n /**\n * Generate a named export for every property of the JSON object\n * @default true\n */\n namedExports?: boolean\n /**\n * Generate performant output as JSON.parse(\"stringified\").\n * Enabling this will disable namedExports.\n * @default false\n */\n stringify?: boolean\n}\n\n// Custom json filter for vite\nconst jsonExtRE = /\\.json($|\\?)(?!commonjs-proxy)/\n\nexport function jsonPlugin(\n options: JsonOptions = {},\n isBuild: boolean\n): Plugin {\n return {\n name: 'vite:json',\n\n transform(json, id) {\n if (!jsonExtRE.test(id)) return null\n if (SPECIAL_QUERY_RE.test(id)) return null\n\n try {\n if (options.stringify) {\n if (isBuild) {\n return {\n // during build, parse then double-stringify to remove all\n // unnecessary whitespaces to reduce bundle size.\n code: `export default JSON.parse(${JSON.stringify(\n JSON.stringify(JSON.parse(json))\n )})`,\n map: { mappings: '' }\n }\n } else {\n return `export default JSON.parse(${JSON.stringify(json)})`\n }\n }\n\n const parsed = JSON.parse(json)\n return {\n code: dataToEsm(parsed, {\n preferConst: true,\n namedExports: options.namedExports\n }),\n map: { mappings: '' }\n }\n } catch (e) {\n const errorMessageList = /[\\d]+/.exec(e.message)\n const position = errorMessageList && parseInt(errorMessageList[0], 10)\n const msg = position\n ? `, invalid JSON syntax found at line ${position}`\n : `.`\n this.error(`Failed to parse JSON file` + msg, e.idx)\n }\n }\n }\n}\n","import fs from 'fs'\nimport path from 'path'\nimport { Plugin } from '../plugin'\nimport { ResolvedConfig } from '../config'\nimport chalk from 'chalk'\nimport MagicString from 'magic-string'\nimport { init, parse as parseImports, ImportSpecifier } from 'es-module-lexer'\nimport { isCSSRequest, isDirectCSSRequest } from './css'\nimport {\n isBuiltin,\n cleanUrl,\n createDebugger,\n generateCodeFrame,\n injectQuery,\n isDataUrl,\n isExternalUrl,\n isJSRequest,\n prettifyUrl,\n timeFrom,\n normalizePath\n} from '../utils'\nimport {\n debugHmr,\n handlePrunedModules,\n lexAcceptedHmrDeps\n} from '../server/hmr'\nimport {\n FS_PREFIX,\n CLIENT_DIR,\n CLIENT_PUBLIC_PATH,\n DEP_VERSION_RE,\n VALID_ID_PREFIX,\n NULL_BYTE_PLACEHOLDER\n} from '../constants'\nimport { ViteDevServer } from '..'\nimport { checkPublicFile } from './asset'\nimport { parse as parseJS } from 'acorn'\nimport type { Node } from 'estree'\nimport { transformImportGlob } from '../importGlob'\nimport { makeLegalIdentifier } from '@rollup/pluginutils'\nimport { shouldExternalizeForSSR } from '../ssr/ssrExternal'\n\nconst isDebug = !!process.env.DEBUG\nconst debugRewrite = createDebugger('vite:rewrite')\n\nconst clientDir = normalizePath(CLIENT_DIR)\n\nconst skipRE = /\\.(map|json)$/\nconst canSkip = (id: string) => skipRE.test(id) || isDirectCSSRequest(id)\n\nfunction isExplicitImportRequired(url: string) {\n return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url)\n}\n\nfunction markExplicitImport(url: string) {\n if (isExplicitImportRequired(url)) {\n return injectQuery(url, 'import')\n }\n return url\n}\n\n/**\n * Server-only plugin that lexes, resolves, rewrites and analyzes url imports.\n *\n * - Imports are resolved to ensure they exist on disk\n *\n * - Lexes HMR accept calls and updates import relationships in the module graph\n *\n * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to\n * absolute file paths, e.g.\n *\n * ```js\n * import 'foo'\n * ```\n * is rewritten to\n * ```js\n * import '/@fs//project/node_modules/foo/dist/foo.js'\n * ```\n *\n * - CSS imports are appended with `.js` since both the js module and the actual\n * css (referenced via ) may go through the transform pipeline:\n *\n * ```js\n * import './style.css'\n * ```\n * is rewritten to\n * ```js\n * import './style.css.js'\n * ```\n */\nexport function importAnalysisPlugin(config: ResolvedConfig): Plugin {\n const { root, base } = config\n const clientPublicPath = path.posix.join(base, CLIENT_PUBLIC_PATH)\n\n let server: ViteDevServer\n\n return {\n name: 'vite:import-analysis',\n\n configureServer(_server) {\n server = _server\n },\n\n async transform(source, importer, ssr) {\n const prettyImporter = prettifyUrl(importer, root)\n\n if (canSkip(importer)) {\n isDebug && debugRewrite(chalk.dim(`[skipped] ${prettyImporter}`))\n return null\n }\n\n const rewriteStart = Date.now()\n await init\n let imports: readonly ImportSpecifier[] = []\n // strip UTF-8 BOM\n if (source.charCodeAt(0) === 0xfeff) {\n source = source.slice(1)\n }\n try {\n imports = parseImports(source)[0]\n } catch (e) {\n const isVue = importer.endsWith('.vue')\n const maybeJSX = !isVue && isJSRequest(importer)\n\n const msg = isVue\n ? `Install @vitejs/plugin-vue to handle .vue files.`\n : maybeJSX\n ? `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.`\n : `You may need to install appropriate plugins to handle the ${path.extname(\n importer\n )} file format.`\n\n this.error(\n `Failed to parse source for import analysis because the content ` +\n `contains invalid JS syntax. ` +\n msg,\n e.idx\n )\n }\n\n if (!imports.length) {\n isDebug &&\n debugRewrite(\n `${timeFrom(rewriteStart)} ${chalk.dim(\n `[no imports] ${prettyImporter}`\n )}`\n )\n return source\n }\n\n let hasHMR = false\n let isSelfAccepting = false\n let hasEnv = false\n let needQueryInjectHelper = false\n let s: MagicString | undefined\n const str = () => s || (s = new MagicString(source))\n // vite-only server context\n const { moduleGraph } = server\n // since we are already in the transform phase of the importer, it must\n // have been loaded so its entry is guaranteed in the module graph.\n const importerModule = moduleGraph.getModuleById(importer)!\n const importedUrls = new Set()\n const acceptedUrls = new Set<{\n url: string\n start: number\n end: number\n }>()\n const toAbsoluteUrl = (url: string) =>\n path.posix.resolve(path.posix.dirname(importerModule.url), url)\n\n const normalizeUrl = async (\n url: string,\n pos: number\n ): Promise<[string, string]> => {\n if (base !== '/' && url.startsWith(base)) {\n url = url.replace(base, '/')\n }\n\n const resolved = await this.resolve(url, importer)\n\n if (!resolved) {\n this.error(\n `Failed to resolve import \"${url}\" from \"${path.relative(\n process.cwd(),\n importer\n )}\". Does the file exist?`,\n pos\n )\n }\n\n const isRelative = url.startsWith('.')\n\n // normalize all imports into resolved URLs\n // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js`\n if (resolved.id.startsWith(root + '/')) {\n // in root: infer short absolute path from root\n url = resolved.id.slice(root.length)\n } else if (fs.existsSync(cleanUrl(resolved.id))) {\n // exists but out of root: rewrite to absolute /@fs/ paths\n url = path.posix.join(FS_PREFIX + resolved.id)\n } else {\n url = resolved.id\n }\n\n if (isExternalUrl(url)) {\n return [url, url]\n }\n\n // if the resolved id is not a valid browser import specifier,\n // prefix it to make it valid. We will strip this before feeding it\n // back into the transform pipeline\n if (!url.startsWith('.') && !url.startsWith('/')) {\n url =\n VALID_ID_PREFIX + resolved.id.replace('\\0', NULL_BYTE_PLACEHOLDER)\n }\n\n // make the URL browser-valid if not SSR\n if (!ssr) {\n // mark non-js/css imports with `?import`\n url = markExplicitImport(url)\n\n // for relative js/css imports, inherit importer's version query\n // do not do this for unknown type imports, otherwise the appended\n // query can break 3rd party plugin's extension checks.\n if (isRelative && !/[\\?&]import=?\\b/.test(url)) {\n const versionMatch = importer.match(DEP_VERSION_RE)\n if (versionMatch) {\n url = injectQuery(url, versionMatch[1])\n }\n }\n\n // check if the dep has been hmr updated. If yes, we need to attach\n // its last updated timestamp to force the browser to fetch the most\n // up-to-date version of this module.\n try {\n const depModule = await moduleGraph.ensureEntryFromUrl(url)\n if (depModule.lastHMRTimestamp > 0) {\n url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`)\n }\n } catch (e) {\n // it's possible that the dep fails to resolve (non-existent import)\n // attach location to the missing import\n e.pos = pos\n throw e\n }\n\n // prepend base (dev base is guaranteed to have ending slash)\n url = base + url.replace(/^\\//, '')\n }\n\n return [url, resolved.id]\n }\n\n for (let index = 0; index < imports.length; index++) {\n const {\n s: start,\n e: end,\n ss: expStart,\n se: expEnd,\n d: dynamicIndex,\n // #2083 User may use escape path,\n // so use imports[index].n to get the unescaped string\n // @ts-ignore\n n: specifier\n } = imports[index]\n\n const rawUrl = source.slice(start, end)\n\n // check import.meta usage\n if (rawUrl === 'import.meta') {\n const prop = source.slice(end, end + 4)\n if (prop === '.hot') {\n hasHMR = true\n if (source.slice(end + 4, end + 11) === '.accept') {\n // further analyze accepted modules\n if (\n lexAcceptedHmrDeps(\n source,\n source.indexOf('(', end + 11) + 1,\n acceptedUrls\n )\n ) {\n isSelfAccepting = true\n }\n }\n } else if (prop === '.env') {\n hasEnv = true\n } else if (prop === '.glo' && source[end + 4] === 'b') {\n // transform import.meta.glob()\n // e.g. `import.meta.glob('glob:./dir/*.js')`\n const { imports, importsString, exp, endIndex, base, pattern } =\n await transformImportGlob(\n source,\n start,\n importer,\n index,\n root,\n normalizeUrl\n )\n str().prepend(importsString)\n str().overwrite(expStart, endIndex, exp)\n imports.forEach((url) => importedUrls.add(url.replace(base, '/')))\n if (!(importerModule.file! in server._globImporters)) {\n server._globImporters[importerModule.file!] = {\n module: importerModule,\n importGlobs: []\n }\n }\n server._globImporters[importerModule.file!].importGlobs.push({\n base,\n pattern\n })\n }\n continue\n }\n\n const isDynamicImport = dynamicIndex >= 0\n\n // static import or valid string in dynamic import\n // If resolvable, let's resolve it\n if (specifier) {\n // skip external / data uri\n if (isExternalUrl(specifier) || isDataUrl(specifier)) {\n continue\n }\n // skip ssr external\n if (ssr) {\n if (\n server._ssrExternals &&\n shouldExternalizeForSSR(specifier, server._ssrExternals)\n ) {\n continue\n }\n if (isBuiltin(specifier)) {\n continue\n }\n }\n // skip client\n if (specifier === clientPublicPath) {\n continue\n }\n\n // warn imports to non-asset /public files\n if (\n specifier.startsWith('/') &&\n !config.assetsInclude(cleanUrl(specifier)) &&\n !specifier.endsWith('.json') &&\n checkPublicFile(specifier, config)\n ) {\n throw new Error(\n `Cannot import non-asset file ${specifier} which is inside /public.` +\n `JS/CSS files inside /public are copied as-is on build and ` +\n `can only be referenced via ` + ) + expect(tsOpenTag).toEqual('` + ) + expect(openTag).toEqual('`) + expect(tag).toEqual('`) + expect(tag1).toEqual(' + js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"` + shouldRemove = true + } + } + } + + // For asset references in index.html, also generate an import + // statement for each - this will be handled by the asset plugin + const assetAttrs = assetAttrsConfig[node.tag] + if (assetAttrs) { + for (const p of node.props) { + if ( + p.type === NodeTypes.ATTRIBUTE && + p.value && + assetAttrs.includes(p.name) + ) { + const url = p.value.content + if (!isExcludedUrl(url)) { + if (node.tag === 'link' && isCSSRequest(url)) { + // CSS references, convert to import + js += `\nimport ${JSON.stringify(url)}` + shouldRemove = true + } else { + assetUrls.push(p) + } + } else if (checkPublicFile(url, config)) { + s.overwrite( + p.value.loc.start.offset, + p.value.loc.end.offset, + `"${config.base + url.slice(1)}"` + ) + } + } + } + } + + if (shouldRemove) { + // remove the script tag from the html. we are going to inject new + // ones in the end. + s.remove(node.loc.start.offset, node.loc.end.offset) + } + }) + + // for each encountered asset url, rewrite original html so that it + // references the post-build location. + for (const attr of assetUrls) { + const value = attr.value! + try { + const url = + attr.name === 'srcset' + ? await processSrcSet(value.content, ({ url }) => + urlToBuiltUrl(url, id, config, this) + ) + : await urlToBuiltUrl(value.content, id, config, this) + + s.overwrite( + value.loc.start.offset, + value.loc.end.offset, + `"${url}"` + ) + } catch (e) { + // #1885 preload may be pointing to urls that do not exist + // locally on disk + if (e.code !== 'ENOENT') { + throw e + } + } + } + + processedHtml.set(id, s.toString()) + + // inject module preload polyfill + if (config.build.polyfillModulePreload) { + js = `import "${modulePreloadPolyfillId}";\n${js}` + } + + return js + } + }, + + async generateBundle(_, bundle) { + const analyzedChunk: Map = new Map() + const getPreloadLinksForChunk = ( + chunk: OutputChunk, + seen: Set = new Set() + ): HtmlTagDescriptor[] => { + const tags: HtmlTagDescriptor[] = [] + chunk.imports.forEach((file) => { + const importee = bundle[file] + if (importee?.type === 'chunk' && !seen.has(file)) { + seen.add(file) + tags.push({ + tag: 'link', + attrs: { + rel: 'modulepreload', + href: toPublicPath(file, config) + } + }) + tags.push(...getPreloadLinksForChunk(importee, seen)) + } + }) + return tags + } + + const getCssTagsForChunk = ( + chunk: OutputChunk, + seen: Set = new Set() + ): HtmlTagDescriptor[] => { + const tags: HtmlTagDescriptor[] = [] + if (!analyzedChunk.has(chunk)) { + analyzedChunk.set(chunk, 1) + chunk.imports.forEach((file) => { + const importee = bundle[file] + if (importee?.type === 'chunk') { + tags.push(...getCssTagsForChunk(importee, seen)) + } + }) + } + + const cssFiles = chunkToEmittedCssFileMap.get(chunk) + if (cssFiles) { + cssFiles.forEach((file) => { + if (!seen.has(file)) { + seen.add(file) + tags.push({ + tag: 'link', + attrs: { + rel: 'stylesheet', + href: toPublicPath(file, config) + } + }) + } + }) + } + return tags + } + + for (const [id, html] of processedHtml) { + // resolve asset url references + let result = html.replace(assetUrlRE, (_, fileHash, postfix = '') => { + return config.base + getAssetFilename(fileHash, config) + postfix + }) + + // find corresponding entry chunk + const chunk = Object.values(bundle).find( + (chunk) => + chunk.type === 'chunk' && + chunk.isEntry && + chunk.facadeModuleId === id + ) as OutputChunk | undefined + + // inject chunk asset links + if (chunk) { + const assetTags = [ + // js entry chunk for this page + { + tag: 'script', + attrs: { + type: 'module', + crossorigin: true, + src: toPublicPath(chunk.fileName, config) + } + }, + // preload for imports + ...getPreloadLinksForChunk(chunk), + ...getCssTagsForChunk(chunk) + ] + + result = injectToHead(result, assetTags) + } + + // inject css link when cssCodeSplit is false + if (!config.build.cssCodeSplit) { + const cssChunk = Object.values(bundle).find( + (chunk) => chunk.type === 'asset' && chunk.name === 'style.css' + ) as OutputAsset | undefined + if (cssChunk) { + result = injectToHead(result, [ + { + tag: 'link', + attrs: { + rel: 'stylesheet', + href: toPublicPath(cssChunk.fileName, config) + } + } + ]) + } + } + + const shortEmitName = path.posix.relative(config.root, id) + result = await applyHtmlTransforms(result, postHooks, { + path: '/' + shortEmitName, + filename: id, + bundle, + chunk + }) + + this.emitFile({ + type: 'asset', + fileName: shortEmitName, + source: result + }) + } + } + } +} + +export interface HtmlTagDescriptor { + tag: string + attrs?: Record + children?: string | HtmlTagDescriptor[] + /** + * default: 'head-prepend' + */ + injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend' +} + +export type IndexHtmlTransformResult = + | string + | HtmlTagDescriptor[] + | { + html: string + tags: HtmlTagDescriptor[] + } + +export interface IndexHtmlTransformContext { + /** + * public path when served + */ + path: string + /** + * filename on disk + */ + filename: string + server?: ViteDevServer + bundle?: OutputBundle + chunk?: OutputChunk + originalUrl?: string +} + +export type IndexHtmlTransformHook = ( + html: string, + ctx: IndexHtmlTransformContext +) => IndexHtmlTransformResult | void | Promise + +export type IndexHtmlTransform = + | IndexHtmlTransformHook + | { + enforce?: 'pre' | 'post' + transform: IndexHtmlTransformHook + } + +export function resolveHtmlTransforms( + plugins: readonly Plugin[] +): [IndexHtmlTransformHook[], IndexHtmlTransformHook[]] { + const preHooks: IndexHtmlTransformHook[] = [] + const postHooks: IndexHtmlTransformHook[] = [] + + for (const plugin of plugins) { + const hook = plugin.transformIndexHtml + if (hook) { + if (typeof hook === 'function') { + postHooks.push(hook) + } else if (hook.enforce === 'pre') { + preHooks.push(hook.transform) + } else { + postHooks.push(hook.transform) + } + } + } + + return [preHooks, postHooks] +} + +export async function applyHtmlTransforms( + html: string, + hooks: IndexHtmlTransformHook[], + ctx: IndexHtmlTransformContext +): Promise { + const headTags: HtmlTagDescriptor[] = [] + const headPrependTags: HtmlTagDescriptor[] = [] + const bodyTags: HtmlTagDescriptor[] = [] + const bodyPrependTags: HtmlTagDescriptor[] = [] + + for (const hook of hooks) { + const res = await hook(html, ctx) + if (!res) { + continue + } + if (typeof res === 'string') { + html = res + } else { + let tags: HtmlTagDescriptor[] + if (Array.isArray(res)) { + tags = res + } else { + html = res.html || html + tags = res.tags + } + for (const tag of tags) { + if (tag.injectTo === 'body') { + bodyTags.push(tag) + } else if (tag.injectTo === 'body-prepend') { + bodyPrependTags.push(tag) + } else if (tag.injectTo === 'head') { + headTags.push(tag) + } else { + headPrependTags.push(tag) + } + } + } + } + + // inject tags + if (headPrependTags.length) { + html = injectToHead(html, headPrependTags, true) + } + if (headTags.length) { + html = injectToHead(html, headTags) + } + if (bodyPrependTags.length) { + html = injectToBody(html, bodyPrependTags, true) + } + if (bodyTags.length) { + html = injectToBody(html, bodyTags) + } + + return html +} + +function toPublicPath(filename: string, config: ResolvedConfig) { + return isExternalUrl(filename) ? filename : config.base + filename +} + +const headInjectRE = /<\/head>/ +const headPrependInjectRE = [//, //i] +function injectToHead( + html: string, + tags: HtmlTagDescriptor[], + prepend = false +) { + const tagsHtml = serializeTags(tags) + if (prepend) { + // inject after head or doctype + for (const re of headPrependInjectRE) { + if (re.test(html)) { + return html.replace(re, `$&\n${tagsHtml}`) + } + } + } else { + // inject before head close + if (headInjectRE.test(html)) { + return html.replace(headInjectRE, `${tagsHtml}\n $&`) + } + } + // if no tag is present, just prepend + return tagsHtml + `\n` + html +} + +const bodyInjectRE = /<\/body>/ +const bodyPrependInjectRE = /]*>/ +function injectToBody( + html: string, + tags: HtmlTagDescriptor[], + prepend = false +) { + if (prepend) { + // inject after body open + const tagsHtml = `\n` + serializeTags(tags) + if (bodyPrependInjectRE.test(html)) { + return html.replace(bodyPrependInjectRE, `$&\n${tagsHtml}`) + } + // if no body, prepend + return tagsHtml + `\n` + html + } else { + // inject before body close + const tagsHtml = `\n` + serializeTags(tags) + if (bodyInjectRE.test(html)) { + return html.replace(bodyInjectRE, `${tagsHtml}\n$&`) + } + // if no body, append + return html + `\n` + tagsHtml + } +} + +const unaryTags = new Set(['link', 'meta', 'base']) + +function serializeTag({ tag, attrs, children }: HtmlTagDescriptor): string { + if (unaryTags.has(tag)) { + return `<${tag}${serializeAttrs(attrs)}>` + } else { + return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children)}` + } +} + +function serializeTags(tags: HtmlTagDescriptor['children']): string { + if (typeof tags === 'string') { + return tags + } else if (tags) { + return ` ${tags.map(serializeTag).join('\n ')}` + } + return '' +} + +function serializeAttrs(attrs: HtmlTagDescriptor['attrs']): string { + let res = '' + for (const key in attrs) { + if (typeof attrs[key] === 'boolean') { + res += attrs[key] ? ` ${key}` : `` + } else { + res += ` ${key}=${JSON.stringify(attrs[key])}` + } + } + return res +} diff --git a/node_modules/vite/src/node/plugins/importAnalysis.ts b/node_modules/vite/src/node/plugins/importAnalysis.ts new file mode 100644 index 0000000..b313f60 --- /dev/null +++ b/node_modules/vite/src/node/plugins/importAnalysis.ts @@ -0,0 +1,612 @@ +import fs from 'fs' +import path from 'path' +import { Plugin } from '../plugin' +import { ResolvedConfig } from '../config' +import chalk from 'chalk' +import MagicString from 'magic-string' +import { init, parse as parseImports, ImportSpecifier } from 'es-module-lexer' +import { isCSSRequest, isDirectCSSRequest } from './css' +import { + isBuiltin, + cleanUrl, + createDebugger, + generateCodeFrame, + injectQuery, + isDataUrl, + isExternalUrl, + isJSRequest, + prettifyUrl, + timeFrom, + normalizePath +} from '../utils' +import { + debugHmr, + handlePrunedModules, + lexAcceptedHmrDeps +} from '../server/hmr' +import { + FS_PREFIX, + CLIENT_DIR, + CLIENT_PUBLIC_PATH, + DEP_VERSION_RE, + VALID_ID_PREFIX, + NULL_BYTE_PLACEHOLDER +} from '../constants' +import { ViteDevServer } from '..' +import { checkPublicFile } from './asset' +import { parse as parseJS } from 'acorn' +import type { Node } from 'estree' +import { transformImportGlob } from '../importGlob' +import { makeLegalIdentifier } from '@rollup/pluginutils' +import { shouldExternalizeForSSR } from '../ssr/ssrExternal' + +const isDebug = !!process.env.DEBUG +const debugRewrite = createDebugger('vite:rewrite') + +const clientDir = normalizePath(CLIENT_DIR) + +const skipRE = /\.(map|json)$/ +const canSkip = (id: string) => skipRE.test(id) || isDirectCSSRequest(id) + +function isExplicitImportRequired(url: string) { + return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url) +} + +function markExplicitImport(url: string) { + if (isExplicitImportRequired(url)) { + return injectQuery(url, 'import') + } + return url +} + +/** + * Server-only plugin that lexes, resolves, rewrites and analyzes url imports. + * + * - Imports are resolved to ensure they exist on disk + * + * - Lexes HMR accept calls and updates import relationships in the module graph + * + * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to + * absolute file paths, e.g. + * + * ```js + * import 'foo' + * ``` + * is rewritten to + * ```js + * import '/@fs//project/node_modules/foo/dist/foo.js' + * ``` + * + * - CSS imports are appended with `.js` since both the js module and the actual + * css (referenced via ) may go through the transform pipeline: + * + * ```js + * import './style.css' + * ``` + * is rewritten to + * ```js + * import './style.css.js' + * ``` + */ +export function importAnalysisPlugin(config: ResolvedConfig): Plugin { + const { root, base } = config + const clientPublicPath = path.posix.join(base, CLIENT_PUBLIC_PATH) + + let server: ViteDevServer + + return { + name: 'vite:import-analysis', + + configureServer(_server) { + server = _server + }, + + async transform(source, importer, ssr) { + const prettyImporter = prettifyUrl(importer, root) + + if (canSkip(importer)) { + isDebug && debugRewrite(chalk.dim(`[skipped] ${prettyImporter}`)) + return null + } + + const rewriteStart = Date.now() + await init + let imports: readonly ImportSpecifier[] = [] + // strip UTF-8 BOM + if (source.charCodeAt(0) === 0xfeff) { + source = source.slice(1) + } + try { + imports = parseImports(source)[0] + } catch (e) { + const isVue = importer.endsWith('.vue') + const maybeJSX = !isVue && isJSRequest(importer) + + const msg = isVue + ? `Install @vitejs/plugin-vue to handle .vue files.` + : maybeJSX + ? `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.` + : `You may need to install appropriate plugins to handle the ${path.extname( + importer + )} file format.` + + this.error( + `Failed to parse source for import analysis because the content ` + + `contains invalid JS syntax. ` + + msg, + e.idx + ) + } + + if (!imports.length) { + isDebug && + debugRewrite( + `${timeFrom(rewriteStart)} ${chalk.dim( + `[no imports] ${prettyImporter}` + )}` + ) + return source + } + + let hasHMR = false + let isSelfAccepting = false + let hasEnv = false + let needQueryInjectHelper = false + let s: MagicString | undefined + const str = () => s || (s = new MagicString(source)) + // vite-only server context + const { moduleGraph } = server + // since we are already in the transform phase of the importer, it must + // have been loaded so its entry is guaranteed in the module graph. + const importerModule = moduleGraph.getModuleById(importer)! + const importedUrls = new Set() + const acceptedUrls = new Set<{ + url: string + start: number + end: number + }>() + const toAbsoluteUrl = (url: string) => + path.posix.resolve(path.posix.dirname(importerModule.url), url) + + const normalizeUrl = async ( + url: string, + pos: number + ): Promise<[string, string]> => { + if (base !== '/' && url.startsWith(base)) { + url = url.replace(base, '/') + } + + const resolved = await this.resolve(url, importer) + + if (!resolved) { + this.error( + `Failed to resolve import "${url}" from "${path.relative( + process.cwd(), + importer + )}". Does the file exist?`, + pos + ) + } + + const isRelative = url.startsWith('.') + + // normalize all imports into resolved URLs + // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js` + if (resolved.id.startsWith(root + '/')) { + // in root: infer short absolute path from root + url = resolved.id.slice(root.length) + } else if (fs.existsSync(cleanUrl(resolved.id))) { + // exists but out of root: rewrite to absolute /@fs/ paths + url = path.posix.join(FS_PREFIX + resolved.id) + } else { + url = resolved.id + } + + if (isExternalUrl(url)) { + return [url, url] + } + + // if the resolved id is not a valid browser import specifier, + // prefix it to make it valid. We will strip this before feeding it + // back into the transform pipeline + if (!url.startsWith('.') && !url.startsWith('/')) { + url = + VALID_ID_PREFIX + resolved.id.replace('\0', NULL_BYTE_PLACEHOLDER) + } + + // make the URL browser-valid if not SSR + if (!ssr) { + // mark non-js/css imports with `?import` + url = markExplicitImport(url) + + // for relative js/css imports, inherit importer's version query + // do not do this for unknown type imports, otherwise the appended + // query can break 3rd party plugin's extension checks. + if (isRelative && !/[\?&]import=?\b/.test(url)) { + const versionMatch = importer.match(DEP_VERSION_RE) + if (versionMatch) { + url = injectQuery(url, versionMatch[1]) + } + } + + // check if the dep has been hmr updated. If yes, we need to attach + // its last updated timestamp to force the browser to fetch the most + // up-to-date version of this module. + try { + const depModule = await moduleGraph.ensureEntryFromUrl(url) + if (depModule.lastHMRTimestamp > 0) { + url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`) + } + } catch (e) { + // it's possible that the dep fails to resolve (non-existent import) + // attach location to the missing import + e.pos = pos + throw e + } + + // prepend base (dev base is guaranteed to have ending slash) + url = base + url.replace(/^\//, '') + } + + return [url, resolved.id] + } + + for (let index = 0; index < imports.length; index++) { + const { + s: start, + e: end, + ss: expStart, + se: expEnd, + d: dynamicIndex, + // #2083 User may use escape path, + // so use imports[index].n to get the unescaped string + // @ts-ignore + n: specifier + } = imports[index] + + const rawUrl = source.slice(start, end) + + // check import.meta usage + if (rawUrl === 'import.meta') { + const prop = source.slice(end, end + 4) + if (prop === '.hot') { + hasHMR = true + if (source.slice(end + 4, end + 11) === '.accept') { + // further analyze accepted modules + if ( + lexAcceptedHmrDeps( + source, + source.indexOf('(', end + 11) + 1, + acceptedUrls + ) + ) { + isSelfAccepting = true + } + } + } else if (prop === '.env') { + hasEnv = true + } else if (prop === '.glo' && source[end + 4] === 'b') { + // transform import.meta.glob() + // e.g. `import.meta.glob('glob:./dir/*.js')` + const { imports, importsString, exp, endIndex, base, pattern } = + await transformImportGlob( + source, + start, + importer, + index, + root, + normalizeUrl + ) + str().prepend(importsString) + str().overwrite(expStart, endIndex, exp) + imports.forEach((url) => importedUrls.add(url.replace(base, '/'))) + if (!(importerModule.file! in server._globImporters)) { + server._globImporters[importerModule.file!] = { + module: importerModule, + importGlobs: [] + } + } + server._globImporters[importerModule.file!].importGlobs.push({ + base, + pattern + }) + } + continue + } + + const isDynamicImport = dynamicIndex >= 0 + + // static import or valid string in dynamic import + // If resolvable, let's resolve it + if (specifier) { + // skip external / data uri + if (isExternalUrl(specifier) || isDataUrl(specifier)) { + continue + } + // skip ssr external + if (ssr) { + if ( + server._ssrExternals && + shouldExternalizeForSSR(specifier, server._ssrExternals) + ) { + continue + } + if (isBuiltin(specifier)) { + continue + } + } + // skip client + if (specifier === clientPublicPath) { + continue + } + + // warn imports to non-asset /public files + if ( + specifier.startsWith('/') && + !config.assetsInclude(cleanUrl(specifier)) && + !specifier.endsWith('.json') && + checkPublicFile(specifier, config) + ) { + throw new Error( + `Cannot import non-asset file ${specifier} which is inside /public.` + + `JS/CSS files inside /public are copied as-is on build and ` + + `can only be referenced via ` + ) + } + } + + // elements with [href/src] attrs + const assetAttrs = assetAttrsConfig[node.tag] + if (assetAttrs) { + for (const p of node.props) { + if ( + p.type === NodeTypes.ATTRIBUTE && + p.value && + assetAttrs.includes(p.name) + ) { + processNodeUrl(p, s, config, htmlPath, originalUrl) + } + } + } + }) + + html = s.toString() + + return { + html, + tags: [ + { + tag: 'script', + attrs: { + type: 'module', + src: path.posix.join(base, CLIENT_PUBLIC_PATH) + }, + injectTo: 'head-prepend' + } + ] + } +} + +export function indexHtmlMiddleware( + server: ViteDevServer +): Connect.NextHandleFunction { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return async function viteIndexHtmlMiddleware(req, res, next) { + const url = req.url && cleanUrl(req.url) + // spa-fallback always redirects to /index.html + if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') { + const filename = getHtmlFilename(url, server) + if (fs.existsSync(filename)) { + try { + let html = fs.readFileSync(filename, 'utf-8') + html = await server.transformIndexHtml(url, html, req.originalUrl) + return send(req, res, html, 'html') + } catch (e) { + return next(e) + } + } + } + next() + } +} diff --git a/node_modules/vite/src/node/server/middlewares/proxy.ts b/node_modules/vite/src/node/server/middlewares/proxy.ts new file mode 100644 index 0000000..f23237d --- /dev/null +++ b/node_modules/vite/src/node/server/middlewares/proxy.ts @@ -0,0 +1,118 @@ +import * as http from 'http' +import { createDebugger, isObject } from '../../utils' +import httpProxy from 'http-proxy' +import { HMR_HEADER } from '../ws' +import { Connect } from 'types/connect' +import { HttpProxy } from 'types/http-proxy' +import chalk from 'chalk' +import { ResolvedConfig } from '../..' + +const debug = createDebugger('vite:proxy') + +export interface ProxyOptions extends HttpProxy.ServerOptions { + /** + * rewrite path + */ + rewrite?: (path: string) => string + /** + * configure the proxy server (e.g. listen to events) + */ + configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void + /** + * webpack-dev-server style bypass function + */ + bypass?: ( + req: http.IncomingMessage, + res: http.ServerResponse, + options: ProxyOptions + ) => void | null | undefined | false | string +} + +export function proxyMiddleware( + httpServer: http.Server | null, + config: ResolvedConfig +): Connect.NextHandleFunction { + const options = config.server.proxy! + + // lazy require only when proxy is used + const proxies: Record = {} + + Object.keys(options).forEach((context) => { + let opts = options[context] + if (typeof opts === 'string') { + opts = { target: opts, changeOrigin: true } as ProxyOptions + } + const proxy = httpProxy.createProxyServer(opts) as HttpProxy.Server + + proxy.on('error', (err) => { + config.logger.error(`${chalk.red(`http proxy error:`)}\n${err.stack}`, { + timestamp: true, + error: err + }) + }) + + if (opts.configure) { + opts.configure(proxy, opts) + } + // clone before saving because http-proxy mutates the options + proxies[context] = [proxy, { ...opts }] + }) + + if (httpServer) { + httpServer.on('upgrade', (req, socket, head) => { + const url = req.url! + for (const context in proxies) { + if (url.startsWith(context)) { + const [proxy, opts] = proxies[context] + if ( + (opts.ws || opts.target?.toString().startsWith('ws:')) && + req.headers['sec-websocket-protocol'] !== HMR_HEADER + ) { + if (opts.rewrite) { + req.url = opts.rewrite(url) + } + proxy.ws(req, socket, head) + } + } + } + }) + } + + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteProxyMiddleware(req, res, next) { + const url = req.url! + for (const context in proxies) { + if ( + (context.startsWith('^') && new RegExp(context).test(url)) || + url.startsWith(context) + ) { + const [proxy, opts] = proxies[context] + const options: HttpProxy.ServerOptions = {} + + if (opts.bypass) { + const bypassResult = opts.bypass(req, res, opts) + if (typeof bypassResult === 'string') { + req.url = bypassResult + debug(`bypass: ${req.url} -> ${bypassResult}`) + return next() + } else if (isObject(bypassResult)) { + Object.assign(options, bypassResult) + debug(`bypass: ${req.url} use modified options: %O`, options) + return next() + } else if (bypassResult === false) { + debug(`bypass: ${req.url} -> 404`) + return res.end(404) + } + } + + debug(`${req.url} -> ${opts.target || opts.forward}`) + if (opts.rewrite) { + req.url = opts.rewrite(req.url!) + } + proxy.web(req, res, options) + return + } + } + next() + } +} diff --git a/node_modules/vite/src/node/server/middlewares/static.ts b/node_modules/vite/src/node/server/middlewares/static.ts new file mode 100644 index 0000000..8bff43a --- /dev/null +++ b/node_modules/vite/src/node/server/middlewares/static.ts @@ -0,0 +1,153 @@ +import path from 'path' +import sirv, { Options } from 'sirv' +import { Connect } from 'types/connect' +import { normalizePath, ResolvedConfig, ViteDevServer } from '../..' +import { FS_PREFIX } from '../../constants' +import { + cleanUrl, + ensureLeadingSlash, + fsPathFromId, + isImportRequest, + isInternalRequest, + isWindows, + slash +} from '../../utils' +import { AccessRestrictedError } from './error' + +const sirvOptions: Options = { + dev: true, + etag: true, + extensions: [], + setHeaders(res, pathname) { + // Matches js, jsx, ts, tsx. + // The reason this is done, is that the .ts file extension is reserved + // for the MIME type video/mp2t. In almost all cases, we can expect + // these files to be TypeScript files, and for Vite to serve them with + // this Content-Type. + if (/\.[tj]sx?$/.test(pathname)) { + res.setHeader('Content-Type', 'application/javascript') + } + } +} + +export function servePublicMiddleware(dir: string): Connect.NextHandleFunction { + const serve = sirv(dir, sirvOptions) + + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteServePublicMiddleware(req, res, next) { + // skip import request and internal requests `/@fs/ /@vite-client` etc... + if (isImportRequest(req.url!) || isInternalRequest(req.url!)) { + return next() + } + serve(req, res, next) + } +} + +export function serveStaticMiddleware( + dir: string, + config: ResolvedConfig +): Connect.NextHandleFunction { + const serve = sirv(dir, sirvOptions) + + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteServeStaticMiddleware(req, res, next) { + // only serve the file if it's not an html request + // so that html requests can fallthrough to our html middleware for + // special processing + // also skip internal requests `/@fs/ /@vite-client` etc... + if ( + path.extname(cleanUrl(req.url!)) === '.html' || + isInternalRequest(req.url!) + ) { + return next() + } + + const url = decodeURI(req.url!) + + // apply aliases to static requests as well + let redirected: string | undefined + for (const { find, replacement } of config.resolve.alias) { + const matches = + typeof find === 'string' ? url.startsWith(find) : find.test(url) + if (matches) { + redirected = url.replace(find, replacement) + break + } + } + if (redirected) { + // dir is pre-normalized to posix style + if (redirected.startsWith(dir)) { + redirected = redirected.slice(dir.length) + } + req.url = redirected + } + + serve(req, res, next) + } +} + +export function serveRawFsMiddleware( + server: ViteDevServer +): Connect.NextHandleFunction { + const serveFromRoot = sirv('/', sirvOptions) + + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteServeRawFsMiddleware(req, res, next) { + let url = req.url! + // In some cases (e.g. linked monorepos) files outside of root will + // reference assets that are also out of served root. In such cases + // the paths are rewritten to `/@fs/` prefixed paths and must be served by + // searching based from fs root. + if (url.startsWith(FS_PREFIX)) { + // restrict files outside of `fs.allow` + ensureServingAccess(slash(path.resolve(fsPathFromId(url))), server) + url = url.slice(FS_PREFIX.length) + if (isWindows) url = url.replace(/^[A-Z]:/i, '') + + req.url = url + serveFromRoot(req, res, next) + } else { + next() + } + } +} + +export function isFileServingAllowed( + url: string, + server: ViteDevServer +): boolean { + // explicitly disabled + if (server.config.server.fs.strict === false) return true + + const file = ensureLeadingSlash(normalizePath(cleanUrl(url))) + + if (server.moduleGraph.safeModulesPath.has(file)) return true + + if (server.config.server.fs.allow.some((i) => file.startsWith(i + '/'))) + return true + + if (!server.config.server.fs.strict) { + server.config.logger.warnOnce(`Unrestricted file system access to "${url}"`) + server.config.logger.warnOnce( + `For security concerns, accessing files outside of serving allow list will ` + + `be restricted by default in the future version of Vite. ` + + `Refer to https://vitejs.dev/config/#server-fs-allow for more details.` + ) + return true + } + + return false +} + +export function ensureServingAccess(url: string, server: ViteDevServer): void { + if (!isFileServingAllowed(url, server)) { + const allow = server.config.server.fs.allow + throw new AccessRestrictedError( + `The request url "${url}" is outside of Vite serving allow list: + +${allow.map((i) => `- ${i}`).join('\n')} + +Refer to docs https://vitejs.dev/config/#server-fs-allow for configurations and more details.` + ) + } +} diff --git a/node_modules/vite/src/node/server/middlewares/time.ts b/node_modules/vite/src/node/server/middlewares/time.ts new file mode 100644 index 0000000..87e8152 --- /dev/null +++ b/node_modules/vite/src/node/server/middlewares/time.ts @@ -0,0 +1,18 @@ +import { Connect } from 'types/connect' +import { createDebugger, prettifyUrl, timeFrom } from '../../utils' + +const logTime = createDebugger('vite:time') + +export function timeMiddleware(root: string): Connect.NextHandleFunction { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteTimeMiddleware(req, res, next) { + const start = Date.now() + const end = res.end + res.end = (...args: any[]) => { + logTime(`${timeFrom(start)} ${prettifyUrl(req.url!, root)}`) + // @ts-ignore + return end.call(res, ...args) + } + next() + } +} diff --git a/node_modules/vite/src/node/server/middlewares/transform.ts b/node_modules/vite/src/node/server/middlewares/transform.ts new file mode 100644 index 0000000..26fb1a0 --- /dev/null +++ b/node_modules/vite/src/node/server/middlewares/transform.ts @@ -0,0 +1,194 @@ +import path from 'path' +import { ViteDevServer } from '..' +import { Connect } from 'types/connect' +import { + cleanUrl, + createDebugger, + injectQuery, + isImportRequest, + isJSRequest, + normalizePath, + prettifyUrl, + removeImportQuery, + removeTimestampQuery, + unwrapId +} from '../../utils' +import { send } from '../send' +import { transformRequest } from '../transformRequest' +import { isHTMLProxy } from '../../plugins/html' +import chalk from 'chalk' +import { + CLIENT_PUBLIC_PATH, + DEP_VERSION_RE, + NULL_BYTE_PLACEHOLDER +} from '../../constants' +import { + isCSSRequest, + isDirectCSSRequest, + isDirectRequest +} from '../../plugins/css' + +/** + * Time (ms) Vite has to full-reload the page before returning + * an empty response. + */ +const NEW_DEPENDENCY_BUILD_TIMEOUT = 1000 + +const debugCache = createDebugger('vite:cache') +const isDebug = !!process.env.DEBUG + +const knownIgnoreList = new Set(['/', '/favicon.ico']) + +export function transformMiddleware( + server: ViteDevServer +): Connect.NextHandleFunction { + const { + config: { root, logger, cacheDir }, + moduleGraph + } = server + + // determine the url prefix of files inside cache directory + let cacheDirPrefix: string | undefined + if (cacheDir) { + const cacheDirRelative = normalizePath(path.relative(root, cacheDir)) + if (cacheDirRelative.startsWith('../')) { + // if the cache directory is outside root, the url prefix would be something + // like '/@fs/absolute/path/to/node_modules/.vite' + cacheDirPrefix = `/@fs/${normalizePath(cacheDir).replace(/^\//, '')}` + } else { + // if the cache directory is inside root, the url prefix would be something + // like '/node_modules/.vite' + cacheDirPrefix = `/${cacheDirRelative}` + } + } + + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return async function viteTransformMiddleware(req, res, next) { + if (req.method !== 'GET' || knownIgnoreList.has(req.url!)) { + return next() + } + + if ( + server._pendingReload && + // always allow vite client requests so that it can trigger page reload + !req.url?.startsWith(CLIENT_PUBLIC_PATH) && + !req.url?.includes('vite/dist/client') + ) { + // missing dep pending reload, hold request until reload happens + server._pendingReload.then(() => + // If the refresh has not happened after timeout, Vite considers + // something unexpected has happened. In this case, Vite + // returns an empty response that will error. + setTimeout(() => { + // Don't do anything if response has already been sent + if (res.writableEnded) return + // status code request timeout + res.statusCode = 408 + res.end( + `

[vite] Something unexpected happened while optimizing "${req.url}"

` + + `

The current page should have reloaded by now

` + ) + }, NEW_DEPENDENCY_BUILD_TIMEOUT) + ) + return + } + + let url = decodeURI(removeTimestampQuery(req.url!)).replace( + NULL_BYTE_PLACEHOLDER, + '\0' + ) + + const withoutQuery = cleanUrl(url) + + try { + const isSourceMap = withoutQuery.endsWith('.map') + // since we generate source map references, handle those requests here + if (isSourceMap) { + const originalUrl = url.replace(/\.map($|\?)/, '$1') + const map = (await moduleGraph.getModuleByUrl(originalUrl)) + ?.transformResult?.map + if (map) { + return send(req, res, JSON.stringify(map), 'json') + } else { + return next() + } + } + + const publicPath = + normalizePath(server.config.publicDir).slice( + server.config.root.length + ) + '/' + // warn explicit public paths + if (url.startsWith(publicPath)) { + logger.warn( + chalk.yellow( + `files in the public directory are served at the root path.\n` + + `Instead of ${chalk.cyan(url)}, use ${chalk.cyan( + url.replace(publicPath, '/') + )}.` + ) + ) + } + + if ( + isJSRequest(url) || + isImportRequest(url) || + isCSSRequest(url) || + isHTMLProxy(url) + ) { + // strip ?import + url = removeImportQuery(url) + // Strip valid id prefix. This is prepended to resolved Ids that are + // not valid browser import specifiers by the importAnalysis plugin. + url = unwrapId(url) + + // for CSS, we need to differentiate between normal CSS requests and + // imports + if ( + isCSSRequest(url) && + !isDirectRequest(url) && + req.headers.accept?.includes('text/css') + ) { + url = injectQuery(url, 'direct') + } + + // check if we can return 304 early + const ifNoneMatch = req.headers['if-none-match'] + if ( + ifNoneMatch && + (await moduleGraph.getModuleByUrl(url))?.transformResult?.etag === + ifNoneMatch + ) { + isDebug && debugCache(`[304] ${prettifyUrl(url, root)}`) + res.statusCode = 304 + return res.end() + } + + // resolve, load and transform using the plugin container + const result = await transformRequest(url, server, { + html: req.headers.accept?.includes('text/html') + }) + if (result) { + const type = isDirectCSSRequest(url) ? 'css' : 'js' + const isDep = + DEP_VERSION_RE.test(url) || + (cacheDirPrefix && url.startsWith(cacheDirPrefix)) + return send( + req, + res, + result.code, + type, + result.etag, + // allow browser to cache npm deps! + isDep ? 'max-age=31536000,immutable' : 'no-cache', + result.map + ) + } + } + } catch (e) { + return next(e) + } + + next() + } +} diff --git a/node_modules/vite/src/node/server/moduleGraph.ts b/node_modules/vite/src/node/server/moduleGraph.ts new file mode 100644 index 0000000..d29c31a --- /dev/null +++ b/node_modules/vite/src/node/server/moduleGraph.ts @@ -0,0 +1,200 @@ +import { extname } from 'path' +import { isDirectCSSRequest } from '../plugins/css' +import { + cleanUrl, + normalizePath, + removeImportQuery, + removeTimestampQuery +} from '../utils' +import { FS_PREFIX } from '../constants' +import { TransformResult } from './transformRequest' +import { PluginContainer } from './pluginContainer' +import { parse as parseUrl } from 'url' + +export class ModuleNode { + /** + * Public served url path, starts with / + */ + url: string + /** + * Resolved file system path + query + */ + id: string | null = null + file: string | null = null + type: 'js' | 'css' + importers = new Set() + importedModules = new Set() + acceptedHmrDeps = new Set() + isSelfAccepting = false + transformResult: TransformResult | null = null + ssrTransformResult: TransformResult | null = null + ssrModule: Record | null = null + lastHMRTimestamp = 0 + + constructor(url: string) { + this.url = url + this.type = isDirectCSSRequest(url) ? 'css' : 'js' + } +} + +function invalidateSSRModule(mod: ModuleNode, seen: Set) { + if (seen.has(mod)) { + return + } + seen.add(mod) + mod.ssrModule = null + mod.importers.forEach((importer) => invalidateSSRModule(importer, seen)) +} +export class ModuleGraph { + urlToModuleMap = new Map() + idToModuleMap = new Map() + // a single file may corresponds to multiple modules with different queries + fileToModulesMap = new Map>() + safeModulesPath = new Set() + container: PluginContainer + + constructor(container: PluginContainer) { + this.container = container + } + + async getModuleByUrl(rawUrl: string): Promise { + const [url] = await this.resolveUrl(rawUrl) + return this.urlToModuleMap.get(url) + } + + getModuleById(id: string): ModuleNode | undefined { + return this.idToModuleMap.get(removeTimestampQuery(id)) + } + + getModulesByFile(file: string): Set | undefined { + return this.fileToModulesMap.get(file) + } + + onFileChange(file: string): void { + const mods = this.getModulesByFile(file) + if (mods) { + const seen = new Set() + mods.forEach((mod) => { + this.invalidateModule(mod, seen) + }) + } + } + + invalidateModule(mod: ModuleNode, seen: Set = new Set()): void { + mod.transformResult = null + mod.ssrTransformResult = null + invalidateSSRModule(mod, seen) + } + + invalidateAll(): void { + const seen = new Set() + this.idToModuleMap.forEach((mod) => { + this.invalidateModule(mod, seen) + }) + } + + /** + * Update the module graph based on a module's updated imports information + * If there are dependencies that no longer have any importers, they are + * returned as a Set. + */ + async updateModuleInfo( + mod: ModuleNode, + importedModules: Set, + acceptedModules: Set, + isSelfAccepting: boolean + ): Promise | undefined> { + mod.isSelfAccepting = isSelfAccepting + const prevImports = mod.importedModules + const nextImports = (mod.importedModules = new Set()) + let noLongerImported: Set | undefined + // update import graph + for (const imported of importedModules) { + const dep = + typeof imported === 'string' + ? await this.ensureEntryFromUrl(imported) + : imported + dep.importers.add(mod) + nextImports.add(dep) + } + // remove the importer from deps that were imported but no longer are. + prevImports.forEach((dep) => { + if (!nextImports.has(dep)) { + dep.importers.delete(mod) + if (!dep.importers.size) { + // dependency no longer imported + ;(noLongerImported || (noLongerImported = new Set())).add(dep) + } + } + }) + // update accepted hmr deps + const deps = (mod.acceptedHmrDeps = new Set()) + for (const accepted of acceptedModules) { + const dep = + typeof accepted === 'string' + ? await this.ensureEntryFromUrl(accepted) + : accepted + deps.add(dep) + } + return noLongerImported + } + + async ensureEntryFromUrl(rawUrl: string): Promise { + const [url, resolvedId] = await this.resolveUrl(rawUrl) + let mod = this.urlToModuleMap.get(url) + if (!mod) { + mod = new ModuleNode(url) + this.urlToModuleMap.set(url, mod) + mod.id = resolvedId + this.idToModuleMap.set(resolvedId, mod) + const file = (mod.file = cleanUrl(resolvedId)) + let fileMappedModules = this.fileToModulesMap.get(file) + if (!fileMappedModules) { + fileMappedModules = new Set() + this.fileToModulesMap.set(file, fileMappedModules) + } + fileMappedModules.add(mod) + } + return mod + } + + // some deps, like a css file referenced via @import, don't have its own + // url because they are inlined into the main css import. But they still + // need to be represented in the module graph so that they can trigger + // hmr in the importing css file. + createFileOnlyEntry(file: string): ModuleNode { + file = normalizePath(file) + let fileMappedModules = this.fileToModulesMap.get(file) + if (!fileMappedModules) { + fileMappedModules = new Set() + this.fileToModulesMap.set(file, fileMappedModules) + } + + const url = `${FS_PREFIX}${file}` + for (const m of fileMappedModules) { + if (m.url === url || m.id === file) { + return m + } + } + + const mod = new ModuleNode(url) + mod.file = file + fileMappedModules.add(mod) + return mod + } + + // for incoming urls, it is important to: + // 1. remove the HMR timestamp query (?t=xxxx) + // 2. resolve its extension so that urls with or without extension all map to + // the same module + async resolveUrl(url: string): Promise<[string, string]> { + url = removeImportQuery(removeTimestampQuery(url)) + const resolvedId = (await this.container.resolveId(url))?.id || url + const ext = extname(cleanUrl(resolvedId)) + const { pathname, search, hash } = parseUrl(url) + if (ext && !pathname!.endsWith(ext)) { + url = pathname + ext + (search || '') + (hash || '') + } + return [url, resolvedId] + } +} diff --git a/node_modules/vite/src/node/server/openBrowser.ts b/node_modules/vite/src/node/server/openBrowser.ts new file mode 100644 index 0000000..658e7ab --- /dev/null +++ b/node_modules/vite/src/node/server/openBrowser.ts @@ -0,0 +1,101 @@ +/** + * The following is modified based on source found in + * https://github.com/facebook/create-react-app + * + * MIT Licensed + * Copyright (c) 2015-present, Facebook, Inc. + * https://github.com/facebook/create-react-app/blob/master/LICENSE + * + */ + +import path from 'path' +import open from 'open' +import execa from 'execa' +import chalk from 'chalk' +import { execSync } from 'child_process' +import { Logger } from '../logger' + +// https://github.com/sindresorhus/open#app +const OSX_CHROME = 'google chrome' + +/** + * Reads the BROWSER environment variable and decides what to do with it. + * Returns true if it opened a browser or ran a node.js script, otherwise false. + */ +export function openBrowser( + url: string, + opt: string | true, + logger: Logger +): boolean { + // The browser executable to open. + // See https://github.com/sindresorhus/open#app for documentation. + const browser = typeof opt === 'string' ? opt : process.env.BROWSER || '' + if (browser.toLowerCase().endsWith('.js')) { + return executeNodeScript(browser, url, logger) + } else if (browser.toLowerCase() !== 'none') { + return startBrowserProcess(browser, url) + } + return false +} + +function executeNodeScript(scriptPath: string, url: string, logger: Logger) { + const extraArgs = process.argv.slice(2) + const child = execa('node', [scriptPath, ...extraArgs, url], { + stdio: 'inherit' + }) + child.on('close', (code) => { + if (code !== 0) { + logger.error( + chalk.red( + `\nThe script specified as BROWSER environment variable failed.\n\n${chalk.cyan( + scriptPath + )} exited with code ${code}.` + ), + { error: null } + ) + } + }) + return true +} + +function startBrowserProcess(browser: string | undefined, url: string) { + // If we're on OS X, the user hasn't specifically + // requested a different browser, we can try opening + // Chrome with AppleScript. This lets us reuse an + // existing tab when possible instead of creating a new one. + const shouldTryOpenChromeWithAppleScript = + process.platform === 'darwin' && (browser === '' || browser === OSX_CHROME) + + if (shouldTryOpenChromeWithAppleScript) { + try { + // Try our best to reuse existing tab + // on OS X Google Chrome with AppleScript + execSync('ps cax | grep "Google Chrome"') + execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', { + cwd: path.dirname(require.resolve('vite/bin/openChrome.applescript')), + stdio: 'ignore' + }) + return true + } catch (err) { + // Ignore errors + } + } + + // Another special case: on OS X, check if BROWSER has been set to "open". + // In this case, instead of passing the string `open` to `open` function (which won't work), + // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser): + // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768 + if (process.platform === 'darwin' && browser === 'open') { + browser = undefined + } + + // Fallback to open + // (It will always open new tab) + try { + const options: open.Options = browser ? { app: { name: browser } } : {} + open(url, options).catch(() => {}) // Prevent `unhandledRejection` error. + return true + } catch (err) { + return false + } +} diff --git a/node_modules/vite/src/node/server/pluginContainer.ts b/node_modules/vite/src/node/server/pluginContainer.ts new file mode 100644 index 0000000..73e962c --- /dev/null +++ b/node_modules/vite/src/node/server/pluginContainer.ts @@ -0,0 +1,550 @@ +/** + * This file is refactored into TypeScript based on + * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js + */ + +/** +https://github.com/preactjs/wmr/blob/master/LICENSE + +MIT License + +Copyright (c) 2020 The Preact Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import fs from 'fs' +import { resolve, join } from 'path' +import { Plugin } from '../plugin' +import { + InputOptions, + MinimalPluginContext, + OutputOptions, + ModuleInfo, + NormalizedInputOptions, + ChangeEvent, + PartialResolvedId, + ResolvedId, + PluginContext as RollupPluginContext, + LoadResult, + SourceDescription, + EmittedFile, + SourceMap, + RollupError, + TransformResult +} from 'rollup' +import * as acorn from 'acorn' +import acornClassFields from 'acorn-class-fields' +import acornNumericSeparator from 'acorn-numeric-separator' +import acornStaticClassFeatures from 'acorn-static-class-features' +import { RawSourceMap } from '@ampproject/remapping/dist/types/types' +import { combineSourcemaps } from '../utils' +import MagicString from 'magic-string' +import { FSWatcher } from 'chokidar' +import { + createDebugger, + ensureWatchedFile, + generateCodeFrame, + isObject, + isExternalUrl, + normalizePath, + numberToPos, + prettifyUrl, + timeFrom +} from '../utils' +import { FS_PREFIX } from '../constants' +import chalk from 'chalk' +import { ResolvedConfig } from '../config' +import { buildErrorMessage } from './middlewares/error' + +export interface PluginContainerOptions { + cwd?: string + output?: OutputOptions + modules?: Map + writeFile?: (name: string, source: string | Uint8Array) => void +} + +export interface PluginContainer { + options: InputOptions + buildStart(options: InputOptions): Promise + watchChange(id: string, event?: ChangeEvent): void + resolveId( + id: string, + importer?: string, + skip?: Set, + ssr?: boolean + ): Promise + transform( + code: string, + id: string, + inMap?: SourceDescription['map'], + ssr?: boolean + ): Promise + load(id: string, ssr?: boolean): Promise + close(): Promise +} + +type PluginContext = Omit< + RollupPluginContext, + // not documented + | 'cache' + // deprecated + | 'emitAsset' + | 'emitChunk' + | 'getAssetFileName' + | 'getChunkFileName' + | 'isExternal' + | 'moduleIds' + | 'resolveId' +> + +export let parser = acorn.Parser.extend( + acornClassFields, + acornStaticClassFeatures, + acornNumericSeparator +) + +export async function createPluginContainer( + { plugins, logger, root, build: { rollupOptions } }: ResolvedConfig, + watcher?: FSWatcher +): Promise { + const isDebug = process.env.DEBUG + + const seenResolves: Record = {} + const debugResolve = createDebugger('vite:resolve') + const debugPluginResolve = createDebugger('vite:plugin-resolve', { + onlyWhenFocused: 'vite:plugin' + }) + const debugPluginTransform = createDebugger('vite:plugin-transform', { + onlyWhenFocused: 'vite:plugin' + }) + + // --------------------------------------------------------------------------- + + const MODULES = new Map() + const watchFiles = new Set() + + // get rollup version + const rollupPkgPath = resolve(require.resolve('rollup'), '../../package.json') + const minimalContext: MinimalPluginContext = { + meta: { + rollupVersion: JSON.parse(fs.readFileSync(rollupPkgPath, 'utf-8')) + .version, + watchMode: true + } + } + + function warnIncompatibleMethod(method: string, plugin: string) { + logger.warn( + chalk.cyan(`[plugin:${plugin}] `) + + chalk.yellow( + `context method ${chalk.bold( + `${method}()` + )} is not supported in serve mode. This plugin is likely not vite-compatible.` + ) + ) + } + + // we should create a new context for each async hook pipeline so that the + // active plugin in that pipeline can be tracked in a concurrency-safe manner. + // using a class to make creating new contexts more efficient + class Context implements PluginContext { + meta = minimalContext.meta + ssr = false + _activePlugin: Plugin | null + _activeId: string | null = null + _activeCode: string | null = null + _resolveSkips?: Set + _addedImports: Set | null = null + + constructor(initialPlugin?: Plugin) { + this._activePlugin = initialPlugin || null + } + + parse(code: string, opts: any = {}) { + return parser.parse(code, { + sourceType: 'module', + ecmaVersion: 2020, + locations: true, + ...opts + }) + } + + async resolve( + id: string, + importer?: string, + options?: { skipSelf?: boolean } + ) { + let skips: Set | undefined + if (options?.skipSelf && this._activePlugin) { + skips = new Set(this._resolveSkips) + skips.add(this._activePlugin) + } + let out = await container.resolveId(id, importer, skips, this.ssr) + if (typeof out === 'string') out = { id: out } + return out as ResolvedId | null + } + + getModuleInfo(id: string) { + let mod = MODULES.get(id) + if (mod) return mod.info + mod = { + /** @type {import('rollup').ModuleInfo} */ + // @ts-ignore-next + info: {} + } + MODULES.set(id, mod) + return mod.info + } + + getModuleIds() { + return MODULES.keys() + } + + addWatchFile(id: string) { + watchFiles.add(id) + ;(this._addedImports || (this._addedImports = new Set())).add(id) + if (watcher) ensureWatchedFile(watcher, id, root) + } + + getWatchFiles() { + return [...watchFiles] + } + + emitFile(assetOrFile: EmittedFile) { + warnIncompatibleMethod(`emitFile`, this._activePlugin!.name) + return '' + } + + setAssetSource() { + warnIncompatibleMethod(`setAssetSource`, this._activePlugin!.name) + } + + getFileName() { + warnIncompatibleMethod(`getFileName`, this._activePlugin!.name) + return '' + } + + warn( + e: string | RollupError, + position?: number | { column: number; line: number } + ) { + const err = formatError(e, position, this) + const msg = buildErrorMessage( + err, + [chalk.yellow(`warning: ${err.message}`)], + false + ) + logger.warn(msg, { + clear: true, + timestamp: true + }) + } + + error( + e: string | RollupError, + position?: number | { column: number; line: number } + ): never { + // error thrown here is caught by the transform middleware and passed on + // the the error middleware. + throw formatError(e, position, this) + } + } + + function formatError( + e: string | RollupError, + position: number | { column: number; line: number } | undefined, + ctx: Context + ) { + const err = (typeof e === 'string' ? new Error(e) : e) as RollupError + if (ctx._activePlugin) err.plugin = ctx._activePlugin.name + if (ctx._activeId && !err.id) err.id = ctx._activeId + if (ctx._activeCode) { + err.pluginCode = ctx._activeCode + const pos = + position != null + ? position + : err.pos != null + ? err.pos + : // some rollup plugins, e.g. json, sets position instead of pos + (err as any).position + if (pos != null) { + err.loc = err.loc || { + file: err.id, + ...numberToPos(ctx._activeCode, pos) + } + err.frame = err.frame || generateCodeFrame(ctx._activeCode, pos) + } else if (err.loc) { + // css preprocessors may report errors in an included file + if (!err.frame) { + let code = ctx._activeCode + if (err.loc.file) { + err.id = normalizePath(err.loc.file) + try { + code = fs.readFileSync(err.loc.file, 'utf-8') + } catch {} + } + err.frame = generateCodeFrame(code, err.loc) + } + } else if ((err as any).line && (err as any).column) { + err.loc = { + file: err.id, + line: (err as any).line, + column: (err as any).column + } + err.frame = err.frame || generateCodeFrame(ctx._activeCode, err.loc) + } + } + return err + } + + class TransformContext extends Context { + filename: string + originalCode: string + originalSourcemap: SourceMap | null = null + sourcemapChain: NonNullable[] = [] + combinedMap: SourceMap | null = null + + constructor(filename: string, code: string, inMap?: SourceMap | string) { + super() + this.filename = filename + this.originalCode = code + if (inMap) { + this.sourcemapChain.push(inMap) + } + } + + _getCombinedSourcemap(createIfNull = false) { + let combinedMap = this.combinedMap + for (let m of this.sourcemapChain) { + if (typeof m === 'string') m = JSON.parse(m) + if (!('version' in (m as SourceMap))) { + // empty, nullified source map + combinedMap = this.combinedMap = null + this.sourcemapChain.length = 0 + break + } + if (!combinedMap) { + combinedMap = m as SourceMap + } else { + combinedMap = combineSourcemaps(this.filename, [ + { + ...(m as RawSourceMap), + sourcesContent: combinedMap.sourcesContent + }, + combinedMap as RawSourceMap + ]) as SourceMap + } + } + if (!combinedMap) { + return createIfNull + ? new MagicString(this.originalCode).generateMap({ + includeContent: true, + hires: true, + source: this.filename + }) + : null + } + if (combinedMap !== this.combinedMap) { + this.combinedMap = combinedMap + this.sourcemapChain.length = 0 + } + return this.combinedMap + } + + getCombinedSourcemap() { + return this._getCombinedSourcemap(true) as SourceMap + } + } + + let closed = false + + const container: PluginContainer = { + options: await (async () => { + let options = rollupOptions + for (const plugin of plugins) { + if (!plugin.options) continue + options = + (await plugin.options.call(minimalContext, options)) || options + } + if (options.acornInjectPlugins) { + parser = acorn.Parser.extend( + ...[ + acornClassFields, + acornStaticClassFeatures, + acornNumericSeparator + ].concat(options.acornInjectPlugins) + ) + } + return { + acorn, + acornInjectPlugins: [], + ...options + } + })(), + + async buildStart() { + await Promise.all( + plugins.map((plugin) => { + if (plugin.buildStart) { + return plugin.buildStart.call( + new Context(plugin) as any, + container.options as NormalizedInputOptions + ) + } + }) + ) + }, + + async resolveId(rawId, importer = join(root, 'index.html'), skips, ssr) { + const ctx = new Context() + ctx.ssr = !!ssr + ctx._resolveSkips = skips + const resolveStart = isDebug ? Date.now() : 0 + + let id: string | null = null + const partial: Partial = {} + for (const plugin of plugins) { + if (!plugin.resolveId) continue + if (skips?.has(plugin)) continue + + ctx._activePlugin = plugin + + const pluginResolveStart = isDebug ? Date.now() : 0 + const result = await plugin.resolveId.call( + ctx as any, + rawId, + importer, + {}, + ssr + ) + if (!result) continue + + if (typeof result === 'string') { + id = result + } else { + id = result.id + Object.assign(partial, result) + } + + isDebug && + debugPluginResolve( + timeFrom(pluginResolveStart), + plugin.name, + prettifyUrl(id, root) + ) + + // resolveId() is hookFirst - first non-null result is returned. + break + } + + if (isDebug && rawId !== id && !rawId.startsWith(FS_PREFIX)) { + const key = rawId + id + // avoid spamming + if (!seenResolves[key]) { + seenResolves[key] = true + debugResolve( + `${timeFrom(resolveStart)} ${chalk.cyan(rawId)} -> ${chalk.dim(id)}` + ) + } + } + + if (id) { + partial.id = isExternalUrl(id) ? id : normalizePath(id) + return partial as PartialResolvedId + } else { + return null + } + }, + + async load(id, ssr) { + const ctx = new Context() + ctx.ssr = !!ssr + for (const plugin of plugins) { + if (!plugin.load) continue + ctx._activePlugin = plugin + const result = await plugin.load.call(ctx as any, id, ssr) + if (result != null) { + return result + } + } + return null + }, + + async transform(code, id, inMap, ssr) { + const ctx = new TransformContext(id, code, inMap as SourceMap) + ctx.ssr = !!ssr + for (const plugin of plugins) { + if (!plugin.transform) continue + ctx._activePlugin = plugin + ctx._activeId = id + ctx._activeCode = code + const start = isDebug ? Date.now() : 0 + let result: TransformResult | string | undefined + try { + result = await plugin.transform.call(ctx as any, code, id, ssr) + } catch (e) { + ctx.error(e) + } + if (!result) continue + isDebug && + debugPluginTransform( + timeFrom(start), + plugin.name, + prettifyUrl(id, root) + ) + if (isObject(result)) { + code = result.code || '' + if (result.map) ctx.sourcemapChain.push(result.map) + } else { + code = result + } + } + return { + code, + map: ctx._getCombinedSourcemap() + } + }, + + watchChange(id, event = 'update') { + const ctx = new Context() + if (watchFiles.has(id)) { + for (const plugin of plugins) { + if (!plugin.watchChange) continue + ctx._activePlugin = plugin + plugin.watchChange.call(ctx as any, id, { event }) + } + } + }, + + async close() { + if (closed) return + const ctx = new Context() + await Promise.all( + plugins.map((p) => p.buildEnd && p.buildEnd.call(ctx as any)) + ) + await Promise.all( + plugins.map((p) => p.closeBundle && p.closeBundle.call(ctx as any)) + ) + closed = true + } + } + + return container +} diff --git a/node_modules/vite/src/node/server/searchRoot.ts b/node_modules/vite/src/node/server/searchRoot.ts new file mode 100644 index 0000000..623cfd5 --- /dev/null +++ b/node_modules/vite/src/node/server/searchRoot.ts @@ -0,0 +1,70 @@ +import fs from 'fs' +import { dirname } from 'path' +import { join } from 'path' + +// https://github.com/vitejs/vite/issues/2820#issuecomment-812495079 +const ROOT_FILES = [ + // '.git', + + // https://pnpm.js.org/workspaces/ + 'pnpm-workspace.yaml' + + // https://rushjs.io/pages/advanced/config_files/ + // 'rush.json', + + // https://nx.dev/latest/react/getting-started/nx-setup + // 'workspace.json', + // 'nx.json' +] + +// npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces +// yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it +function hasWorkspacePackageJSON(root: string): boolean { + const path = join(root, 'package.json') + try { + fs.accessSync(path, fs.constants.R_OK) + } catch { + return false + } + const content = JSON.parse(fs.readFileSync(path, 'utf-8')) || {} + return !!content.workspaces +} + +function hasRootFile(root: string): boolean { + return ROOT_FILES.some((file) => fs.existsSync(join(root, file))) +} + +function hasPackageJSON(root: string) { + const path = join(root, 'package.json') + return fs.existsSync(path) +} + +/** + * Search up for the nearest `package.json` + */ +export function searchForPackageRoot(current: string, root = current): string { + if (hasPackageJSON(current)) return current + + const dir = dirname(current) + // reach the fs root + if (!dir || dir === current) return root + + return searchForPackageRoot(dir, root) +} + +/** + * Search up for the nearest workspace root + */ +export function searchForWorkspaceRoot( + current: string, + root = searchForPackageRoot(current) +): string { + if (hasRootFile(current)) return current + if (hasWorkspacePackageJSON(current)) return current + + const dir = dirname(current) + // reach the fs root + if (!dir || dir === current) return root + + return searchForWorkspaceRoot(dir, root) +} diff --git a/node_modules/vite/src/node/server/send.ts b/node_modules/vite/src/node/server/send.ts new file mode 100644 index 0000000..1c54ec4 --- /dev/null +++ b/node_modules/vite/src/node/server/send.ts @@ -0,0 +1,54 @@ +import { IncomingMessage, ServerResponse } from 'http' +import getEtag from 'etag' +import { SourceMap } from 'rollup' + +const isDebug = process.env.DEBUG + +const alias: Record = { + js: 'application/javascript', + css: 'text/css', + html: 'text/html', + json: 'application/json' +} + +export function send( + req: IncomingMessage, + res: ServerResponse, + content: string | Buffer, + type: string, + etag = getEtag(content, { weak: true }), + cacheControl = 'no-cache', + map?: SourceMap | null +): void { + if (req.headers['if-none-match'] === etag) { + res.statusCode = 304 + return res.end() + } + + res.setHeader('Content-Type', alias[type] || type) + res.setHeader('Cache-Control', cacheControl) + res.setHeader('Etag', etag) + + // inject source map reference + if (map && map.mappings) { + if (isDebug) { + content += `\n/*${JSON.stringify(map, null, 2).replace( + /\*\//g, + '*\\/' + )}*/\n` + } + content += genSourceMapString(map) + } + + res.statusCode = 200 + return res.end(content) +} + +function genSourceMapString(map: SourceMap | string | undefined) { + if (typeof map !== 'string') { + map = JSON.stringify(map) + } + return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from( + map + ).toString('base64')}` +} diff --git a/node_modules/vite/src/node/server/sourcemap.ts b/node_modules/vite/src/node/server/sourcemap.ts new file mode 100644 index 0000000..515b5a6 --- /dev/null +++ b/node_modules/vite/src/node/server/sourcemap.ts @@ -0,0 +1,54 @@ +import path from 'path' +import { promises as fs } from 'fs' +import { Logger } from '../logger' +import { createDebugger } from '../utils' + +const isDebug = !!process.env.DEBUG +const debug = createDebugger('vite:sourcemap', { + onlyWhenFocused: true +}) + +interface SourceMapLike { + sources: string[] + sourcesContent?: (string | null)[] + sourceRoot?: string +} + +export async function injectSourcesContent( + map: SourceMapLike, + file: string, + logger: Logger +): Promise { + let sourceRoot: string | undefined + try { + // The source root is undefined for virtual modules and permission errors. + sourceRoot = await fs.realpath( + path.resolve(path.dirname(file), map.sourceRoot || '') + ) + } catch {} + + const missingSources: string[] = [] + map.sourcesContent = await Promise.all( + map.sources.map((sourcePath) => { + if (sourcePath) { + sourcePath = decodeURI(sourcePath) + if (sourceRoot) { + sourcePath = path.resolve(sourceRoot, sourcePath) + } + return fs.readFile(sourcePath, 'utf-8').catch(() => { + missingSources.push(sourcePath) + return null + }) + } + return null + }) + ) + + // Use this command… + // DEBUG="vite:sourcemap" vite build + // …to log the missing sources. + if (missingSources.length) { + logger.warnOnce(`Sourcemap for "${file}" points to missing source files`) + isDebug && debug(`Missing sources:\n ` + missingSources.join(`\n `)) + } +} diff --git a/node_modules/vite/src/node/server/transformRequest.ts b/node_modules/vite/src/node/server/transformRequest.ts new file mode 100644 index 0000000..483df46 --- /dev/null +++ b/node_modules/vite/src/node/server/transformRequest.ts @@ -0,0 +1,167 @@ +import { promises as fs } from 'fs' +import path from 'path' +import getEtag from 'etag' +import * as convertSourceMap from 'convert-source-map' +import { SourceDescription, SourceMap } from 'rollup' +import { ViteDevServer } from '..' +import chalk from 'chalk' +import { + createDebugger, + cleanUrl, + prettifyUrl, + removeTimestampQuery, + timeFrom, + ensureWatchedFile, + isObject +} from '../utils' +import { checkPublicFile } from '../plugins/asset' +import { ssrTransform } from '../ssr/ssrTransform' +import { injectSourcesContent } from './sourcemap' +import { isFileServingAllowed } from './middlewares/static' + +const debugLoad = createDebugger('vite:load') +const debugTransform = createDebugger('vite:transform') +const debugCache = createDebugger('vite:cache') +const isDebug = !!process.env.DEBUG + +export interface TransformResult { + code: string + map: SourceMap | null + etag?: string + deps?: string[] +} + +export interface TransformOptions { + ssr?: boolean + html?: boolean +} + +export async function transformRequest( + url: string, + server: ViteDevServer, + options: TransformOptions = {} +): Promise { + const { config, pluginContainer, moduleGraph, watcher } = server + + url = removeTimestampQuery(url) + const { root, logger } = config + const prettyUrl = isDebug ? prettifyUrl(url, root) : '' + const ssr = !!options.ssr + + // check if we have a fresh cache + const module = await moduleGraph.getModuleByUrl(url) + const cached = + module && (ssr ? module.ssrTransformResult : module.transformResult) + if (cached) { + isDebug && debugCache(`[memory] ${prettyUrl}`) + return cached + } + + // resolve + const id = (await pluginContainer.resolveId(url))?.id || url + const file = cleanUrl(id) + + let code: string | null = null + let map: SourceDescription['map'] = null + + // load + const loadStart = isDebug ? Date.now() : 0 + const loadResult = await pluginContainer.load(id, ssr) + if (loadResult == null) { + // if this is an html request and there is no load result, skip ahead to + // SPA fallback. + if (options.html && !id.endsWith('.html')) { + return null + } + // try fallback loading it from fs as string + // if the file is a binary, there should be a plugin that already loaded it + // as string + // only try the fallback if access is allowed, skip for out of root url + // like /service-worker.js or /api/users + if (options.ssr || isFileServingAllowed(file, server)) { + try { + code = await fs.readFile(file, 'utf-8') + isDebug && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`) + } catch (e) { + if (e.code !== 'ENOENT') { + throw e + } + } + } + if (code) { + try { + map = ( + convertSourceMap.fromSource(code) || + convertSourceMap.fromMapFileSource(code, path.dirname(file)) + )?.toObject() + } catch (e) { + logger.warn(`Failed to load source map for ${url}.`, { + timestamp: true + }) + } + } + } else { + isDebug && debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`) + if (isObject(loadResult)) { + code = loadResult.code + map = loadResult.map + } else { + code = loadResult + } + } + if (code == null) { + if (checkPublicFile(url, config)) { + throw new Error( + `Failed to load url ${url} (resolved id: ${id}). ` + + `This file is in /public and will be copied as-is during build without ` + + `going through the plugin transforms, and therefore should not be ` + + `imported from source code. It can only be referenced via HTML tags.` + ) + } else { + return null + } + } + + // ensure module in graph after successful load + const mod = await moduleGraph.ensureEntryFromUrl(url) + ensureWatchedFile(watcher, mod.file, root) + + // transform + const transformStart = isDebug ? Date.now() : 0 + const transformResult = await pluginContainer.transform(code, id, map, ssr) + if ( + transformResult == null || + (isObject(transformResult) && transformResult.code == null) + ) { + // no transform applied, keep code as-is + isDebug && + debugTransform( + timeFrom(transformStart) + chalk.dim(` [skipped] ${prettyUrl}`) + ) + } else { + isDebug && debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`) + code = transformResult.code! + map = transformResult.map + } + + if (map && mod.file) { + map = (typeof map === 'string' ? JSON.parse(map) : map) as SourceMap + if (map.mappings && !map.sourcesContent) { + await injectSourcesContent(map, mod.file, logger) + } + } + + if (ssr) { + return (mod.ssrTransformResult = await ssrTransform( + code, + map as SourceMap, + url + )) + } else { + return (mod.transformResult = { + code, + map, + etag: getEtag(code, { weak: true }) + } as TransformResult) + } +} diff --git a/node_modules/vite/src/node/server/ws.ts b/node_modules/vite/src/node/server/ws.ts new file mode 100644 index 0000000..eac4633 --- /dev/null +++ b/node_modules/vite/src/node/server/ws.ts @@ -0,0 +1,131 @@ +import chalk from 'chalk' +import { Server, STATUS_CODES } from 'http' +import { + createServer as createHttpsServer, + ServerOptions as HttpsServerOptions +} from 'https' +import WebSocket from 'ws' +import { ErrorPayload, HMRPayload } from 'types/hmrPayload' +import { ResolvedConfig } from '..' +import { isObject } from '../utils' +import { Socket } from 'net' +export const HMR_HEADER = 'vite-hmr' + +export interface WebSocketServer { + send(payload: HMRPayload): void + close(): Promise +} + +export function createWebSocketServer( + server: Server | null, + config: ResolvedConfig, + httpsOptions?: HttpsServerOptions +): WebSocketServer { + let wss: WebSocket.Server + let httpsServer: Server | undefined = undefined + + const hmr = isObject(config.server.hmr) && config.server.hmr + const wsServer = (hmr && hmr.server) || server + + if (wsServer) { + wss = new WebSocket.Server({ noServer: true }) + wsServer.on('upgrade', (req, socket, head) => { + if (req.headers['sec-websocket-protocol'] === HMR_HEADER) { + wss.handleUpgrade(req, socket as Socket, head, (ws) => { + wss.emit('connection', ws, req) + }) + } + }) + } else { + const websocketServerOptions: WebSocket.ServerOptions = {} + const port = (hmr && hmr.port) || 24678 + if (httpsOptions) { + // if we're serving the middlewares over https, the ws library doesn't support automatically creating an https server, so we need to do it ourselves + // create an inline https server and mount the websocket server to it + httpsServer = createHttpsServer(httpsOptions, (req, res) => { + const statusCode = 426 + const body = STATUS_CODES[statusCode] + if (!body) + throw new Error( + `No body text found for the ${statusCode} status code` + ) + + res.writeHead(statusCode, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }) + res.end(body) + }) + + httpsServer.listen(port) + websocketServerOptions.server = httpsServer + } else { + // we don't need to serve over https, just let ws handle its own server + websocketServerOptions.port = port + } + + // vite dev server in middleware mode + wss = new WebSocket.Server(websocketServerOptions) + } + + wss.on('connection', (socket) => { + socket.send(JSON.stringify({ type: 'connected' })) + if (bufferedError) { + socket.send(JSON.stringify(bufferedError)) + bufferedError = null + } + }) + + wss.on('error', (e: Error & { code: string }) => { + if (e.code !== 'EADDRINUSE') { + config.logger.error( + chalk.red(`WebSocket server error:\n${e.stack || e.message}`), + { error: e } + ) + } + }) + + // On page reloads, if a file fails to compile and returns 500, the server + // sends the error payload before the client connection is established. + // If we have no open clients, buffer the error and send it to the next + // connected client. + let bufferedError: ErrorPayload | null = null + + return { + send(payload: HMRPayload) { + if (payload.type === 'error' && !wss.clients.size) { + bufferedError = payload + return + } + + const stringified = JSON.stringify(payload) + wss.clients.forEach((client) => { + if (client.readyState === WebSocket.OPEN) { + client.send(stringified) + } + }) + }, + + close() { + return new Promise((resolve, reject) => { + wss.close((err) => { + if (err) { + reject(err) + } else { + if (httpsServer) { + httpsServer.close((err) => { + if (err) { + reject(err) + } else { + resolve() + } + }) + } else { + resolve() + } + } + }) + }) + } + } +} diff --git a/node_modules/vite/src/node/ssr/__tests__/ssrTransform.spec.ts b/node_modules/vite/src/node/ssr/__tests__/ssrTransform.spec.ts new file mode 100644 index 0000000..d3320a0 --- /dev/null +++ b/node_modules/vite/src/node/ssr/__tests__/ssrTransform.spec.ts @@ -0,0 +1,309 @@ +import { traverseHtml } from '../../plugins/html' +import { ssrTransform } from '../ssrTransform' + +test('default import', async () => { + expect( + ( + await ssrTransform( + `import foo from 'vue';console.log(foo.bar)`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); + console.log(__vite_ssr_import_0__.default.bar)" + `) +}) + +test('named import', async () => { + expect( + ( + await ssrTransform( + `import { ref } from 'vue';function foo() { return ref(0) }`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); + function foo() { return __vite_ssr_import_0__.ref(0) }" + `) +}) + +test('namespace import', async () => { + expect( + ( + await ssrTransform( + `import * as vue from 'vue';function foo() { return vue.ref(0) }`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); + function foo() { return __vite_ssr_import_0__.ref(0) }" + `) +}) + +test('export function declaration', async () => { + expect((await ssrTransform(`export function foo() {}`, null, null)).code) + .toMatchInlineSnapshot(` + "function foo() {} + Object.defineProperty(__vite_ssr_exports__, \\"foo\\", { enumerable: true, configurable: true, get(){ return foo }});" + `) +}) + +test('export class declaration', async () => { + expect((await ssrTransform(`export class foo {}`, null, null)).code) + .toMatchInlineSnapshot(` + "class foo {} + Object.defineProperty(__vite_ssr_exports__, \\"foo\\", { enumerable: true, configurable: true, get(){ return foo }});" + `) +}) + +test('export var declaration', async () => { + expect((await ssrTransform(`export const a = 1, b = 2`, null, null)).code) + .toMatchInlineSnapshot(` + "const a = 1, b = 2 + Object.defineProperty(__vite_ssr_exports__, \\"a\\", { enumerable: true, configurable: true, get(){ return a }}); + Object.defineProperty(__vite_ssr_exports__, \\"b\\", { enumerable: true, configurable: true, get(){ return b }});" + `) +}) + +test('export named', async () => { + expect( + (await ssrTransform(`const a = 1, b = 2; export { a, b as c }`, null, null)) + .code + ).toMatchInlineSnapshot(` + "const a = 1, b = 2; + Object.defineProperty(__vite_ssr_exports__, \\"a\\", { enumerable: true, configurable: true, get(){ return a }}); + Object.defineProperty(__vite_ssr_exports__, \\"c\\", { enumerable: true, configurable: true, get(){ return b }});" + `) +}) + +test('export named from', async () => { + expect( + (await ssrTransform(`export { ref, computed as c } from 'vue'`, null, null)) + .code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); + + Object.defineProperty(__vite_ssr_exports__, \\"ref\\", { enumerable: true, configurable: true, get(){ return __vite_ssr_import_0__.ref }}); + Object.defineProperty(__vite_ssr_exports__, \\"c\\", { enumerable: true, configurable: true, get(){ return __vite_ssr_import_0__.computed }});" + `) +}) + +test('named exports of imported binding', async () => { + expect( + ( + await ssrTransform( + `import {createApp} from 'vue';export {createApp}`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); + + Object.defineProperty(__vite_ssr_exports__, \\"createApp\\", { enumerable: true, configurable: true, get(){ return __vite_ssr_import_0__.createApp }});" + `) +}) + +test('export * from', async () => { + expect( + ( + await ssrTransform( + `export * from 'vue'\n` + `export * from 'react'`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); + __vite_ssr_exportAll__(__vite_ssr_import_0__); + const __vite_ssr_import_1__ = await __vite_ssr_import__(\\"react\\"); + __vite_ssr_exportAll__(__vite_ssr_import_1__);" + `) +}) + +test('export * as from', async () => { + expect((await ssrTransform(`export * as foo from 'vue'`, null, null)).code) + .toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); + + Object.defineProperty(__vite_ssr_exports__, \\"foo\\", { enumerable: true, configurable: true, get(){ return __vite_ssr_import_0__ }});" + `) +}) + +test('export default', async () => { + expect( + (await ssrTransform(`export default {}`, null, null)).code + ).toMatchInlineSnapshot(`"__vite_ssr_exports__.default = {}"`) +}) + +test('import.meta', async () => { + expect( + (await ssrTransform(`console.log(import.meta.url)`, null, null)).code + ).toMatchInlineSnapshot(`"console.log(__vite_ssr_import_meta__.url)"`) +}) + +test('dynamic import', async () => { + expect( + (await ssrTransform(`export const i = () => import('./foo')`, null, null)) + .code + ).toMatchInlineSnapshot(` + "const i = () => __vite_ssr_dynamic_import__('./foo') + Object.defineProperty(__vite_ssr_exports__, \\"i\\", { enumerable: true, configurable: true, get(){ return i }});" + `) +}) + +test('do not rewrite method definition', async () => { + expect( + ( + await ssrTransform( + `import { fn } from 'vue';class A { fn() { fn() } }`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); + class A { fn() { __vite_ssr_import_0__.fn() } }" + `) +}) + +test('do not rewrite catch clause', async () => { + expect( + ( + await ssrTransform( + `import {error} from './dependency';try {} catch(error) {}`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./dependency\\"); + try {} catch(error) {}" + `) +}) + +// #2221 +test('should declare variable for imported super class', async () => { + expect( + ( + await ssrTransform( + `import { Foo } from './dependency';` + `class A extends Foo {}`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./dependency\\"); + const Foo = __vite_ssr_import_0__.Foo; + class A extends Foo {}" + `) + + // exported classes: should prepend the declaration at root level, before the + // first class that uses the binding + expect( + ( + await ssrTransform( + `import { Foo } from './dependency';` + + `export default class A extends Foo {}\n` + + `export class B extends Foo {}`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./dependency\\"); + const Foo = __vite_ssr_import_0__.Foo; + class A extends Foo {} + class B extends Foo {} + Object.defineProperty(__vite_ssr_exports__, \\"default\\", { enumerable: true, value: A }); + Object.defineProperty(__vite_ssr_exports__, \\"B\\", { enumerable: true, configurable: true, get(){ return B }});" + `) +}) + +// #4049 +test('should handle default export variants', async () => { + // default anonymous functions + expect( + (await ssrTransform(`export default function() {}\n`, null, null)).code + ).toMatchInlineSnapshot(` + "__vite_ssr_exports__.default = function() {} + " + `) + // default anonymous class + expect((await ssrTransform(`export default class {}\n`, null, null)).code) + .toMatchInlineSnapshot(` + "__vite_ssr_exports__.default = class {} + " + `) + // default named functions + expect( + ( + await ssrTransform( + `export default function foo() {}\n` + + `foo.prototype = Object.prototype;`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "function foo() {} + foo.prototype = Object.prototype; + Object.defineProperty(__vite_ssr_exports__, \\"default\\", { enumerable: true, value: foo });" + `) + // default named classes + expect( + ( + await ssrTransform( + `export default class A {}\n` + `export class B extends A {}`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "class A {} + class B extends A {} + Object.defineProperty(__vite_ssr_exports__, \\"default\\", { enumerable: true, value: A }); + Object.defineProperty(__vite_ssr_exports__, \\"B\\", { enumerable: true, configurable: true, get(){ return B }});" + `) +}) + +test('sourcemap source', async () => { + expect( + (await ssrTransform(`export const a = 1`, null, 'input.js')).map.sources + ).toStrictEqual(['input.js']) +}) + +test('overwrite bindings', async () => { + expect( + ( + await ssrTransform( + `import { inject } from 'vue';` + + `const a = { inject }\n` + + `const b = { test: inject }\n` + + `function c() { const { test: inject } = { test: true }; console.log(inject) }\n` + + `const d = inject \n` + + `function f() { console.log(inject) }\n` + + `function e() { const { inject } = { inject: true } }\n` + + `function g() { const f = () => { const inject = true }; console.log(inject) }\n`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); + const a = { inject: __vite_ssr_import_0__.inject } + const b = { test: __vite_ssr_import_0__.inject } + function c() { const { test: inject } = { test: true }; console.log(inject) } + const d = __vite_ssr_import_0__.inject + function f() { console.log(__vite_ssr_import_0__.inject) } + function e() { const { inject } = { inject: true } } + function g() { const f = () => { const inject = true }; console.log(__vite_ssr_import_0__.inject) } + " + `) +}) diff --git a/node_modules/vite/src/node/ssr/ssrExternal.ts b/node_modules/vite/src/node/ssr/ssrExternal.ts new file mode 100644 index 0000000..0ef48c1 --- /dev/null +++ b/node_modules/vite/src/node/ssr/ssrExternal.ts @@ -0,0 +1,147 @@ +import fs from 'fs' +import path from 'path' +import { tryNodeResolve, InternalResolveOptions } from '../plugins/resolve' +import { isDefined, lookupFile, resolveFrom, unique } from '../utils' +import { ResolvedConfig } from '..' +import { createFilter } from '@rollup/pluginutils' + +/** + * Heuristics for determining whether a dependency should be externalized for + * server-side rendering. + * + * TODO right now externals are imported using require(), we probably need to + * rework this when more libraries ship native ESM distributions for Node. + */ +export function resolveSSRExternal( + config: ResolvedConfig, + knownImports: string[], + ssrExternals: Set = new Set(), + seen: Set = new Set() +): string[] { + if (config.ssr?.noExternal === true) { + return [] + } + + const { root } = config + const pkgContent = lookupFile(root, ['package.json']) + if (!pkgContent) { + return [] + } + const pkg = JSON.parse(pkgContent) + const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined) + const deps = unique([ + ...importedDeps, + ...Object.keys(pkg.devDependencies || {}), + ...Object.keys(pkg.dependencies || {}) + ]) + + const resolveOptions: InternalResolveOptions = { + root, + isProduction: false, + isBuild: true + } + + const depsToTrace = new Set() + + for (const id of deps) { + if (seen.has(id)) { + continue + } + seen.add(id) + + let entry: string | undefined + let requireEntry: string + try { + entry = tryNodeResolve( + id, + undefined, + resolveOptions, + true, + undefined, + true + )?.id + requireEntry = require.resolve(id, { paths: [root] }) + } catch (e) { + // resolve failed, assume include + continue + } + if (!entry) { + // no esm entry but has require entry (is this even possible?) + ssrExternals.add(id) + continue + } + if (!entry.includes('node_modules')) { + // entry is not a node dep, possibly linked - don't externalize + // instead, trace its dependencies. + depsToTrace.add(id) + continue + } + if (entry !== requireEntry) { + // has separate esm/require entry, assume require entry is cjs + ssrExternals.add(id) + } else { + // node resolve and esm resolve resolves to the same file. + if (!/\.m?js$/.test(entry)) { + // entry is not js, cannot externalize + continue + } + // check if the entry is cjs + const content = fs.readFileSync(entry, 'utf-8') + if (/\bmodule\.exports\b|\bexports[.\[]|\brequire\s*\(/.test(content)) { + ssrExternals.add(id) + } + } + } + + for (const id of depsToTrace) { + const depRoot = path.dirname(resolveFrom(`${id}/package.json`, root)) + resolveSSRExternal( + { + ...config, + root: depRoot + }, + knownImports, + ssrExternals, + seen + ) + } + + if (config.ssr?.external) { + config.ssr.external.forEach((id) => ssrExternals.add(id)) + } + let externals = [...ssrExternals] + if (config.ssr?.noExternal) { + const filter = createFilter(undefined, config.ssr.noExternal, { + resolve: false + }) + externals = externals.filter((id) => filter(id)) + } + return externals.filter((id) => id !== 'vite') +} + +export function shouldExternalizeForSSR( + id: string, + externals: string[] +): boolean { + const should = externals.some((e) => { + if (id === e) { + return true + } + // deep imports, check ext before externalizing - only externalize + // extension-less imports and explicit .js imports + if (id.startsWith(e + '/') && (!path.extname(id) || id.endsWith('.js'))) { + return true + } + }) + return should +} + +function getNpmPackageName(importPath: string): string | null { + const parts = importPath.split('/') + if (parts[0].startsWith('@')) { + if (!parts[1]) return null + return `${parts[0]}/${parts[1]}` + } else { + return parts[0] + } +} diff --git a/node_modules/vite/src/node/ssr/ssrManifestPlugin.ts b/node_modules/vite/src/node/ssr/ssrManifestPlugin.ts new file mode 100644 index 0000000..d137f72 --- /dev/null +++ b/node_modules/vite/src/node/ssr/ssrManifestPlugin.ts @@ -0,0 +1,53 @@ +import { relative } from 'path' +import { normalizePath } from '@rollup/pluginutils' +import { ResolvedConfig } from '..' +import { Plugin } from '../plugin' +import { chunkToEmittedCssFileMap } from '../plugins/css' +import { chunkToEmittedAssetsMap } from '../plugins/asset' + +export function ssrManifestPlugin(config: ResolvedConfig): Plugin { + // module id => preload assets mapping + const ssrManifest: Record = {} + const base = config.base + + return { + name: 'vite:manifest', + generateBundle(_options, bundle) { + for (const file in bundle) { + const chunk = bundle[file] + if (chunk.type === 'chunk') { + // links for certain entry chunks are already generated in static HTML + // in those cases we only need to record info for non-entry chunks + const cssFiles = chunk.isEntry + ? null + : chunkToEmittedCssFileMap.get(chunk) + const assetFiles = chunkToEmittedAssetsMap.get(chunk) + for (const id in chunk.modules) { + const normalizedId = normalizePath(relative(config.root, id)) + const mappedChunks = + ssrManifest[normalizedId] || (ssrManifest[normalizedId] = []) + if (!chunk.isEntry) { + mappedChunks.push(base + chunk.fileName) + } + if (cssFiles) { + cssFiles.forEach((file) => { + mappedChunks.push(base + file) + }) + } + if (assetFiles) { + assetFiles.forEach((file) => { + mappedChunks.push(base + file) + }) + } + } + } + } + + this.emitFile({ + fileName: 'ssr-manifest.json', + type: 'asset', + source: JSON.stringify(ssrManifest, null, 2) + }) + } + } +} diff --git a/node_modules/vite/src/node/ssr/ssrModuleLoader.ts b/node_modules/vite/src/node/ssr/ssrModuleLoader.ts new file mode 100644 index 0000000..6a64d6a --- /dev/null +++ b/node_modules/vite/src/node/ssr/ssrModuleLoader.ts @@ -0,0 +1,199 @@ +import fs from 'fs' +import path from 'path' +import { ViteDevServer } from '..' +import { cleanUrl, resolveFrom, unwrapId } from '../utils' +import { rebindErrorStacktrace, ssrRewriteStacktrace } from './ssrStacktrace' +import { + ssrExportAllKey, + ssrModuleExportsKey, + ssrImportKey, + ssrImportMetaKey, + ssrDynamicImportKey +} from './ssrTransform' +import { transformRequest } from '../server/transformRequest' + +interface SSRContext { + global: NodeJS.Global +} + +type SSRModule = Record + +const pendingModules = new Map>() +const pendingImports = new Map() + +export async function ssrLoadModule( + url: string, + server: ViteDevServer, + context: SSRContext = { global }, + urlStack: string[] = [] +): Promise { + url = unwrapId(url) + + // when we instantiate multiple dependency modules in parallel, they may + // point to shared modules. We need to avoid duplicate instantiation attempts + // by register every module as pending synchronously so that all subsequent + // request to that module are simply waiting on the same promise. + const pending = pendingModules.get(url) + if (pending) { + return pending + } + + const modulePromise = instantiateModule(url, server, context, urlStack) + pendingModules.set(url, modulePromise) + modulePromise + .catch(() => { + pendingImports.delete(url) + }) + .finally(() => { + pendingModules.delete(url) + }) + return modulePromise +} + +async function instantiateModule( + url: string, + server: ViteDevServer, + context: SSRContext = { global }, + urlStack: string[] = [] +): Promise { + const { moduleGraph } = server + const mod = await moduleGraph.ensureEntryFromUrl(url) + + if (mod.ssrModule) { + return mod.ssrModule + } + + const result = + mod.ssrTransformResult || + (await transformRequest(url, server, { ssr: true })) + if (!result) { + // TODO more info? is this even necessary? + throw new Error(`failed to load module for ssr: ${url}`) + } + + const ssrModule = { + [Symbol.toStringTag]: 'Module' + } + Object.defineProperty(ssrModule, '__esModule', { value: true }) + + // Tolerate circular imports by ensuring the module can be + // referenced before it's been instantiated. + mod.ssrModule = ssrModule + + const ssrImportMeta = { url } + + urlStack = urlStack.concat(url) + const isCircular = (url: string) => urlStack.includes(url) + + // Since dynamic imports can happen in parallel, we need to + // account for multiple pending deps and duplicate imports. + const pendingDeps: string[] = [] + + const ssrImport = async (dep: string) => { + if (dep[0] !== '.' && dep[0] !== '/') { + return nodeRequire(dep, mod.file, server.config.root) + } + dep = unwrapId(dep) + if (!isCircular(dep) && !pendingImports.get(dep)?.some(isCircular)) { + pendingDeps.push(dep) + if (pendingDeps.length === 1) { + pendingImports.set(url, pendingDeps) + } + await ssrLoadModule(dep, server, context, urlStack) + if (pendingDeps.length === 1) { + pendingImports.delete(url) + } else { + pendingDeps.splice(pendingDeps.indexOf(dep), 1) + } + } + return moduleGraph.urlToModuleMap.get(dep)?.ssrModule + } + + const ssrDynamicImport = (dep: string) => { + // #3087 dynamic import vars is ignored at rewrite import path, + // so here need process relative path + if (dep[0] === '.') { + dep = path.posix.resolve(path.dirname(url), dep) + } + return ssrImport(dep) + } + + function ssrExportAll(sourceModule: any) { + for (const key in sourceModule) { + if (key !== 'default') { + Object.defineProperty(ssrModule, key, { + enumerable: true, + configurable: true, + get() { + return sourceModule[key] + } + }) + } + } + } + + try { + // eslint-disable-next-line @typescript-eslint/no-empty-function + const AsyncFunction = async function () {}.constructor as typeof Function + const initModule = new AsyncFunction( + `global`, + ssrModuleExportsKey, + ssrImportMetaKey, + ssrImportKey, + ssrDynamicImportKey, + ssrExportAllKey, + result.code + `\n//# sourceURL=${mod.url}` + ) + await initModule( + context.global, + ssrModule, + ssrImportMeta, + ssrImport, + ssrDynamicImport, + ssrExportAll + ) + } catch (e) { + const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph) + rebindErrorStacktrace(e, stacktrace) + server.config.logger.error( + `Error when evaluating SSR module ${url}:\n${stacktrace}`, + { + timestamp: true, + clear: server.config.clearScreen, + error: e + } + ) + throw e + } + + return Object.freeze(ssrModule) +} + +function nodeRequire(id: string, importer: string | null, root: string) { + const mod = require(resolve(id, importer, root)) + const defaultExport = mod.__esModule ? mod.default : mod + // rollup-style default import interop for cjs + return new Proxy(mod, { + get(mod, prop) { + if (prop === 'default') return defaultExport + return mod[prop] + } + }) +} + +const resolveCache = new Map() + +function resolve(id: string, importer: string | null, root: string) { + const key = id + importer + root + const cached = resolveCache.get(key) + if (cached) { + return cached + } + const resolveDir = + importer && fs.existsSync(cleanUrl(importer)) + ? path.dirname(importer) + : root + const resolved = resolveFrom(id, resolveDir, true) + resolveCache.set(key, resolved) + return resolved +} diff --git a/node_modules/vite/src/node/ssr/ssrStacktrace.ts b/node_modules/vite/src/node/ssr/ssrStacktrace.ts new file mode 100644 index 0000000..23fd7d0 --- /dev/null +++ b/node_modules/vite/src/node/ssr/ssrStacktrace.ts @@ -0,0 +1,75 @@ +import { SourceMapConsumer, RawSourceMap } from 'source-map' +import { ModuleGraph } from '../server/moduleGraph' + +let offset: number +try { + new Function('throw new Error(1)')() +} catch (e) { + // in Node 12, stack traces account for the function wrapper. + // in Node 13 and later, the function wrapper adds two lines, + // which must be subtracted to generate a valid mapping + const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]) + offset = match ? +match[1] - 1 : 0 +} + +export function ssrRewriteStacktrace( + stack: string, + moduleGraph: ModuleGraph +): string { + return stack + .split('\n') + .map((line) => { + return line.replace( + /^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/, + (input, varName, url, line, column) => { + if (!url) return input + + const mod = moduleGraph.urlToModuleMap.get(url) + const rawSourceMap = mod?.ssrTransformResult?.map + + if (!rawSourceMap) { + return input + } + + const consumer = new SourceMapConsumer( + rawSourceMap as unknown as RawSourceMap + ) + + const pos = consumer.originalPositionFor({ + line: Number(line) - offset, + column: Number(column), + bias: SourceMapConsumer.LEAST_UPPER_BOUND + }) + + if (!pos.source) { + return input + } + + const source = `${pos.source}:${pos.line || 0}:${pos.column || 0}` + if (!varName || varName === 'eval') { + return ` at ${source}` + } else { + return ` at ${varName} (${source})` + } + } + ) + }) + .join('\n') +} + +export function rebindErrorStacktrace(e: Error, stacktrace: string): void { + const { configurable, writable } = Object.getOwnPropertyDescriptor( + e, + 'stack' + )! + if (configurable) { + Object.defineProperty(e, 'stack', { + value: stacktrace, + enumerable: true, + configurable: true, + writable: true + }) + } else if (writable) { + e.stack = stacktrace + } +} diff --git a/node_modules/vite/src/node/ssr/ssrTransform.ts b/node_modules/vite/src/node/ssr/ssrTransform.ts new file mode 100644 index 0000000..c5d87e8 --- /dev/null +++ b/node_modules/vite/src/node/ssr/ssrTransform.ts @@ -0,0 +1,447 @@ +import MagicString from 'magic-string' +import { SourceMap } from 'rollup' +import { TransformResult } from '../server/transformRequest' +import { parser } from '../server/pluginContainer' +import { + Identifier, + Node as _Node, + Property, + Function as FunctionNode +} from 'estree' +import { extract_names as extractNames } from 'periscopic' +import { walk as eswalk } from 'estree-walker' +import { combineSourcemaps } from '../utils' +import { RawSourceMap } from '@ampproject/remapping/dist/types/types' + +type Node = _Node & { + start: number + end: number +} + +export const ssrModuleExportsKey = `__vite_ssr_exports__` +export const ssrImportKey = `__vite_ssr_import__` +export const ssrDynamicImportKey = `__vite_ssr_dynamic_import__` +export const ssrExportAllKey = `__vite_ssr_exportAll__` +export const ssrImportMetaKey = `__vite_ssr_import_meta__` + +export async function ssrTransform( + code: string, + inMap: SourceMap | null, + url: string +): Promise { + const s = new MagicString(code) + + const ast = parser.parse(code, { + sourceType: 'module', + ecmaVersion: 2021, + locations: true + }) as any + + let uid = 0 + const deps = new Set() + const idToImportMap = new Map() + const declaredConst = new Set() + + function defineImport(node: Node, source: string) { + deps.add(source) + const importId = `__vite_ssr_import_${uid++}__` + s.appendLeft( + node.start, + `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\n` + ) + return importId + } + + function defineExport(position: number, name: string, local = name) { + s.appendRight( + position, + `\nObject.defineProperty(${ssrModuleExportsKey}, "${name}", ` + + `{ enumerable: true, configurable: true, get(){ return ${local} }});` + ) + } + + // 1. check all import statements and record id -> importName map + for (const node of ast.body as Node[]) { + // import foo from 'foo' --> foo -> __import_foo__.default + // import { baz } from 'foo' --> baz -> __import_foo__.baz + // import * as ok from 'foo' --> ok -> __import_foo__ + if (node.type === 'ImportDeclaration') { + const importId = defineImport(node, node.source.value as string) + for (const spec of node.specifiers) { + if (spec.type === 'ImportSpecifier') { + idToImportMap.set( + spec.local.name, + `${importId}.${spec.imported.name}` + ) + } else if (spec.type === 'ImportDefaultSpecifier') { + idToImportMap.set(spec.local.name, `${importId}.default`) + } else { + // namespace specifier + idToImportMap.set(spec.local.name, importId) + } + } + s.remove(node.start, node.end) + } + } + + // 2. check all export statements and define exports + for (const node of ast.body as Node[]) { + // named exports + if (node.type === 'ExportNamedDeclaration') { + if (node.declaration) { + if ( + node.declaration.type === 'FunctionDeclaration' || + node.declaration.type === 'ClassDeclaration' + ) { + // export function foo() {} + defineExport(node.end, node.declaration.id!.name) + } else { + // export const foo = 1, bar = 2 + for (const declaration of node.declaration.declarations) { + const names = extractNames(declaration.id as any) + for (const name of names) { + defineExport(node.end, name) + } + } + } + s.remove(node.start, (node.declaration as Node).start) + } else { + s.remove(node.start, node.end) + if (node.source) { + // export { foo, bar } from './foo' + const importId = defineImport(node, node.source.value as string) + for (const spec of node.specifiers) { + defineExport( + node.end, + spec.exported.name, + `${importId}.${spec.local.name}` + ) + } + } else { + // export { foo, bar } + for (const spec of node.specifiers) { + const local = spec.local.name + const binding = idToImportMap.get(local) + defineExport(node.end, spec.exported.name, binding || local) + } + } + } + } + + // default export + if (node.type === 'ExportDefaultDeclaration') { + if ('id' in node.declaration && node.declaration.id) { + // named hoistable/class exports + // export default function foo() {} + // export default class A {} + const { name } = node.declaration.id + s.remove(node.start, node.start + 15 /* 'export default '.length */) + s.append( + `\nObject.defineProperty(${ssrModuleExportsKey}, "default", ` + + `{ enumerable: true, value: ${name} });` + ) + } else { + // anonymous default exports + s.overwrite( + node.start, + node.start + 14 /* 'export default'.length */, + `${ssrModuleExportsKey}.default =` + ) + } + } + + // export * from './foo' + if (node.type === 'ExportAllDeclaration') { + if (node.exported) { + const importId = defineImport(node, node.source.value as string) + s.remove(node.start, node.end) + defineExport(node.end, node.exported.name, `${importId}`) + } else { + const importId = defineImport(node, node.source.value as string) + s.remove(node.start, node.end) + s.appendLeft(node.end, `${ssrExportAllKey}(${importId});`) + } + } + } + + // 3. convert references to import bindings & import.meta references + walk(ast, { + onIdentifier(id, parent, parentStack) { + const binding = idToImportMap.get(id.name) + if (!binding) { + return + } + if (isStaticProperty(parent) && parent.shorthand) { + // let binding used in a property shorthand + // { foo } -> { foo: __import_x__.foo } + // skip for destructuring patterns + if ( + !(parent as any).inPattern || + isInDestructuringAssignment(parent, parentStack) + ) { + s.appendLeft(id.end, `: ${binding}`) + } + } else if ( + parent.type === 'ClassDeclaration' && + id === parent.superClass + ) { + if (!declaredConst.has(id.name)) { + declaredConst.add(id.name) + // locate the top-most node containing the class declaration + const topNode = parentStack[1] + s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`) + } + } else { + s.overwrite(id.start, id.end, binding) + } + }, + onImportMeta(node) { + s.overwrite(node.start, node.end, ssrImportMetaKey) + }, + onDynamicImport(node) { + s.overwrite(node.start, node.start + 6, ssrDynamicImportKey) + } + }) + + let map = s.generateMap({ hires: true }) + if (inMap && inMap.mappings && inMap.sources.length > 0) { + map = combineSourcemaps(url, [ + { + ...map, + sources: inMap.sources, + sourcesContent: inMap.sourcesContent + } as RawSourceMap, + inMap as RawSourceMap + ]) as SourceMap + } else { + map.sources = [url] + map.sourcesContent = [code] + } + + return { + code: s.toString(), + map, + deps: [...deps] + } +} + +interface Visitors { + onIdentifier: ( + node: Identifier & { + start: number + end: number + }, + parent: Node, + parentStack: Node[] + ) => void + onImportMeta: (node: Node) => void + onDynamicImport: (node: Node) => void +} + +/** + * Same logic from \@vue/compiler-core & \@vue/compiler-sfc + * Except this is using acorn AST + */ +function walk( + root: Node, + { onIdentifier, onImportMeta, onDynamicImport }: Visitors +) { + const parentStack: Node[] = [] + const scope: Record = Object.create(null) + const scopeMap = new WeakMap<_Node, Set>() + + const setScope = (node: FunctionNode, name: string) => { + let scopeIds = scopeMap.get(node) + if (scopeIds && scopeIds.has(name)) { + return + } + if (name in scope) { + scope[name]++ + } else { + scope[name] = 1 + } + if (!scopeIds) { + scopeIds = new Set() + scopeMap.set(node, scopeIds) + } + scopeIds.add(name) + } + + ;(eswalk as any)(root, { + enter(node: Node, parent: Node | null) { + if (node.type === 'ImportDeclaration') { + return this.skip() + } + + parent && parentStack.push(parent) + + if (node.type === 'MetaProperty' && node.meta.name === 'import') { + onImportMeta(node) + } else if (node.type === 'ImportExpression') { + onDynamicImport(node) + } + + if (node.type === 'Identifier') { + if (!scope[node.name] && isRefIdentifier(node, parent!, parentStack)) { + onIdentifier(node, parent!, parentStack) + } + } else if (isFunction(node)) { + // walk function expressions and add its arguments to known identifiers + // so that we don't prefix them + node.params.forEach((p) => + (eswalk as any)(p, { + enter(child: Node, parent: Node) { + if ( + child.type === 'Identifier' && + // do not record as scope variable if is a destructuring key + !isStaticPropertyKey(child, parent) && + // do not record if this is a default value + // assignment of a destructuring variable + !( + parent && + parent.type === 'AssignmentPattern' && + parent.right === child + ) + ) { + setScope(node, child.name) + } + } + }) + ) + } else if (node.type === 'Property' && parent!.type === 'ObjectPattern') { + // mark property in destructuring pattern + ;(node as any).inPattern = true + } else if (node.type === 'VariableDeclarator') { + const parentFunction = findParentFunction(parentStack) + if (parentFunction) { + if (node.id.type === 'ObjectPattern') { + node.id.properties.forEach((property) => { + if (property.type === 'RestElement') { + setScope(parentFunction, (property.argument as Identifier).name) + } else { + setScope(parentFunction, (property.value as Identifier).name) + } + }) + } else { + setScope(parentFunction, (node.id as Identifier).name) + } + } + } + }, + + leave(node: Node, parent: Node | null) { + parent && parentStack.pop() + const scopeIds = scopeMap.get(node) + if (scopeIds) { + scopeIds.forEach((id: string) => { + scope[id]-- + if (scope[id] === 0) { + delete scope[id] + } + }) + } + } + }) +} + +function isRefIdentifier(id: Identifier, parent: _Node, parentStack: _Node[]) { + // declaration id + if ( + parent.type === 'CatchClause' || + ((parent.type === 'VariableDeclarator' || + parent.type === 'ClassDeclaration') && + parent.id === id) + ) { + return false + } + + if (isFunction(parent)) { + // function declaration/expression id + if ((parent as any).id === id) { + return false + } + // params list + if (parent.params.includes(id)) { + return false + } + } + + // class method name + if (parent.type === 'MethodDefinition') { + return false + } + + // property key + // this also covers object destructuring pattern + if (isStaticPropertyKey(id, parent) || (parent as any).inPattern) { + return false + } + + // non-assignment array destructuring pattern + if ( + parent.type === 'ArrayPattern' && + !isInDestructuringAssignment(parent, parentStack) + ) { + return false + } + + // member expression property + if ( + parent.type === 'MemberExpression' && + parent.property === id && + !parent.computed + ) { + return false + } + + if (parent.type === 'ExportSpecifier') { + return false + } + + // is a special keyword but parsed as identifier + if (id.name === 'arguments') { + return false + } + + return true +} + +const isStaticProperty = (node: _Node): node is Property => + node && node.type === 'Property' && !node.computed + +const isStaticPropertyKey = (node: _Node, parent: _Node) => + isStaticProperty(parent) && parent.key === node + +function isFunction(node: _Node): node is FunctionNode { + return /Function(?:Expression|Declaration)$|Method$/.test(node.type) +} + +function findParentFunction(parentStack: _Node[]): FunctionNode | undefined { + for (let i = parentStack.length - 1; i >= 0; i--) { + const node = parentStack[i] + if (isFunction(node)) { + return node + } + } +} + +function isInDestructuringAssignment( + parent: _Node, + parentStack: _Node[] +): boolean { + if ( + parent && + (parent.type === 'Property' || parent.type === 'ArrayPattern') + ) { + let i = parentStack.length + while (i--) { + const p = parentStack[i] + if (p.type === 'AssignmentExpression') { + return true + } else if (p.type !== 'Property' && !p.type.endsWith('Pattern')) { + break + } + } + } + return false +} diff --git a/node_modules/vite/src/node/tsconfig.json b/node_modules/vite/src/node/tsconfig.json new file mode 100644 index 0000000..456e6f2 --- /dev/null +++ b/node_modules/vite/src/node/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["./", "../../types"], + "exclude": ["**/__tests__"], + "compilerOptions": { + // compile away optional-chaining-operator + // node support table: https://node.green/#ES2020-features-optional-chaining-operator----- + "target": "ES2019", + "outDir": "../../dist/node", + "module": "commonjs", + "lib": ["ESNext"], + "sourceMap": true + } +} diff --git a/node_modules/vite/src/node/utils.ts b/node_modules/vite/src/node/utils.ts new file mode 100644 index 0000000..d43661a --- /dev/null +++ b/node_modules/vite/src/node/utils.ts @@ -0,0 +1,554 @@ +import debug from 'debug' +import chalk from 'chalk' +import fs from 'fs' +import os from 'os' +import path from 'path' +import { pathToFileURL, URL } from 'url' +import { + FS_PREFIX, + DEFAULT_EXTENSIONS, + VALID_ID_PREFIX, + CLIENT_PUBLIC_PATH, + ENV_PUBLIC_PATH +} from './constants' +import resolve from 'resolve' +import builtins from 'builtin-modules' +import { FSWatcher } from 'chokidar' +import remapping from '@ampproject/remapping' +import { + DecodedSourceMap, + RawSourceMap +} from '@ampproject/remapping/dist/types/types' + +export function slash(p: string): string { + return p.replace(/\\/g, '/') +} + +// Strip valid id prefix. This is prepended to resolved Ids that are +// not valid browser import specifiers by the importAnalysis plugin. +export function unwrapId(id: string): string { + return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length) : id +} + +export const flattenId = (id: string): string => + id.replace(/(\s*>\s*)/g, '__').replace(/[\/\.]/g, '_') + +export const normalizeId = (id: string): string => + id.replace(/(\s*>\s*)/g, ' > ') + +export function isBuiltin(id: string): boolean { + return builtins.includes(id) +} + +export const bareImportRE = /^[\w@](?!.*:\/\/)/ +export const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\// + +export let isRunningWithYarnPnp: boolean +try { + isRunningWithYarnPnp = Boolean(require('pnpapi')) +} catch {} + +const ssrExtensions = ['.js', '.cjs', '.json', '.node'] + +export function resolveFrom(id: string, basedir: string, ssr = false): string { + return resolve.sync(id, { + basedir, + extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS, + // necessary to work with pnpm + preserveSymlinks: isRunningWithYarnPnp || false + }) +} + +/** + * like `resolveFrom` but supports resolving `>` path in `id`, + * for example: `foo > bar > baz` + */ +export function nestedResolveFrom(id: string, basedir: string): string { + const pkgs = id.split('>').map((pkg) => pkg.trim()) + try { + for (const pkg of pkgs) { + basedir = resolveFrom(pkg, basedir) + } + } catch {} + return basedir +} + +// set in bin/vite.js +const filter = process.env.VITE_DEBUG_FILTER + +const DEBUG = process.env.DEBUG + +interface DebuggerOptions { + onlyWhenFocused?: boolean | string +} + +export type ViteDebugScope = `vite:${string}` + +export function createDebugger( + namespace: ViteDebugScope, + options: DebuggerOptions = {} +): debug.Debugger['log'] { + const log = debug(namespace) + const { onlyWhenFocused } = options + const focus = + typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace + return (msg: string, ...args: any[]) => { + if (filter && !msg.includes(filter)) { + return + } + if (onlyWhenFocused && !DEBUG?.includes(focus)) { + return + } + log(msg, ...args) + } +} + +export const isWindows = os.platform() === 'win32' +const VOLUME_RE = /^[A-Z]:/i + +export function normalizePath(id: string): string { + return path.posix.normalize(isWindows ? slash(id) : id) +} + +export function fsPathFromId(id: string): string { + const fsPath = normalizePath(id.slice(FS_PREFIX.length)) + return fsPath.startsWith('/') || fsPath.match(VOLUME_RE) + ? fsPath + : `/${fsPath}` +} + +export function ensureVolumeInPath(file: string): string { + return isWindows ? path.resolve(file) : file +} + +export const queryRE = /\?.*$/s +export const hashRE = /#.*$/s + +export const cleanUrl = (url: string): string => + url.replace(hashRE, '').replace(queryRE, '') + +export const externalRE = /^(https?:)?\/\// +export const isExternalUrl = (url: string): boolean => externalRE.test(url) + +export const dataUrlRE = /^\s*data:/i +export const isDataUrl = (url: string): boolean => dataUrlRE.test(url) + +const knownJsSrcRE = /\.((j|t)sx?|mjs|vue|marko|svelte)($|\?)/ +export const isJSRequest = (url: string): boolean => { + url = cleanUrl(url) + if (knownJsSrcRE.test(url)) { + return true + } + if (!path.extname(url) && !url.endsWith('/')) { + return true + } + return false +} + +const importQueryRE = /(\?|&)import=?(?:&|$)/ +const internalPrefixes = [ + FS_PREFIX, + VALID_ID_PREFIX, + CLIENT_PUBLIC_PATH, + ENV_PUBLIC_PATH +] +const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`) +const trailingSeparatorRE = /[\?&]$/ +export const isImportRequest = (url: string): boolean => importQueryRE.test(url) +export const isInternalRequest = (url: string): boolean => + InternalPrefixRE.test(url) + +export function removeImportQuery(url: string): string { + return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, '') +} + +export function injectQuery(url: string, queryToInject: string): string { + // encode percents for consistent behavior with pathToFileURL + // see #2614 for details + let resolvedUrl = new URL(url.replace(/%/g, '%25'), 'relative:///') + if (resolvedUrl.protocol !== 'relative:') { + resolvedUrl = pathToFileURL(url) + } + let { protocol, pathname, search, hash } = resolvedUrl + if (protocol === 'file:') { + pathname = pathname.slice(1) + } + pathname = decodeURIComponent(pathname) + return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${ + hash || '' + }` +} + +const timestampRE = /\bt=\d{13}&?\b/ +export function removeTimestampQuery(url: string): string { + return url.replace(timestampRE, '').replace(trailingSeparatorRE, '') +} + +export async function asyncReplace( + input: string, + re: RegExp, + replacer: (match: RegExpExecArray) => string | Promise +): Promise { + let match: RegExpExecArray | null + let remaining = input + let rewritten = '' + while ((match = re.exec(remaining))) { + rewritten += remaining.slice(0, match.index) + rewritten += await replacer(match) + remaining = remaining.slice(match.index + match[0].length) + } + rewritten += remaining + return rewritten +} + +export function timeFrom(start: number, subtract = 0): string { + const time: number | string = Date.now() - start - subtract + const timeString = (time + `ms`).padEnd(5, ' ') + if (time < 10) { + return chalk.green(timeString) + } else if (time < 50) { + return chalk.yellow(timeString) + } else { + return chalk.red(timeString) + } +} + +/** + * pretty url for logging. + */ +export function prettifyUrl(url: string, root: string): string { + url = removeTimestampQuery(url) + const isAbsoluteFile = url.startsWith(root) + if (isAbsoluteFile || url.startsWith(FS_PREFIX)) { + let file = path.relative(root, isAbsoluteFile ? url : fsPathFromId(url)) + const seg = file.split('/') + const npmIndex = seg.indexOf(`node_modules`) + const isSourceMap = file.endsWith('.map') + if (npmIndex > 0) { + file = seg[npmIndex + 1] + if (file.startsWith('@')) { + file = `${file}/${seg[npmIndex + 2]}` + } + file = `npm: ${chalk.dim(file)}${isSourceMap ? ` (source map)` : ``}` + } + return chalk.dim(file) + } else { + return chalk.dim(url) + } +} + +export function isObject(value: unknown): value is Record { + return Object.prototype.toString.call(value) === '[object Object]' +} + +export function isDefined(value: T | undefined | null): value is T { + return value != null +} + +export function lookupFile( + dir: string, + formats: string[], + pathOnly = false +): string | undefined { + for (const format of formats) { + const fullPath = path.join(dir, format) + if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) { + return pathOnly ? fullPath : fs.readFileSync(fullPath, 'utf-8') + } + } + const parentDir = path.dirname(dir) + if (parentDir !== dir) { + return lookupFile(parentDir, formats, pathOnly) + } +} + +const splitRE = /\r?\n/ + +const range: number = 2 + +export function pad(source: string, n = 2): string { + const lines = source.split(splitRE) + return lines.map((l) => ` `.repeat(n) + l).join(`\n`) +} + +export function posToNumber( + source: string, + pos: number | { line: number; column: number } +): number { + if (typeof pos === 'number') return pos + const lines = source.split(splitRE) + const { line, column } = pos + let start = 0 + for (let i = 0; i < line - 1; i++) { + start += lines[i].length + 1 + } + return start + column +} + +export function numberToPos( + source: string, + offset: number | { line: number; column: number } +): { line: number; column: number } { + if (typeof offset !== 'number') return offset + if (offset > source.length) { + throw new Error('offset is longer than source length!') + } + const lines = source.split(splitRE) + let counted = 0 + let line = 0 + let column = 0 + for (; line < lines.length; line++) { + const lineLength = lines[line].length + 1 + if (counted + lineLength >= offset) { + column = offset - counted + 1 + break + } + counted += lineLength + } + return { line: line + 1, column } +} + +export function generateCodeFrame( + source: string, + start: number | { line: number; column: number } = 0, + end?: number +): string { + start = posToNumber(source, start) + end = end || start + const lines = source.split(splitRE) + let count = 0 + const res: string[] = [] + for (let i = 0; i < lines.length; i++) { + count += lines[i].length + 1 + if (count >= start) { + for (let j = i - range; j <= i + range || end > count; j++) { + if (j < 0 || j >= lines.length) continue + const line = j + 1 + res.push( + `${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${ + lines[j] + }` + ) + const lineLength = lines[j].length + if (j === i) { + // push underline + const pad = start - (count - lineLength) + 1 + const length = Math.max( + 1, + end > count ? lineLength - pad : end - start + ) + res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)) + } else if (j > i) { + if (end > count) { + const length = Math.max(Math.min(end - count, lineLength), 1) + res.push(` | ` + '^'.repeat(length)) + } + count += lineLength + 1 + } + } + break + } + } + return res.join('\n') +} + +export function writeFile( + filename: string, + content: string | Uint8Array +): void { + const dir = path.dirname(filename) + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }) + } + fs.writeFileSync(filename, content) +} + +/** + * Delete every file and subdirectory. **The given directory must exist.** + * Pass an optional `skip` array to preserve files in the root directory. + */ +export function emptyDir(dir: string, skip?: string[]): void { + for (const file of fs.readdirSync(dir)) { + if (skip?.includes(file)) { + continue + } + const abs = path.resolve(dir, file) + // baseline is Node 12 so can't use rmSync :( + if (fs.lstatSync(abs).isDirectory()) { + emptyDir(abs) + fs.rmdirSync(abs) + } else { + fs.unlinkSync(abs) + } + } +} + +export function copyDir(srcDir: string, destDir: string): void { + fs.mkdirSync(destDir, { recursive: true }) + for (const file of fs.readdirSync(srcDir)) { + const srcFile = path.resolve(srcDir, file) + if (srcFile === destDir) { + continue + } + const destFile = path.resolve(destDir, file) + const stat = fs.statSync(srcFile) + if (stat.isDirectory()) { + copyDir(srcFile, destFile) + } else { + fs.copyFileSync(srcFile, destFile) + } + } +} + +export function ensureLeadingSlash(path: string): string { + return !path.startsWith('/') ? '/' + path : path +} + +export function ensureWatchedFile( + watcher: FSWatcher, + file: string | null, + root: string +): void { + if ( + file && + // only need to watch if out of root + !file.startsWith(root + '/') && + // some rollup plugins use null bytes for private resolved Ids + !file.includes('\0') && + fs.existsSync(file) + ) { + // resolve file to normalized system path + watcher.add(path.resolve(file)) + } +} + +interface ImageCandidate { + url: string + descriptor: string +} +const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g +export async function processSrcSet( + srcs: string, + replacer: (arg: ImageCandidate) => Promise +): Promise { + const imageCandidates: ImageCandidate[] = srcs + .split(',') + .map((s) => { + const [url, descriptor] = s + .replace(escapedSpaceCharacters, ' ') + .trim() + .split(' ', 2) + return { url, descriptor } + }) + .filter(({ url }) => !!url) + + const ret = await Promise.all( + imageCandidates.map(async ({ url, descriptor }) => { + return { + url: await replacer({ url, descriptor }), + descriptor + } + }) + ) + + const url = ret.reduce((prev, { url, descriptor }, index) => { + descriptor = descriptor || '' + return (prev += + url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`) + }, '') + + return url +} + +// based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221 +const nullSourceMap: RawSourceMap = { + names: [], + sources: [], + mappings: '', + version: 3 +} +export function combineSourcemaps( + filename: string, + sourcemapList: Array +): RawSourceMap { + if ( + sourcemapList.length === 0 || + sourcemapList.every((m) => m.sources.length === 0) + ) { + return { ...nullSourceMap } + } + + // We don't declare type here so we can convert/fake/map as RawSourceMap + let map //: SourceMap + let mapIndex = 1 + const useArrayInterface = + sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined + if (useArrayInterface) { + map = remapping(sourcemapList, () => null, true) + } else { + map = remapping( + sourcemapList[0], + function loader(sourcefile) { + if (sourcefile === filename && sourcemapList[mapIndex]) { + return sourcemapList[mapIndex++] + } else { + return { ...nullSourceMap } + } + }, + true + ) + } + if (!map.file) { + delete map.file + } + + return map as RawSourceMap +} + +export function unique(arr: T[]): T[] { + return Array.from(new Set(arr)) +} + +export interface Hostname { + // undefined sets the default behaviour of server.listen + host: string | undefined + // resolve to localhost when possible + name: string +} + +export function resolveHostname( + optionsHost: string | boolean | undefined +): Hostname { + let host: string | undefined + if ( + optionsHost === undefined || + optionsHost === false || + optionsHost === 'localhost' + ) { + // Use a secure default + host = '127.0.0.1' + } else if (optionsHost === true) { + // If passed --host in the CLI without arguments + host = undefined // undefined typically means 0.0.0.0 or :: (listen on all IPs) + } else { + host = optionsHost + } + + // Set host name to localhost when possible, unless the user explicitly asked for '127.0.0.1' + const name = + (optionsHost !== '127.0.0.1' && host === '127.0.0.1') || + host === '0.0.0.0' || + host === '::' || + host === undefined + ? 'localhost' + : host + + return { host, name } +} + +export function arraify(target: T | T[]): T[] { + return Array.isArray(target) ? target : [target] +} + +export const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm +export const singlelineCommentsRE = /\/\/.*/g diff --git a/node_modules/vite/tsconfig.base.json b/node_modules/vite/tsconfig.base.json new file mode 100644 index 0000000..ed56297 --- /dev/null +++ b/node_modules/vite/tsconfig.base.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "ES2018", + "moduleResolution": "node", + "strict": true, + "declaration": true, + "noImplicitOverride": true, + "noUnusedLocals": true, + "esModuleInterop": true + } +} diff --git a/node_modules/vite/types/alias.d.ts b/node_modules/vite/types/alias.d.ts new file mode 100644 index 0000000..aa70ec5 --- /dev/null +++ b/node_modules/vite/types/alias.d.ts @@ -0,0 +1,59 @@ +/** +Types from https://github.com/rollup/plugins/blob/master/packages/alias/types/index.d.ts +Inlined because the plugin is bundled. + +https://github.com/rollup/plugins/blob/master/LICENSE + +The MIT License (MIT) + +Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +import { PluginHooks } from 'rollup' + +export interface Alias { + find: string | RegExp + replacement: string + /** + * Instructs the plugin to use an alternative resolving algorithm, + * rather than the Rollup's resolver. + * @default null + */ + customResolver?: ResolverFunction | ResolverObject | null +} + +export type ResolverFunction = PluginHooks['resolveId'] + +export interface ResolverObject { + buildStart?: PluginHooks['buildStart'] + resolveId: ResolverFunction +} + +/** + * Specifies an `Object`, or an `Array` of `Object`, + * which defines aliases used to replace values in `import` or `require` statements. + * With either format, the order of the entries is important, + * in that the first defined rules are applied first. + * + * This is passed to \@rollup/plugin-alias as the "entries" field + * https://github.com/rollup/plugins/tree/master/packages/alias#entries + */ +export type AliasOptions = readonly Alias[] | { [find: string]: string } diff --git a/node_modules/vite/types/anymatch.d.ts b/node_modules/vite/types/anymatch.d.ts new file mode 100644 index 0000000..9204588 --- /dev/null +++ b/node_modules/vite/types/anymatch.d.ts @@ -0,0 +1,5 @@ +export type AnymatchFn = (testString: string) => boolean +export type AnymatchPattern = string | RegExp | AnymatchFn +type AnymatchMatcher = AnymatchPattern | AnymatchPattern[] + +export { AnymatchMatcher as Matcher } diff --git a/node_modules/vite/types/chokidar.d.ts b/node_modules/vite/types/chokidar.d.ts new file mode 100644 index 0000000..8882f02 --- /dev/null +++ b/node_modules/vite/types/chokidar.d.ts @@ -0,0 +1,218 @@ +// Inlined to avoid extra dependency (chokidar is bundled in the published build) + +// https://github.com/paulmillr/chokidar/blob/master/types/index.d.ts +// MIT Licensed https://github.com/paulmillr/chokidar/blob/master/LICENSE + +/** +The MIT License (MIT) + +Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker + +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. +*/ +/// + +import * as fs from 'fs' +import { Matcher } from './anymatch' + +export interface FSWatcher extends fs.FSWatcher { + options: WatchOptions + + /** + * Constructs a new FSWatcher instance with optional WatchOptions parameter. + */ + (options?: WatchOptions): void + + /** + * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one + * string. + */ + add(paths: string | ReadonlyArray): void + + /** + * Stop watching files, directories, or glob patterns. Takes an array of strings or just one + * string. + */ + unwatch(paths: string | ReadonlyArray): void + + /** + * 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 values are arrays of the names of the items contained in + * each directory. + */ + getWatched(): { + [directory: string]: string[] + } + + /** + * Removes all listeners from watched files. + */ + close(): Promise + + on( + event: 'add' | 'addDir' | 'change', + listener: (path: string, stats?: fs.Stats) => void + ): this + + on( + event: 'all', + listener: ( + eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', + path: string, + stats?: fs.Stats + ) => void + ): this + + /** + * Error occurred + */ + on(event: 'error', listener: (error: Error) => void): this + + /** + * Exposes the native Node `fs.FSWatcher events` + */ + on( + event: 'raw', + listener: (eventName: string, path: string, details: any) => void + ): this + + /** + * Fires when the initial scan is complete + */ + on(event: 'ready', listener: () => void): this + + on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this + + on(event: string, listener: (...args: any[]) => void): this +} + +export interface WatchOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched. If + * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, + * even if the process continues to run. + */ + persistent?: boolean + + /** + * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to + * be ignored. The whole relative or absolute path is tested, not just filename. If a function + * with two arguments is provided, it gets called twice per path - once with a single argument + * (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?: Matcher + + /** + * If set to `false` then `add`/`addDir` events are also emitted for matching paths while + * instantiating the watching as chokidar discovers these file paths (before the `ready` event). + */ + ignoreInitial?: boolean + + /** + * When `false`, only the symlinks themselves will be watched for changes instead of following + * the link references and bubbling events through the link's path. + */ + followSymlinks?: boolean + + /** + * The base directory from which watch `paths` are to be derived. Paths emitted with events will + * be relative to this. + */ + cwd?: string + + /** + * If set to true then the strings passed to .watch() and .add() are treated as literal path + * names, even if they look like globs. Default: false. + */ + disableGlobbing?: boolean + + /** + * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU + * utilization, consider setting this to `false`. It is typically necessary to **set this to + * `true` to successfully watch files over a network**, and it may be necessary to successfully + * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides + * the `useFsEvents` default. + */ + usePolling?: boolean + + /** + * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly + * and `fsevents` is available this supersedes the `usePolling` setting. When set to `false` on + * OS X, `usePolling: true` becomes the default. + */ + useFsEvents?: boolean + + /** + * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that + * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is + * provided even in cases where it wasn't already available from the underlying watch events. + */ + alwaysStat?: boolean + + /** + * If set, limits how many levels of subdirectories will be traversed. + */ + depth?: number + + /** + * Interval of file system polling. + */ + interval?: number + + /** + * Interval of file system polling for binary files. ([see list of binary extensions](https://gi + * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) + */ + binaryInterval?: number + + /** + * Indicates whether to watch files that don't have read permissions if possible. If watching + * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed + * silently. + */ + ignorePermissionErrors?: boolean + + /** + * `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts + * that occur when using editors that use "atomic writes" instead of writing directly to the + * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change` + * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you, + * you can override it by setting `atomic` to a custom value, in milliseconds. + */ + atomic?: boolean | number + + /** + * can be set to an object in order to adjust timing params: + */ + awaitWriteFinish?: + | { + /** + * Amount of time in milliseconds for a file size to remain constant before emitting its event. + */ + stabilityThreshold?: number + + /** + * File size polling interval. + */ + pollInterval?: number + } + | boolean +} diff --git a/node_modules/vite/types/commonjs.d.ts b/node_modules/vite/types/commonjs.d.ts new file mode 100644 index 0000000..fd9ab8a --- /dev/null +++ b/node_modules/vite/types/commonjs.d.ts @@ -0,0 +1,162 @@ +/** + * https://github.com/rollup/plugins/blob/master/packages/commonjs/types/index.d.ts + * + * This source code is licensed under the MIT license found in the + * LICENSE file at + * https://github.com/rollup/plugins/blob/master/LICENSE + */ +export interface RollupCommonJSOptions { + /** + * A minimatch pattern, or array of patterns, which specifies the files in + * the build the plugin should operate on. By default, all files with + * extension `".cjs"` or those in `extensions` are included, but you can narrow + * this list by only including specific files. These files will be analyzed + * and transpiled if either the analysis does not find ES module specific + * statements or `transformMixedEsModules` is `true`. + * @default undefined + */ + include?: string | RegExp | readonly (string | RegExp)[] + /** + * A minimatch pattern, or array of patterns, which specifies the files in + * the build the plugin should _ignore_. By default, all files with + * extensions other than those in `extensions` or `".cjs"` are ignored, but you + * can exclude additional files. See also the `include` option. + * @default undefined + */ + exclude?: string | RegExp | readonly (string | RegExp)[] + /** + * For extensionless imports, search for extensions other than .js in the + * order specified. Note that you need to make sure that non-JavaScript files + * are transpiled by another plugin first. + * @default [ '.js' ] + */ + extensions?: ReadonlyArray + /** + * If true then uses of `global` won't be dealt with by this plugin + * @default false + */ + ignoreGlobal?: boolean + /** + * If false, skips source map generation for CommonJS modules. This will improve performance. + * @default true + */ + sourceMap?: boolean + /** + * Some `require` calls cannot be resolved statically to be translated to + * imports. + * When this option is set to `false`, the generated code will either + * directly throw an error when such a call is encountered or, when + * `dynamicRequireTargets` is used, when such a call cannot be resolved with a + * configured dynamic require target. + * Setting this option to `true` will instead leave the `require` call in the + * code or use it as a fallback for `dynamicRequireTargets`. + * @default false + */ + ignoreDynamicRequires?: boolean + /** + * Instructs the plugin whether to enable mixed module transformations. This + * is useful in scenarios with modules that contain a mix of ES `import` + * statements and CommonJS `require` expressions. Set to `true` if `require` + * calls should be transformed to imports in mixed modules, or `false` if the + * `require` expressions should survive the transformation. The latter can be + * important if the code contains environment detection, or you are coding + * for an environment with special treatment for `require` calls such as + * ElectronJS. See also the `ignore` option. + * @default false + */ + transformMixedEsModules?: boolean + /** + * Sometimes you have to leave require statements unconverted. Pass an array + * containing the IDs or a `id => boolean` function. + * @default [] + */ + ignore?: ReadonlyArray | ((id: string) => boolean) + /** + * Controls how to render imports from external dependencies. By default, + * this plugin assumes that all external dependencies are CommonJS. This + * means they are rendered as default imports to be compatible with e.g. + * NodeJS where ES modules can only import a default export from a CommonJS + * dependency. + * + * If you set `esmExternals` to `true`, this plugins assumes that all + * external dependencies are ES modules and respect the + * `requireReturnsDefault` option. If that option is not set, they will be + * rendered as namespace imports. + * + * You can also supply an array of ids to be treated as ES modules, or a + * function that will be passed each external id to determine if it is an ES + * module. + * @default false + */ + esmExternals?: boolean | ReadonlyArray | ((id: string) => boolean) + /** + * Controls what is returned when requiring an ES module from a CommonJS file. + * When using the `esmExternals` option, this will also apply to external + * modules. By default, this plugin will render those imports as namespace + * imports i.e. + * + * ```js + * // input + * const foo = require('foo'); + * + * // output + * import * as foo from 'foo'; + * ``` + * + * However there are some situations where this may not be desired. + * For these situations, you can change Rollup's behaviour either globally or + * per module. To change it globally, set the `requireReturnsDefault` option + * to one of the following values: + * + * - `false`: This is the default, requiring an ES module returns its + * namespace. This is the only option that will also add a marker + * `__esModule: true` to the namespace to support interop patterns in + * CommonJS modules that are transpiled ES modules. + * - `"namespace"`: Like `false`, requiring an ES module returns its + * namespace, but the plugin does not add the `__esModule` marker and thus + * creates more efficient code. For external dependencies when using + * `esmExternals: true`, no additional interop code is generated. + * - `"auto"`: This is complementary to how `output.exports: "auto"` works in + * Rollup: If a module has a default export and no named exports, requiring + * that module returns the default export. In all other cases, the namespace + * is returned. For external dependencies when using `esmExternals: true`, a + * corresponding interop helper is added. + * - `"preferred"`: If a module has a default export, requiring that module + * always returns the default export, no matter whether additional named + * exports exist. This is similar to how previous versions of this plugin + * worked. Again for external dependencies when using `esmExternals: true`, + * an interop helper is added. + * - `true`: This will always try to return the default export on require + * without checking if it actually exists. This can throw at build time if + * there is no default export. This is how external dependencies are handled + * when `esmExternals` is not used. The advantage over the other options is + * that, like `false`, this does not add an interop helper for external + * dependencies, keeping the code lean. + * + * To change this for individual modules, you can supply a function for + * `requireReturnsDefault` instead. This function will then be called once for + * each required ES module or external dependency with the corresponding id + * and allows you to return different values for different modules. + * @default false + */ + requireReturnsDefault?: + | boolean + | 'auto' + | 'preferred' + | 'namespace' + | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace') + /** + * Some modules contain dynamic `require` calls, or require modules that + * contain circular dependencies, which are not handled well by static + * imports. Including those modules as `dynamicRequireTargets` will simulate a + * CommonJS (NodeJS-like) environment for them with support for dynamic and + * circular dependencies. + * + * Note: In extreme cases, this feature may result in some paths being + * rendered as absolute in the final bundle. The plugin tries to avoid + * exposing paths from the local machine, but if you are `dynamicRequirePaths` + * with paths that are far away from your project's folder, that may require + * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`. + */ + dynamicRequireTargets?: string | ReadonlyArray +} diff --git a/node_modules/vite/types/connect.d.ts b/node_modules/vite/types/connect.d.ts new file mode 100644 index 0000000..753569c --- /dev/null +++ b/node_modules/vite/types/connect.d.ts @@ -0,0 +1,111 @@ +// Inlined to avoid extra dependency +// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE + +// Type definitions for connect v3.4.0 +// Project: https://github.com/senchalabs/connect +// Definitions by: Maxime LUCE +// Evan Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as http from 'http' + +export namespace Connect { + export type ServerHandle = HandleFunction | http.Server + + export class IncomingMessage extends http.IncomingMessage { + originalUrl?: http.IncomingMessage['url'] + } + + export type NextFunction = (err?: any) => void + + export type SimpleHandleFunction = ( + req: IncomingMessage, + res: http.ServerResponse + ) => void + export type NextHandleFunction = ( + req: IncomingMessage, + res: http.ServerResponse, + next: NextFunction + ) => void + export type ErrorHandleFunction = ( + err: any, + req: IncomingMessage, + res: http.ServerResponse, + next: NextFunction + ) => void + export type HandleFunction = + | SimpleHandleFunction + | NextHandleFunction + | ErrorHandleFunction + + export interface ServerStackItem { + route: string + handle: ServerHandle + } + + export interface Server extends NodeJS.EventEmitter { + (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void + + route: string + stack: ServerStackItem[] + + /** + * Utilize the given middleware `handle` to the given `route`, + * defaulting to _/_. This "route" is the mount-point for the + * middleware, when given a value other than _/_ the middleware + * is only effective when that segment is present in the request's + * pathname. + * + * For example if we were to mount a function at _/admin_, it would + * be invoked on _/admin_, and _/admin/settings_, however it would + * not be invoked for _/_, or _/posts_. + */ + use(fn: NextHandleFunction): Server + use(fn: HandleFunction): Server + use(route: string, fn: NextHandleFunction): Server + use(route: string, fn: HandleFunction): Server + + /** + * Handle server requests, punting them down + * the middleware stack. + */ + handle( + req: http.IncomingMessage, + res: http.ServerResponse, + next: Function + ): void + + /** + * Listen for connections. + * + * This method takes the same arguments + * as node's `http.Server#listen()`. + * + * HTTP and HTTPS: + * + * If you run your application both as HTTP + * and HTTPS you may wrap them individually, + * since your Connect "server" is really just + * a JavaScript `Function`. + * + * var connect = require('connect') + * , http = require('http') + * , https = require('https'); + * + * var app = connect(); + * + * http.createServer(app).listen(80); + * https.createServer(options, app).listen(443); + */ + listen( + port: number, + hostname?: string, + backlog?: number, + callback?: Function + ): http.Server + listen(port: number, hostname?: string, callback?: Function): http.Server + listen(path: string, callback?: Function): http.Server + listen(handle: any, listeningListener?: Function): http.Server + } +} diff --git a/node_modules/vite/types/customEvent.d.ts b/node_modules/vite/types/customEvent.d.ts new file mode 100644 index 0000000..c38a4ac --- /dev/null +++ b/node_modules/vite/types/customEvent.d.ts @@ -0,0 +1,5 @@ +// See https://stackoverflow.com/a/63549561. +export type CustomEventName = (T extends `vite:${T}` + ? never + : T) & + (`vite:${T}` extends T ? never : T) diff --git a/node_modules/vite/types/dynamicImportVars.d.ts b/node_modules/vite/types/dynamicImportVars.d.ts new file mode 100644 index 0000000..99f1b5c --- /dev/null +++ b/node_modules/vite/types/dynamicImportVars.d.ts @@ -0,0 +1,17 @@ +export interface RollupDynamicImportVarsOptions { + /** + * Files to include in this plugin (default all). + * @default [] + */ + include?: string | RegExp | (string | RegExp)[] + /** + * Files to exclude in this plugin (default none). + * @default [] + */ + exclude?: string | RegExp | (string | RegExp)[] + /** + * By default, the plugin quits the build process when it encounters an error. If you set this option to true, it will throw a warning instead and leave the code untouched. + * @default false + */ + warnOnError?: boolean +} diff --git a/node_modules/vite/types/hmrPayload.d.ts b/node_modules/vite/types/hmrPayload.d.ts new file mode 100644 index 0000000..2fbed3a --- /dev/null +++ b/node_modules/vite/types/hmrPayload.d.ts @@ -0,0 +1,57 @@ +export type HMRPayload = + | ConnectedPayload + | UpdatePayload + | FullReloadPayload + | CustomPayload + | ErrorPayload + | PrunePayload + +export interface ConnectedPayload { + type: 'connected' +} + +export interface UpdatePayload { + type: 'update' + updates: Update[] +} + +export interface Update { + type: 'js-update' | 'css-update' + path: string + acceptedPath: string + timestamp: number +} + +export interface PrunePayload { + type: 'prune' + paths: string[] +} + +export interface FullReloadPayload { + type: 'full-reload' + path?: string +} + +export interface CustomPayload { + type: 'custom' + event: string + data?: any +} + +export interface ErrorPayload { + type: 'error' + err: { + [name: string]: any + message: string + stack: string + id?: string + frame?: string + plugin?: string + pluginCode?: string + loc?: { + file?: string + line: number + column: number + } + } +} diff --git a/node_modules/vite/types/http-proxy.d.ts b/node_modules/vite/types/http-proxy.d.ts new file mode 100644 index 0000000..3ad701f --- /dev/null +++ b/node_modules/vite/types/http-proxy.d.ts @@ -0,0 +1,242 @@ +// Inlined to avoid extra dependency +// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE + +// Type definitions for node-http-proxy 1.17 +// Project: https://github.com/nodejitsu/node-http-proxy +// Definitions by: Maxime LUCE +// Florian Oellerich +// Daniel Schmidt +// Jordan Abreu +// Samuel Bodin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import * as net from 'net' +import * as http from 'http' +import * as events from 'events' +import * as url from 'url' +import * as stream from 'stream' + +export namespace HttpProxy { + export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed + + export type ProxyTargetUrl = string | Partial + + export interface ProxyTargetDetailed { + host: string + port: number + protocol?: string + hostname?: string + socketPath?: string + key?: string + passphrase?: string + pfx?: Buffer | string + cert?: string + ca?: string + ciphers?: string + secureProtocol?: string + } + + export type ErrorCallback = ( + err: Error, + req: http.IncomingMessage, + res: http.ServerResponse, + target?: ProxyTargetUrl + ) => void + + export class Server extends events.EventEmitter { + /** + * Creates the proxy server with specified options. + * @param options - Config object passed to the proxy + */ + constructor(options?: ServerOptions) + + /** + * Used for proxying regular HTTP(S) requests + * @param req - Client request. + * @param res - Client response. + * @param options - Additionnal options. + */ + web( + req: http.IncomingMessage, + res: http.ServerResponse, + options?: ServerOptions, + callback?: ErrorCallback + ): void + + /** + * Used for proxying regular HTTP(S) requests + * @param req - Client request. + * @param socket - Client socket. + * @param head - Client head. + * @param options - Additional options. + */ + ws( + req: http.IncomingMessage, + socket: unknown, + head: unknown, + options?: ServerOptions, + callback?: ErrorCallback + ): void + + /** + * A function that wraps the object in a webserver, for your convenience + * @param port - Port to listen on + */ + listen(port: number): Server + + /** + * A function that closes the inner webserver and stops listening on given port + */ + close(callback?: () => void): void + + /** + * Creates the proxy server with specified options. + * @param options - Config object passed to the proxy + * @returns Proxy object with handlers for `ws` and `web` requests + */ + static createProxyServer(options?: ServerOptions): Server + + /** + * Creates the proxy server with specified options. + * @param options - Config object passed to the proxy + * @returns Proxy object with handlers for `ws` and `web` requests + */ + static createServer(options?: ServerOptions): Server + + /** + * Creates the proxy server with specified options. + * @param options - Config object passed to the proxy + * @returns Proxy object with handlers for `ws` and `web` requests + */ + static createProxy(options?: ServerOptions): Server + + addListener(event: string, listener: () => void): this + on(event: string, listener: () => void): this + on(event: 'error', listener: ErrorCallback): this + on( + event: 'start', + listener: ( + req: http.IncomingMessage, + res: http.ServerResponse, + target: ProxyTargetUrl + ) => void + ): this + on( + event: 'proxyReq', + listener: ( + proxyReq: http.ClientRequest, + req: http.IncomingMessage, + res: http.ServerResponse, + options: ServerOptions + ) => void + ): this + on( + event: 'proxyRes', + listener: ( + proxyRes: http.IncomingMessage, + req: http.IncomingMessage, + res: http.ServerResponse + ) => void + ): this + on( + event: 'proxyReqWs', + listener: ( + proxyReq: http.ClientRequest, + req: http.IncomingMessage, + socket: net.Socket, + options: ServerOptions, + head: any + ) => void + ): this + on( + event: 'econnreset', + listener: ( + err: Error, + req: http.IncomingMessage, + res: http.ServerResponse, + target: ProxyTargetUrl + ) => void + ): this + on( + event: 'end', + listener: ( + req: http.IncomingMessage, + res: http.ServerResponse, + proxyRes: http.IncomingMessage + ) => void + ): this + on( + event: 'close', + listener: ( + proxyRes: http.IncomingMessage, + proxySocket: net.Socket, + proxyHead: any + ) => void + ): this + + once(event: string, listener: () => void): this + removeListener(event: string, listener: () => void): this + removeAllListeners(event?: string): this + getMaxListeners(): number + setMaxListeners(n: number): this + listeners(event: string): Array<() => void> + emit(event: string, ...args: any[]): boolean + listenerCount(type: string): number + } + + export interface ServerOptions { + /** URL string to be parsed with the url module. */ + target?: ProxyTarget + /** URL string to be parsed with the url module. */ + forward?: ProxyTargetUrl + /** Object to be passed to http(s).request. */ + agent?: any + /** Object to be passed to https.createServer(). */ + ssl?: any + /** If you want to proxy websockets. */ + ws?: boolean + /** Adds x- forward headers. */ + xfwd?: boolean + /** Verify SSL certificate. */ + secure?: boolean + /** Explicitly specify if we are proxying to another proxy. */ + toProxy?: boolean + /** Specify whether you want to prepend the target's path to the proxy path. */ + prependPath?: boolean + /** Specify whether you want to ignore the proxy path of the incoming request. */ + ignorePath?: boolean + /** Local interface string to bind for outgoing connections. */ + localAddress?: string + /** Changes the origin of the host header to the target URL. */ + changeOrigin?: boolean + /** specify whether you want to keep letter case of response header key */ + preserveHeaderKeyCase?: boolean + /** Basic authentication i.e. 'user:password' to compute an Authorization header. */ + auth?: string + /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */ + hostRewrite?: string + /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */ + autoRewrite?: boolean + /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */ + protocolRewrite?: string + /** rewrites domain of set-cookie headers. */ + cookieDomainRewrite?: false | string | { [oldDomain: string]: string } + /** rewrites path of set-cookie headers. Default: false */ + cookiePathRewrite?: false | string | { [oldPath: string]: string } + /** object with extra headers to be added to target requests. */ + headers?: { [header: string]: string } + /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */ + proxyTimeout?: number + /** Timeout (in milliseconds) for incoming requests */ + timeout?: number + /** Specify whether you want to follow redirects. Default: false */ + followRedirects?: boolean + /** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */ + selfHandleResponse?: boolean + /** Buffer */ + buffer?: stream.Stream + } +} diff --git a/node_modules/vite/types/importMeta.d.ts b/node_modules/vite/types/importMeta.d.ts new file mode 100644 index 0000000..7a96d76 --- /dev/null +++ b/node_modules/vite/types/importMeta.d.ts @@ -0,0 +1,69 @@ +interface ImportMeta { + url: string + + readonly hot?: { + readonly data: any + + accept(): void + accept(cb: (mod: any) => void): void + accept(dep: string, cb: (mod: any) => void): void + accept(deps: readonly string[], cb: (mods: any[]) => void): void + + /** + * @deprecated + */ + acceptDeps(): never + + dispose(cb: (data: any) => void): void + decline(): void + invalidate(): void + + on: { + ( + event: 'vite:beforeUpdate', + cb: (payload: import('./hmrPayload').UpdatePayload) => void + ): void + ( + event: 'vite:beforePrune', + cb: (payload: import('./hmrPayload').PrunePayload) => void + ): void + ( + event: 'vite:beforeFullReload', + cb: (payload: import('./hmrPayload').FullReloadPayload) => void + ): void + ( + event: 'vite:error', + cb: (payload: import('./hmrPayload').ErrorPayload) => void + ): void + ( + event: import('./customEvent').CustomEventName, + cb: (data: any) => void + ): void + } + } + + readonly env: ImportMetaEnv + + glob(pattern: string): Record< + string, + () => Promise<{ + [key: string]: any + }> + > + + globEager(pattern: string): Record< + string, + { + [key: string]: any + } + > +} + +interface ImportMetaEnv { + [key: string]: string | boolean | undefined + BASE_URL: string + MODE: string + DEV: boolean + PROD: boolean + SSR: boolean +} diff --git a/node_modules/vite/types/shims.d.ts b/node_modules/vite/types/shims.d.ts new file mode 100644 index 0000000..8a0e94e --- /dev/null +++ b/node_modules/vite/types/shims.d.ts @@ -0,0 +1,119 @@ +declare module 'connect' { + const connect: () => any + export = connect +} + +declare module 'cors' { + function cors(options: any): any + export = cors +} + +declare module 'selfsigned' { + export function generate(attrs: any, options: any, done?: any): any +} + +declare module 'http-proxy' { + const proxy: any + export = proxy +} + +declare module 'acorn-class-fields' { + const plugin: any + export = plugin +} + +declare module 'acorn-static-class-features' { + const plugin: any + export default plugin +} + +declare module 'acorn-numeric-separator' { + const plugin: any + export default plugin +} + +declare module 'connect-history-api-fallback' { + const plugin: any + export = plugin +} + +declare module 'launch-editor-middleware' { + const plugin: any + export = plugin +} + +declare module 'merge-source-map' { + export default function merge(oldMap: object, newMap: object): object +} + +declare module 'postcss-load-config' { + import { ProcessOptions, Plugin } from 'postcss' + function load( + inline: any, + root: string + ): Promise<{ + options: ProcessOptions + plugins: Plugin[] + }> + export = load +} + +declare module 'postcss-import' { + import { Plugin } from 'postcss' + const plugin: (options: { + resolve: ( + id: string, + basedir: string, + importOptions: any + ) => string | string[] | Promise + }) => Plugin + export = plugin +} + +declare module 'postcss-modules' { + import { Plugin } from 'postcss' + const plugin: (options: any) => Plugin + export = plugin +} + +declare module '@rollup/plugin-dynamic-import-vars' { + import { Plugin } from 'rollup' + + interface Options { + include?: string | RegExp | (string | RegExp)[] + exclude?: string | RegExp | (string | RegExp)[] + warnOnError?: boolean + } + + const p: (o?: Options) => Plugin + export default p +} + +declare module 'rollup-plugin-web-worker-loader' { + import { Plugin } from 'rollup' + + interface Options { + targetPlatform?: string + pattern?: RegExp + extensions?: string[] + sourcemap?: boolean + inline?: boolean + } + + const p: (o?: Options) => Plugin + export default p +} + +declare module 'minimatch' { + function match(path: string, pattern: string): boolean + export default match +} + +declare module 'compression' { + function compression(): any + export default compression +} + +// LESS' types somewhat references this which doesn't make sense in Node, +// so we have to shim it +declare interface HTMLLinkElement {} diff --git a/node_modules/vite/types/terser.d.ts b/node_modules/vite/types/terser.d.ts new file mode 100644 index 0000000..44c7398 --- /dev/null +++ b/node_modules/vite/types/terser.d.ts @@ -0,0 +1,209 @@ +// Modified and inlined to avoid extra dependency +// Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts +// BSD Licensed https://github.com/terser/terser/blob/master/LICENSE + +/* +Terser is released under the BSD license: + +Copyright 2012-2018 (c) Mihai Bazon + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, +OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. +*/ + +export namespace Terser { + export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 + + export interface ParseOptions { + bare_returns?: boolean + ecma?: ECMA + html5_comments?: boolean + shebang?: boolean + } + + export interface CompressOptions { + arguments?: boolean + arrows?: boolean + booleans_as_integers?: boolean + booleans?: boolean + collapse_vars?: boolean + comparisons?: boolean + computed_props?: boolean + conditionals?: boolean + dead_code?: boolean + defaults?: boolean + directives?: boolean + drop_console?: boolean + drop_debugger?: boolean + ecma?: ECMA + evaluate?: boolean + expression?: boolean + global_defs?: object + hoist_funs?: boolean + hoist_props?: boolean + hoist_vars?: boolean + ie8?: boolean + if_return?: boolean + inline?: boolean | InlineFunctions + join_vars?: boolean + keep_classnames?: boolean | RegExp + keep_fargs?: boolean + keep_fnames?: boolean | RegExp + keep_infinity?: boolean + loops?: boolean + module?: boolean + negate_iife?: boolean + passes?: number + properties?: boolean + pure_funcs?: string[] + pure_getters?: boolean | 'strict' + reduce_funcs?: boolean + reduce_vars?: boolean + sequences?: boolean | number + side_effects?: boolean + switches?: boolean + toplevel?: boolean + top_retain?: null | string | string[] | RegExp + typeofs?: boolean + unsafe_arrows?: boolean + unsafe?: boolean + unsafe_comps?: boolean + unsafe_Function?: boolean + unsafe_math?: boolean + unsafe_symbols?: boolean + unsafe_methods?: boolean + unsafe_proto?: boolean + unsafe_regexp?: boolean + unsafe_undefined?: boolean + unused?: boolean + } + + export enum InlineFunctions { + Disabled = 0, + SimpleFunctions = 1, + WithArguments = 2, + WithArgumentsAndVariables = 3 + } + + export interface MangleOptions { + eval?: boolean + keep_classnames?: boolean | RegExp + keep_fnames?: boolean | RegExp + module?: boolean + properties?: boolean | ManglePropertiesOptions + reserved?: string[] + safari10?: boolean + toplevel?: boolean + } + + export interface ManglePropertiesOptions { + builtins?: boolean + debug?: boolean + keep_quoted?: boolean | 'strict' + regex?: RegExp | string + reserved?: string[] + } + + export interface FormatOptions { + ascii_only?: boolean + beautify?: boolean + braces?: boolean + comments?: + | boolean + | 'all' + | 'some' + | RegExp + | (( + node: any, + comment: { + value: string + type: 'comment1' | 'comment2' | 'comment3' | 'comment4' + pos: number + line: number + col: number + } + ) => boolean) + ecma?: ECMA + ie8?: boolean + indent_level?: number + indent_start?: number + inline_script?: boolean + keep_quoted_props?: boolean + max_line_len?: number | false + preamble?: string + preserve_annotations?: boolean + quote_keys?: boolean + quote_style?: OutputQuoteStyle + safari10?: boolean + semicolons?: boolean + shebang?: boolean + shorthand?: boolean + source_map?: SourceMapOptions + webkit?: boolean + width?: number + wrap_iife?: boolean + wrap_func_args?: boolean + } + + export enum OutputQuoteStyle { + PreferDouble = 0, + AlwaysSingle = 1, + AlwaysDouble = 2, + AlwaysOriginal = 3 + } + + export interface MinifyOptions { + compress?: boolean | CompressOptions + ecma?: ECMA + ie8?: boolean + keep_classnames?: boolean | RegExp + keep_fnames?: boolean | RegExp + mangle?: boolean | MangleOptions + module?: boolean + nameCache?: object + format?: FormatOptions + /** @deprecated use format instead */ + output?: FormatOptions + parse?: ParseOptions + safari10?: boolean + sourceMap?: boolean | SourceMapOptions + toplevel?: boolean + } + + export interface MinifyOutput { + code?: string + map?: object | string + } + + export interface SourceMapOptions { + /** Source map object, 'inline' or source map file content */ + content?: object | string + includeSources?: boolean + filename?: string + root?: string + url?: string | 'inline' + } +} diff --git a/node_modules/vue/LICENSE b/node_modules/vue/LICENSE new file mode 100644 index 0000000..15f1f7e --- /dev/null +++ b/node_modules/vue/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018-present, Yuxi (Evan) You + +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/vue/README.md b/node_modules/vue/README.md new file mode 100644 index 0000000..a98bd99 --- /dev/null +++ b/node_modules/vue/README.md @@ -0,0 +1,54 @@ +# vue + +## Which dist file to use? + +### From CDN or without a Bundler + +- **`vue(.runtime).global(.prod).js`**: + - For direct use via `